问:
Will code after a jQuery ready() be guarantied to run before the ready function?
As titled!

ready() specifies that it loads after the DOM has been initialized and is ready for JS execution. However, I'm unsure of how that interacts with the JS itself!

If I have some JavaScript with the general format:

let functocall = () => {
    alert("Bad ending!");
};

// ...

$(document).ready(() => {
    functocall();
});

// ...

functocall = () => {
    console.log("Safe!");
};
```

(note that the JS is loaded via a

答: No. We don't know when the whole code is executed. It could be loaded after the document is ready, so the ready promise is resolved and the code will execute immediately.

Body:
As titled!

ready() specifies that it loads after the DOM has been initialized and is ready for JS execution. However, I'm unsure of how that interacts with the JS itself!

If I have some JavaScript with the general format:

let functocall = () => {
    alert("Bad ending!");
};

// ...

$(document).ready(() => {
    functocall();
});

// ...

functocall = () => {
    console.log("Safe!");
};

(note that the JS is loaded via a


来源: stackexchange

问:
Opaque C structs: various ways to declare them
I've seen both of the following two styles of declaring opaque types in C APIs. What are the various ways to declare opaque structs/pointers in C? Is there any clear advantage to using one style over the other?

Option 1

```<code>// foo.h
typedef struct foo * fooRef;
void doStuff(fooRef f);

// foo.c
struct foo {
    int x;
    int y;
};
</code>```

Option 2

```<code>// foo.h
typedef struct _foo foo;
void doStuff(foo *f);

// foo.c
struct _foo {
    int x;
    int y;
};
</code>```

答:
Option 3: Give people choice

/*  foo.h  */

typedef struct PersonInstance PersonInstance;

typedef struct PersonInstance * PersonHandle;

typedef const struct PersonInstance * ConstPersonHandle;

void saveStuff (PersonHandle person);

int readStuff (ConstPersonHandle person);

...

/*  foo.c  */

struct PersonInstance {
    int a;
    int b;
    ...
};

...
```

ContentLicense: CC BY-SA 4.0

Body:
I've seen both of the following two styles of declaring opaque types in C APIs. What are the various ways to declare opaque structs/pointers in C? Is there any clear advantage to using one style over the other?

Option 1

// foo.h
typedef struct foo * fooRef;
void doStuff(fooRef f);

// foo.c
struct foo {
    int x;
    int y;
};

Option 2

// foo.h
typedef struct _foo foo;
void doStuff(foo *f);

// foo.c
struct _foo {
    int x;
    int y;
};


问:
Delete row from databricks table if not existing in incoming dataset
I have an delta table in Databricks. Let's call it df for this instance. A mocked data set below.

```<code>df
+---+---+----+
## |id|label|
## +---+----+
## |  1| foo|
## |  2| bar|
## +---+----+
</code>```

I'm using incoming data sets (let's call it new_df) to merge into df.

```<code>new_df
+---+---+----+
## |id|label|
## +---+----+
## |  2| bar|
## |  3| fob|
## +---+----+
</code>```

Code I'm using to merge:

```<code>MERGE INTO default.df AS df
USING new_df
ON df.id = new_df.id

WHEN MATCHED THEN
  UPDATE SET *

WHEN NOT MATCHED THEN
    INSERT (id, label)
    VALUES (new_df.id, new_df.label);
</code>```

This works pretty well and gives me a result like this:

```<code>+---+---+----+
## |id|label|
## +---+----+
## |  1| foo|
## |  2| bar|
## |  3| fob|
## +---+----+
</code>```

The only issue is that I'd like for row [1, foo] to be removed since the data is no longer in new_df (and is not 'active'). What would be the best way to achieve this? Please note that Databricks ANSI SQL merge command is limited and doesn't have options such as WHEN NOT MATCHED BY SOURCE/TARGET. Ideally the solution is all done in Databricks Spark SQL but I'm open to suggestions in Pyspark as well. Thanks in advance!

答:
I ended up having to use another SQL command. It seems that because of ANSI SQL being limited (compared to TSQL, etc.), the actions needed to be broken down. The second part of my code became something like this:</p>
```<code>```
DELETE FROM
  df
WHERE
  NOT EXISTS(
    SELECT
      id
    FROM
      df2
    WHERE
      df2.id = df.id
  )
</code>```

Body:
I have an delta table in Databricks. Let's call it df for this instance. A mocked data set below.

df
+---+---+----+
## |id|label|
## +---+----+
## |  1| foo|
## |  2| bar|
## +---+----+

I'm using incoming data sets (let's call it new_df) to merge into df.

new_df
+---+---+----+
## |id|label|
## +---+----+
## |  2| bar|
## |  3| fob|
## +---+----+

Code I'm using to merge:

MERGE INTO default.df AS df
USING new_df
ON df.id = new_df.id

WHEN MATCHED THEN
  UPDATE SET *

WHEN NOT MATCHED THEN
    INSERT (id, label)
    VALUES (new_df.id, new_df.label);

This works pretty well and gives me a result like this:

+---+---+----+
## |id|label|
## +---+----+
## |  1| foo|
## |  2| bar|
## |  3| fob|
## +---+----+

The only issue is that I'd like for row [1, foo] to be removed since the data is no longer in new_df (and is not 'active'). What would be the best way to achieve this? Please note that Databricks ANSI SQL merge command is limited and doesn't have options such as WHEN NOT MATCHED BY SOURCE/TARGET. Ideally the solution is all done in Databricks Spark SQL but I'm open to suggestions in Pyspark as well. Thanks in advance!

Body:
I ended up having to use another SQL command. It seems that because of ANSI SQL being limited (compared to TSQL, etc.), the actions needed to be broken down. The second part of my code became something like this:

```
DELETE FROM
  df
WHERE
  NOT EXISTS(
    SELECT
      id
    FROM
      df2
    WHERE
      df2.id = df.id
  )


问:
ISet vs HashSet in C#
I just have a general question as I am a C# 'newb'. Is there a reason to use ISet over HashSet when creating a Set?

```<code>class Program {

public static void Main(string[] args)
{
ISet<string> myHashSet = new HashSet<string>();
myHashSet.Add("first");
myHashSet.Add("second");
myHashSet.Add("third");

// vs.

HashSet<string> myHashSet = new HashSet<string>();
myHashSet.Add("first");
myHashSet.Add("second");
myHashSet.Add("third");

}

}
</code>```

I know ISet is in an 'interface' of HashSet I just don't understand why you would use ISet over HashSet or what difference it would make?

答:
In the simple code you have submitted it is difficult to see the difference between using ISet and HashSet.

But consider a different situation, where instead of the code being in the Main() but in a method and the set data is passed in. Then the method would have the signature similar to :

```<code>void AddItems(ISet<string> repository)
{
    repository.Add("first");
    ...
}
</code>```

The important thing to notice is that the method AddItems is responsible for Adding Items to the repository, but is not responsible for creating the repository. That responsibility is left to another component. That concrete instance of the repository is determined by the context in which the Add Item method is called. In real executable code, the underlying ISet<string> might be a HashSet<string>; in test code it might be a mock object exposing a ISet<string> interface. So using the abstraction ISet<string> in the method allows it to be used in very different contexts.

Title: ISet vs HashSet in C#

Body:
I just have a general question as I am a C# 'newb'. Is there a reason to use ISet over HashSet when creating a Set?

class Program {

public static void Main(string[] args)
{
ISet<string> myHashSet = new HashSet<string>();
myHashSet.Add("first");
myHashSet.Add("second");
myHashSet.Add("third");

// vs.

HashSet<string> myHashSet = new HashSet<string>();
myHashSet.Add("first");
myHashSet.Add("second");
myHashSet.Add("third");

}

}

I know ISet is in an 'interface' of HashSet I just don't understand why you would use ISet over HashSet or what difference it would make?

Body:
In the simple code you have submitted it is difficult to see the difference between using ISet and HashSet.

But consider a different situation, where instead of the code being in the Main() but in a method and the set data is passed in. Then the method would have the signature similar to :

void AddItems(ISet<string> repository)
{
    repository.Add("first");
    ...
}

The important thing to notice is that the method AddItems is responsible for Adding Items to the repository, but is not responsible for creating the repository. That responsibility is left to another component. That concrete instance of the repository is determined by the context in which the Add Item method is called. In real executable code, the underlying ISet<string> might be a HashSet<string>; in test code it might be a mock object exposing a ISet<string> interface. So using the abstraction ISet<string> in the method allows it to be used in very different contexts.


问:
What is the difference between zipWithUniqueId and zipWithIndex in pyspark?
The documentation says that one triggers a spark job and the other one does not. I am not sure I understand what that means. Could you help me understand the difference between the two?</p>

答:
The source of truth comes from latest code:

```<code>  /**
   * Zips this RDD with its element indices. The ordering is first based on the partition index
   * and then the ordering of items within each partition. So the first item in the first
   * partition gets index 0, and the last item in the last partition receives the largest index.
   *
   * This is similar to Scala's zipWithIndex but it uses Long instead of Int as the index type.
   * This method needs to trigger a spark job when this RDD contains more than one partitions.
   *
   * @note Some RDDs, such as those returned by groupBy(), do not guarantee order of
   * elements in a partition. The index assigned to each element is therefore not guaranteed,
   * and may even change if the RDD is reevaluated. If a fixed ordering is required to guarantee
   * the same index assignments, you should sort the RDD with sortByKey() or save it to a file.
   */
  def zipWithIndex(): RDD[(T, Long)] = withScope {
    new ZippedWithIndexRDD(this)
  }

  /**
   * Zips this RDD with generated unique Long ids. Items in the kth partition will get ids k, n+k,
   * 2*n+k, ..., where n is the number of partitions. So there may exist gaps, but this method
   * won't trigger a spark job, which is different from [[org.apache.spark.rdd.RDD#zipWithIndex]].
   *
   * @note Some RDDs, such as those returned by groupBy(), do not guarantee order of
   * elements in a partition. The unique ID assigned to each element is therefore not guaranteed,
   * and may even change if the RDD is reevaluated. If a fixed ordering is required to guarantee
   * the same index assignments, you should sort the RDD with sortByKey() or save it to a file.
   */
  def zipWithUniqueId(): RDD[(T, Long)]
</code>```

https://github.com/apache/spark/blob/master/core/src/main/scala/org/apache/spark/rdd/RDD.scala#L1396

Body:
The source of truth comes from latest code:

  /**
   * Zips this RDD with its element indices. The ordering is first based on the partition index
   * and then the ordering of items within each partition. So the first item in the first
   * partition gets index 0, and the last item in the last partition receives the largest index.
   *
   * This is similar to Scala's zipWithIndex but it uses Long instead of Int as the index type.
   * This method needs to trigger a spark job when this RDD contains more than one partitions.
   *
   * @note Some RDDs, such as those returned by groupBy(), do not guarantee order of
   * elements in a partition. The index assigned to each element is therefore not guaranteed,
   * and may even change if the RDD is reevaluated. If a fixed ordering is required to guarantee
   * the same index assignments, you should sort the RDD with sortByKey() or save it to a file.
   */
  def zipWithIndex(): RDD[(T, Long)] = withScope {
    new ZippedWithIndexRDD(this)
  }

  /**
   * Zips this RDD with generated unique Long ids. Items in the kth partition will get ids k, n+k,
   * 2*n+k, ..., where n is the number of partitions. So there may exist gaps, but this method
   * won't trigger a spark job, which is different from [[org.apache.spark.rdd.RDD#zipWithIndex]].
   *
   * @note Some RDDs, such as those returned by groupBy(), do not guarantee order of
   * elements in a partition. The unique ID assigned to each element is therefore not guaranteed,
   * and may even change if the RDD is reevaluated. If a fixed ordering is required to guarantee
   * the same index assignments, you should sort the RDD with sortByKey() or save it to a file.
   */
  def zipWithUniqueId(): RDD[(T, Long)]

https://github.com/apache/spark/blob/master/core/src/main/scala/org/apache/spark/rdd/RDD.scala#L1396


问:
Angular Service, no return when API is used
I am trying Angular service for the first time, and I am having trouble while I use the API in the service. When I call the regular method, I get a return value, but when I call the method that uses API, I don't get any return value.

Here's my app.component.ts file.

```<code>import { Component, OnInit } from '@angular/core;
enter code hereimport { DataService } from './data.service;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{
  _artists: Array<any>
  _produceArray: Array<any>
  title = 'APIAssignmentPartBandCVersion2';

  constructor(private list: DataService) { }
  ngOnInit(): void {
      this._artists = this.list.getList()
      this._produceArray = this.list.getProduce()
      console.log(this._produceArray, "hellohello")
      console.log(this._artists, "artistArray")
    }
}
</code>```

Here's my data.service file.

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
const BASE_URL = 'https://localhost:44308/api/Store/';

@Injectable({
  providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }

_producesArray: Array<any>;
_suppliersArray: Array<any>;
_producesupplierArray: Array<any>;
_errorMessage: String = "";

getList(){
    return[
      {'grade':1, 'name':'Davido', 'country':'Nigeria'},
      {'grade':2, 'name':'Burna Boy', 'country':'Nigeria'},
      {'grade':3, 'name':'Diamondz Platinum', 'country':'Tanzania'},
      {'grade':4, 'name':'Sarkodie', 'country':'Ghana'},
      {'grade':5, 'name':'Mr. Eazi', 'country':'Nigeria'}
    ];
  }

getProduce(){
  this.http.get<any>(BASE_URL + "produce/").subscribe(data => {
    this._producesArray = data;
    this._errorMessage = data["errorMessage"];
    console.log(data)
},
error =>{
    this._errorMessage = JSON.stringify(error);
})
return this._producesArray
}
}
</code>```

Thank you.

答:
the problem is that - you call the API which is asynchronic action which means is moving on to the next line of code while this request is execute...
so you return _producesArray before it's really filled with data.
what do you need to do is simply return the observable like this:

```<code> return this.http.get<any>(BASE_URL + "produce/")
</code>```

and make the subscribe inside the component

```<code>this.list.getProduce().subscribe(...)
</code>```

good luck :)

Body:
I am trying Angular service for the first time, and I am having trouble while I use the API in the service. When I call the regular method, I get a return value, but when I call the method that uses API, I don't get any return value.

Here's my app.component.ts file.

import { Component, OnInit } from '@angular/core;
enter code hereimport { DataService } from './data.service;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{
  _artists: Array<any>
  _produceArray: Array<any>
  title = 'APIAssignmentPartBandCVersion2';

  constructor(private list: DataService) { }
  ngOnInit(): void {
      this._artists = this.list.getList()
      this._produceArray = this.list.getProduce()
      console.log(this._produceArray, "hellohello")
      console.log(this._artists, "artistArray")
    }
}

Here's my data.service file.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
const BASE_URL = 'https://localhost:44308/api/Store/';

@Injectable({
  providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }

_producesArray: Array<any>;
_suppliersArray: Array<any>;
_producesupplierArray: Array<any>;
_errorMessage: String = "";

getList(){
    return[
      {'grade':1, 'name':'Davido', 'country':'Nigeria'},
      {'grade':2, 'name':'Burna Boy', 'country':'Nigeria'},
      {'grade':3, 'name':'Diamondz Platinum', 'country':'Tanzania'},
      {'grade':4, 'name':'Sarkodie', 'country':'Ghana'},
      {'grade':5, 'name':'Mr. Eazi', 'country':'Nigeria'}
    ];
  }

getProduce(){
  this.http.get<any>(BASE_URL + "produce/").subscribe(data => {
    this._producesArray = data;
    this._errorMessage = data["errorMessage"];
    console.log(data)
},
error =>{
    this._errorMessage = JSON.stringify(error);
})
return this._producesArray
}
}

Thank you.

Body:
the problem is that - you call the API which is asynchronic action which means is moving on to the next line of code while this request is execute...
so you return _producesArray before it's really filled with data.
what do you need to do is simply return the observable like this:

 return this.http.get<any>(BASE_URL + "produce/")

and make the subscribe inside the component

this.list.getProduce().subscribe(...)

good luck :)


问:
Expected non-nullable lint warning for LiveData in Android Studio 2020.3.1 P2
Here's the code in question:

```<code>private val _cropRequiredLiveData = SingleLiveEvent<MediaContent>()
fun crop(): LiveData<MediaContent> = _cropRequiredLiveData

private fun onDownloadComplete(content: MediaContent?) {

    if (request.isCropEnabled
        && content != null
    ) {
        _cropRequiredLiveData.value = content
        return
    }

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

content variable in following line shows me a lint warning:

```<code>_cropRequiredLiveData.value = content
</code>```

The warning is:

Expected non-nullable value

If I replace content with a content!! or requireNotNull(content), I get another lint warning saying:

Unnecessary non-null assertion (!!) on a non-null receiver of type MediaContent

Redundant 'requireNotNull' call

Is there something I can do to make the lint happy?

Here's the MediaContent file:

```<code>@Parcelize
class MediaContent(
    val metadata: MediaMetadata,
    val source: MediaSource,
    val path: String
) : Parcelable

fun MediaContent.toFile() = File(path)
</code>```

答: Try this._cropRequiredLiveData.value = content. Not sure why but it works for me.

Body:
Here's the code in question:

private val _cropRequiredLiveData = SingleLiveEvent<MediaContent>()
fun crop(): LiveData<MediaContent> = _cropRequiredLiveData

private fun onDownloadComplete(content: MediaContent?) {

    if (request.isCropEnabled
        && content != null
    ) {
        _cropRequiredLiveData.value = content
        return
    }

    // ...
}

content variable in following line shows me a lint warning:

_cropRequiredLiveData.value = content

The warning is:

Expected non-nullable value

If I replace content with a content!! or requireNotNull(content), I get another lint warning saying:

Unnecessary non-null assertion (!!) on a non-null receiver of type MediaContent

Redundant 'requireNotNull' call

Is there something I can do to make the lint happy?

Here's the MediaContent file:

@Parcelize
class MediaContent(
    val metadata: MediaMetadata,
    val source: MediaSource,
    val path: String
) : Parcelable

fun MediaContent.toFile() = File(path)


Title: Find Specific Dates Within a Data Set Where data is less than?

Body:
I have the following dataset in R.

> jan_weather
        X HighTemp WindSpeed Snowfall WindChill
1   1-Jan       19         8      0.0       9.0
2   2-Jan       23        11      0.2      12.0
3   3-Jan       25         9      0.0      15.7
4   4-Jan       33        14      7.6      23.2
5   5-Jan       38         7      0.0      32.7
6   6-Jan       34         6      2.1      28.6
7   7-Jan       35        12      0.0      26.6
8   8-Jan       27        15      0.0      15.2
9   9-Jan       28        11      3.3      18.2
10 10-Jan       30        17      1.4      18.3
11 11-Jan       36        13      0.0      27.4
12 12-Jan       44         9      0.0      39.0
13 13-Jan       41         8      0.0      35.8
14 14-Jan       34        14      0.0      24.5
15 15-Jan       31        15      0.0      20.3
16 16-Jan       32        12      2.8      22.8
17 17-Jan       35        18      0.0      24.5
18 18-Jan       20        22      0.0       3.6
19 19-Jan       17        24      0.0      -1.1
20 20-Jan       16        20      0.6      -1.0
21 21-Jan       19         8      0.0       9.0
22 22-Jan       25         9      0.0      15.7
23 23-Jan       28        13     14.9      17.3
24 24-Jan       23        11      0.0      12.0
25 25-Jan       28        32      0.0      11.7
26 26-Jan       33        13      0.0      23.6
27 27-Jan       31        15      3.7      20.3
28 28-Jan       39        10      0.0      32.4
29 29-Jan       36         4      0.0      32.7
30 30-Jan       33         8      0.9      26.1
31 31-Jan       37        10      0.0      29.9

I would like to find the dates where for which the wind chill value is no less than 22 degrees Fahrenheit, combined with for which the wind speed is also no greater than 13 miles per hour. I figure this is a simple if statement and storing the return in a variable, but I seem to be having problems on how to set it up. Any advice?

Body:
We could use filter from dplyr:

library(dplyr)

df %>%
  filter(WindChill > 22 & WindSpeed < 13)

or Base R:

subset(df, WindChill > 22 & WindSpeed < 13)

        X HighTemp WindSpeed Snowfall WindChill
5   5-Jan       38         7      0.0      32.7
6   6-Jan       34         6      2.1      28.6
7   7-Jan       35        12      0.0      26.6
12 12-Jan       44         9      0.0      39.0
13 13-Jan       41         8      0.0      35.8
16 16-Jan       32        12      2.8      22.8
28 28-Jan       39        10      0.0      32.4
29 29-Jan       36         4      0.0      32.7
30 30-Jan       33         8      0.9      26.1
31 31-Jan       37        10      0.0      29.9


问:
Docker - Replacement for `dockerd` on Mac
I wanted to start the docker daemon with an open TCP address like this: docker daemon -H tcp://0.0.0.0:2375, but the terminal suggested that I use dockerd instead, which is apparently not a program that comes with the Docker Client for mac. Is there a way I can either

A - get some form of dockerd on my mac machine.

B - get around the use of dockerd by some other method.

?

答: If you want to do any specific configuration on mac, you might have already installed Docker Desktop. Docker desktop supports configuration using UserInterface shown below in the screenshot.

ContentLicense: CC BY-SA 3.0


问:
NullPointerException while working with stateful PartialFunction and collectFirst
Consider this (very ugly code):

```<code>object ExternalReferences2 {
  import java.util.regex._

  implicit def symbol2string(sym: Symbol) = sym.name

  object Mapping {
    def fromXml(mapping: scala.xml.NodeSeq) = {
      new Mapping(mapping \ 'vendor text,
                  mapping \ 'match text,
                  mapping \ 'format text)
    }
  }
  case class Mapping(vendor: String,
                     matches: String,
                     format: String) extends PartialFunction[String, String] {
    private val pattern = Pattern.compile(matches)
    private var _currentMatcher: Matcher = null
    private def currentMatcher =
      { println("Getting matcher: " + _currentMatcher); _currentMatcher }
    private def currentMatcher_=(matcher: Matcher) =
      { println("Setting matcher: " + matcher); _currentMatcher = matcher }

    def isDefinedAt(entity: String) =
      { currentMatcher = pattern.matcher(entity); currentMatcher.matches }

    def apply(entity: String) = apply

    def apply = {
      val range = 0 until currentMatcher.groupCount()
      val groups = range
                     map (currentMatcher.group(_))
                     filterNot (_ == null)
                     map (_.replace('.', '/'))
      format.format(groups: _*)
    }
  }

  val config =
    <external-links>
      <mapping>
        <vendor>OpenJDK</vendor>
        <match>{ """^(javax?|sunw?|com.sun|org\.(ietf\.jgss|omg|w3c\.dom|xml\.sax))(\.[^.]+)+$""" }</match>
        <format>{ "http://download.oracle.com/javase/7/docs/api/%s.html" }</format>
      </mapping>
    </external-links>

  def getLinkNew(entity: String) =
     (config \ 'mapping)
       collectFirst({ case m => Mapping.fromXml(m)})
       map(_.apply)

  def getLinkOld(entity: String) =
    (config \ 'mapping).view
      map(m => Mapping.fromXml(m))
      find(_.isDefinedAt(entity))
      map(_.apply)
}
</code>```

I tried to improve the getLinkOld method by using collectFirst as shown in getLinkNew, but I always get a NullPointerException because _currentMatcher is still set to null

```<code>scala> ExternalReferences2.getLinkNew("java.util.Date")
Getting matcher: null
java.lang.NullPointerException
    at ExternalReferences2$Mapping.apply(<console>:32)
    at ExternalReferences2$$anonfun$getLinkNew$2.apply(<console>:58)
    at ExternalReferences2$$anonfun$getLinkNew$2.apply(<console>:58)
    at scala.Option.map(Option.scala:131)
    at ExternalReferences2$.getLinkNew(<console>:58)
    at .<init>(<console>:13)
    at .<clinit>(<console>)
    at .<init>(<console>:11)
    at .<clinit>(<console>)
</code>```

while it works perfectly with getLinkOld.

What is the problem here?

答:
Your matcher is created as a side-effect in isDefined. Passing side effecting functions to routine such as map is usually a recipe for disaster, but this is not even what happens here. Your code requires isDefined to have been called just before apply is, with the same argument. That makes your code very fragile, and that is what you should change.

Clients of PartialFunction do not have to do follow that protocol in general. Imagine for instance

```<code>if (f.isDefinedAt(x) && f.isDefinedAt(y)) {fx = f(x); fy = f(y)}.
</code>```

And here the code that calls apply is not even yours, but the collection classes', so you do not control what happens.

Your specific problem in getLinkNew is that isDefined is simply never called.The PartialFunction argument of collectFirst is {case m => ...}. The isDefined that is called is the isDefined of this function. As m is an irrefutable pattern, it is allways true, and collectFirst will always return the first element if there is one. That the partial function returns another partial function (the Mapping) which happens not to be defined at m, is irrelevant.

Edit - Possible workaround

A very light change would be to check whether a matcher is available and create it if it is not. Better, keep the entity string that has been used to create it too, so that you can check it is the proper one. This should make the side effect benign as long as there is no multithreading. But the way, do not use null, use Option, so the compiler will not let you ignore the possibility that it may be None.

```<code>var _currentMatcher : Option[(String, Matcher)] = None
def currentMatcher(entity: String) : Matcher = _currentMatcher match{
  case Some(e,m) if e == entity => m
  case _ => {
    _currentMatcher = (entity, pattern.matcher(entity))
    _currentmatcher._2
  }
}
</code>```

Edit again. Stupid me

Sorry, the so called workaround indeed makes the class safer, but it does not make the collectFirst solution work. Again, the case m => partial function is always defined (note: entity does not even appears in your getLinkNew code, which should be worrying). The problem is that one would need a PartialFunction of a NodeSeq (not of entity, which will be known to the function, but not passed as argument). isDefined will be called, then apply. The pattern and the matcher depends on the NodeSeq, so they cannnot be created beforehand, but only in isDefined and/or apply. In the same spirit, you can cache what is computed in isDefined to reuse in Apply. This is definitely not pretty

```<code>def linkFor(entity: String) = new PartialFunction[NodeSeq, String] {
  var _matcher : Option[String, Matcher] = None
  def matcher(regexp: String) = _matcher match {
    case Some(r, m) where r == regexp => m
    case None => {
      val pattern = Pattern.compile(regexp)
      _matcher = (regexp, pattern.matcher(entity))
      _matcher._2
    }
  }
  def isDefined(mapping: NodeSeq) = {
    matcher(mapping \ "match" text).matches
  }
  def apply(mapping: NodeSeq) = {
     // call matcher(...), it is likely to reuse previous matcher, build result
  }

}
</code>```

You use that with (config \ mapping).collectFirst(linkFor(entity))

Body:
Consider this (very ugly code):

object ExternalReferences2 {
  import java.util.regex._

  implicit def symbol2string(sym: Symbol) = sym.name

  object Mapping {
    def fromXml(mapping: scala.xml.NodeSeq) = {
      new Mapping(mapping \ 'vendor text,
                  mapping \ 'match text,
                  mapping \ 'format text)
    }
  }
  case class Mapping(vendor: String,
                     matches: String,
                     format: String) extends PartialFunction[String, String] {
    private val pattern = Pattern.compile(matches)
    private var _currentMatcher: Matcher = null
    private def currentMatcher =
      { println("Getting matcher: " + _currentMatcher); _currentMatcher }
    private def currentMatcher_=(matcher: Matcher) =
      { println("Setting matcher: " + matcher); _currentMatcher = matcher }

    def isDefinedAt(entity: String) =
      { currentMatcher = pattern.matcher(entity); currentMatcher.matches }

    def apply(entity: String) = apply

    def apply = {
      val range = 0 until currentMatcher.groupCount()
      val groups = range
                     map (currentMatcher.group(_))
                     filterNot (_ == null)
                     map (_.replace('.', '/'))
      format.format(groups: _*)
    }
  }

  val config =
    <external-links>
      <mapping>
        <vendor>OpenJDK</vendor>
        <match>{ """^(javax?|sunw?|com.sun|org\.(ietf\.jgss|omg|w3c\.dom|xml\.sax))(\.[^.]+)+$""" }</match>
        <format>{ "http://download.oracle.com/javase/7/docs/api/%s.html" }</format>
      </mapping>
    </external-links>

  def getLinkNew(entity: String) =
     (config \ 'mapping)
       collectFirst({ case m => Mapping.fromXml(m)})
       map(_.apply)

  def getLinkOld(entity: String) =
    (config \ 'mapping).view
      map(m => Mapping.fromXml(m))
      find(_.isDefinedAt(entity))
      map(_.apply)
}

I tried to improve the getLinkOld method by using collectFirst as shown in getLinkNew, but I always get a NullPointerException because _currentMatcher is still set to null

scala> ExternalReferences2.getLinkNew("java.util.Date")
Getting matcher: null
java.lang.NullPointerException
    at ExternalReferences2$Mapping.apply(<console>:32)
    at ExternalReferences2$$anonfun$getLinkNew$2.apply(<console>:58)
    at ExternalReferences2$$anonfun$getLinkNew$2.apply(<console>:58)
    at scala.Option.map(Option.scala:131)
    at ExternalReferences2$.getLinkNew(<console>:58)
    at .<init>(<console>:13)
    at .<clinit>(<console>)
    at .<init>(<console>:11)
    at .<clinit>(<console>)

while it works perfectly with getLinkOld.

What is the problem here?

Body:
Your matcher is created as a side-effect in isDefined. Passing side effecting functions to routine such as map is usually a recipe for disaster, but this is not even what happens here. Your code requires isDefined to have been called just before apply is, with the same argument. That makes your code very fragile, and that is what you should change.

Clients of PartialFunction do not have to do follow that protocol in general. Imagine for instance

if (f.isDefinedAt(x) && f.isDefinedAt(y)) {fx = f(x); fy = f(y)}.

And here the code that calls apply is not even yours, but the collection classes', so you do not control what happens.

Your specific problem in getLinkNew is that isDefined is simply never called.The PartialFunction argument of collectFirst is {case m => ...}. The isDefined that is called is the isDefined of this function. As m is an irrefutable pattern, it is allways true, and collectFirst will always return the first element if there is one. That the partial function returns another partial function (the Mapping) which happens not to be defined at m, is irrelevant.

Edit - Possible workaround

A very light change would be to check whether a matcher is available and create it if it is not. Better, keep the entity string that has been used to create it too, so that you can check it is the proper one. This should make the side effect benign as long as there is no multithreading. But the way, do not use null, use Option, so the compiler will not let you ignore the possibility that it may be None.

var _currentMatcher : Option[(String, Matcher)] = None
def currentMatcher(entity: String) : Matcher = _currentMatcher match{
  case Some(e,m) if e == entity => m
  case _ => {
    _currentMatcher = (entity, pattern.matcher(entity))
    _currentmatcher._2
  }
}

Edit again. Stupid me

Sorry, the so called workaround indeed makes the class safer, but it does not make the collectFirst solution work. Again, the case m => partial function is always defined (note: entity does not even appears in your getLinkNew code, which should be worrying). The problem is that one would need a PartialFunction of a NodeSeq (not of entity, which will be known to the function, but not passed as argument). isDefined will be called, then apply. The pattern and the matcher depends on the NodeSeq, so they cannnot be created beforehand, but only in isDefined and/or apply. In the same spirit, you can cache what is computed in isDefined to reuse in Apply. This is definitely not pretty

def linkFor(entity: String) = new PartialFunction[NodeSeq, String] {
  var _matcher : Option[String, Matcher] = None
  def matcher(regexp: String) = _matcher match {
    case Some(r, m) where r == regexp => m
    case None => {
      val pattern = Pattern.compile(regexp)
      _matcher = (regexp, pattern.matcher(entity))
      _matcher._2
    }
  }
  def isDefined(mapping: NodeSeq) = {
    matcher(mapping \ "match" text).matches
  }
  def apply(mapping: NodeSeq) = {
     // call matcher(...), it is likely to reuse previous matcher, build result
  }

}

You use that with (config \ mapping).collectFirst(linkFor(entity))


答:
In both statements, the myHashSet is actually of type HashSet.

The difference is: In the first case, the myHashSet is something that implements ISet, which might have some APIs different from HashSet.

For example:

```<code>interface ISet
{
    void method1();
    ......
}

class HashSet: ISet
{
    void method1();
    void method2();
    ......
}
</code>```

Now

```<code>ISet set1 = new HashSet();  // set1.method1() is ok, but set1.method2() doesn't work!
HashSet set2 = new HashSet(); // set2.method1() and set2.method2() are all ok
</code>```

Title: ISet vs HashSet in C#

Body:
In both statements, the myHashSet is actually of type HashSet.

The difference is: In the first case, the myHashSet is something that implements ISet, which might have some APIs different from HashSet.

For example:

interface ISet
{
    void method1();
    ......
}

class HashSet: ISet
{
    void method1();
    void method2();
    ......
}

Now

ISet set1 = new HashSet();  // set1.method1() is ok, but set1.method2() doesn't work!
HashSet set2 = new HashSet(); // set2.method1() and set2.method2() are all ok


Body:
base R

df[df$WindChill > 22 & df$WindSpeed < 13,]

Output

        X HighTemp WindSpeed Snowfall WindChill
5   5-Jan       38         7      0.0      32.7
6   6-Jan       34         6      2.1      28.6
7   7-Jan       35        12      0.0      26.6
12 12-Jan       44         9      0.0      39.0
13 13-Jan       41         8      0.0      35.8
16 16-Jan       32        12      2.8      22.8
28 28-Jan       39        10      0.0      32.4
29 29-Jan       36         4      0.0      32.7
30 30-Jan       33         8      0.9      26.1
31 31-Jan       37        10      0.0      29.9

Or with data.table

library(data.table)

dt <- as.data.table(df)
dt[, .SD[WindChill > 22 & WindSpeed < 13]]

Data

df <- structure(list(X = c("1-Jan", "2-Jan", "3-Jan", "4-Jan", "5-Jan",
"6-Jan", "7-Jan", "8-Jan", "9-Jan", "10-Jan", "11-Jan", "12-Jan",
"13-Jan", "14-Jan", "15-Jan", "16-Jan", "17-Jan", "18-Jan", "19-Jan",
"20-Jan", "21-Jan", "22-Jan", "23-Jan", "24-Jan", "25-Jan", "26-Jan",
"27-Jan", "28-Jan", "29-Jan", "30-Jan", "31-Jan"), HighTemp = c(19L,
23L, 25L, 33L, 38L, 34L, 35L, 27L, 28L, 30L, 36L, 44L, 41L, 34L,
31L, 32L, 35L, 20L, 17L, 16L, 19L, 25L, 28L, 23L, 28L, 33L, 31L,
39L, 36L, 33L, 37L), WindSpeed = c(8L, 11L, 9L, 14L, 7L, 6L,
12L, 15L, 11L, 17L, 13L, 9L, 8L, 14L, 15L, 12L, 18L, 22L, 24L,
20L, 8L, 9L, 13L, 11L, 32L, 13L, 15L, 10L, 4L, 8L, 10L), Snowfall = c(0,
0.2, 0, 7.6, 0, 2.1, 0, 0, 3.3, 1.4, 0, 0, 0, 0, 0, 2.8, 0, 0,
0, 0.6, 0, 0, 14.9, 0, 0, 0, 3.7, 0, 0, 0.9, 0), WindChill = c(9,
12, 15.7, 23.2, 32.7, 28.6, 26.6, 15.2, 18.2, 18.3, 27.4, 39,
35.8, 24.5, 20.3, 22.8, 24.5, 3.6, -1.1, -1, 9, 15.7, 17.3, 12,
11.7, 23.6, 20.3, 32.4, 32.7, 26.1, 29.9)), class = "data.frame", row.names = c(NA,
-31L))


问:
Insert Data to a SQL DB using multiple threads
I am trying to write a code that makes records in a SQL DB.

The data I'll be inserting will be received real time(at least 10,000 and up to 80,000 per minute) and one crucial thing is that the exact time the data was received is also recorded.

I understand that a code using a single thread dealing with that much data might overload the core so I'm trying to figure out a better way to write a code.

From searching the web, this is what I came up with.

Have a main thread receive the data and also make record of the time.

Divide the received data into multiple threads.

Make those multiple threads insert to a single DB in a batch.

As I am not familiar with codes using multiple threads, I am not sure how to implement this or if this is even OK.
If it is not, what would be a better way? If it is, what method or class should I use to execute each step?

答:
This is what Queues can be used for. Have a list in memory that you add to and then have a service that processes the queue in order they are received to ensure sequence is correct.

It can then process them on a separate thread. You can do this on a timed event since you receive them per minute and process them every minute if you want.

If you need a basic example I suppose I could make one, but yeah this is one option.

UPDATE: here is example for auctions that does something similar. This is a basic example for a small scale demo auction application. This too has bottlenecks, but it will ensure all records are inputted as they are received allowing the true winning bid to always go through.

```<code>public Queue<AuctionBidQueue> AuctionBidQueueList = new Queue<AuctionBidQueue>();; //create a class for what data is coming in.

public void PopulateAuctionBidQueue()
        {
            //Can only add auctions from AuctionBidQueue table if queue is not processing.
            if(QueueProcessing == false)
            {
                //Lock the Queue - This is done to prevent another thread or process from processing the queue. In my scenario this could happen, maybe not for you.
                LockAuctionBidQueue();
                //add AuctionBidQueue to AuctionBidQueueList
                List<AuctionBidQueue> auctionBigQueue = new List<AuctionBidQueue>();

                try
                {
                   //I call DB here to get bids, but this is where you'd take your 10k-80k records and put them into a tolist
                   auctionBigQueue = _context.AuctionBidQueue.Where(x => x.Active == true && x.IsProcessed == false).OrderBy(x => x.CreateTimeInTicks).ToList();
                } catch(Exception error)
                {
                    Console.WriteLine(error);
                    return;
                }

                if(auctionBigQueue.Count != 0)
                {
                    foreach (AuctionBidQueue abq in auctionBigQueue)
                    {
                        AuctionBidQueueList.Enqueue(abq); //adds auctions to in memory list.
                    }

                    //Process the bid  Queue
                    ProcessAuctionBidQueue();
                    //Clear the Auction Bid Queue List
                    ClearAuctionBidQueue();

                }
                //Unlock the queue to be processed again
                UnlockAuctionBidQueue();

            }
        }
</code>```

You can then have a task that process the list. In my example bids are processed every 200 ms, so since you only get records everyone 1 minute you could increase the time of the time thread to not run so frequent.

```<code>AuctionEngineTimer = new Timer(o => {
                using (var scope = _scopeFactory.CreateScope())
                {

                    var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();

                    AuctionEngine auctionEngine = new AuctionEngine(_hostEnv, _scopeFactory, _hubContext, dbContext);
                    auctionEngine.PopulateAuctionBidQueue();
                }
            },
            null,
            TimeSpan.Zero,
            TimeSpan.FromMilliseconds(200));
</code>```

Body:
This is what Queues can be used for. Have a list in memory that you add to and then have a service that processes the queue in order they are received to ensure sequence is correct.

It can then process them on a separate thread. You can do this on a timed event since you receive them per minute and process them every minute if you want.

If you need a basic example I suppose I could make one, but yeah this is one option.

UPDATE: here is example for auctions that does something similar. This is a basic example for a small scale demo auction application. This too has bottlenecks, but it will ensure all records are inputted as they are received allowing the true winning bid to always go through.

public Queue<AuctionBidQueue> AuctionBidQueueList = new Queue<AuctionBidQueue>();; //create a class for what data is coming in.

public void PopulateAuctionBidQueue()
        {
            //Can only add auctions from AuctionBidQueue table if queue is not processing.
            if(QueueProcessing == false)
            {
                //Lock the Queue - This is done to prevent another thread or process from processing the queue. In my scenario this could happen, maybe not for you.
                LockAuctionBidQueue();
                //add AuctionBidQueue to AuctionBidQueueList
                List<AuctionBidQueue> auctionBigQueue = new List<AuctionBidQueue>();

                try
                {
                   //I call DB here to get bids, but this is where you'd take your 10k-80k records and put them into a tolist
                   auctionBigQueue = _context.AuctionBidQueue.Where(x => x.Active == true && x.IsProcessed == false).OrderBy(x => x.CreateTimeInTicks).ToList();
                } catch(Exception error)
                {
                    Console.WriteLine(error);
                    return;
                }

                if(auctionBigQueue.Count != 0)
                {
                    foreach (AuctionBidQueue abq in auctionBigQueue)
                    {
                        AuctionBidQueueList.Enqueue(abq); //adds auctions to in memory list.
                    }

                    //Process the bid  Queue
                    ProcessAuctionBidQueue();
                    //Clear the Auction Bid Queue List
                    ClearAuctionBidQueue();

                }
                //Unlock the queue to be processed again
                UnlockAuctionBidQueue();

            }
        }

You can then have a task that process the list. In my example bids are processed every 200 ms, so since you only get records everyone 1 minute you could increase the time of the time thread to not run so frequent.

AuctionEngineTimer = new Timer(o => {
                using (var scope = _scopeFactory.CreateScope())
                {

                    var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();

                    AuctionEngine auctionEngine = new AuctionEngine(_hostEnv, _scopeFactory, _hubContext, dbContext);
                    auctionEngine.PopulateAuctionBidQueue();
                }
            },
            null,
            TimeSpan.Zero,
            TimeSpan.FromMilliseconds(200));


问:
custom marker icon with react-leaflet
I tried everything I found on the web, Stackoverflow and Github, and I still can't make it.

I want to make a custom marker with a custom icon, but with my code below I always got an error : 'TypeError: options.icon.createIcon is not a function'

Here is my code (no error on the paths to folders, everything is in src/js or src/img)

Icon.js

```<code>import L from 'leaflet';

const iconPerson = L.Icon.extend({
  options: {
    iconUrl: require('../img/marker-pin-person.svg'),
    iconRetinaUrl: require('../img/marker-pin-person.svg'),
    iconAnchor: null,
    popupAnchor: null,
    shadowUrl: null,
    shadowSize: null,
    shadowAnchor: null,
    iconSize: new L.Point(60, 75),
    className: 'leaflet-div-icon'
  }
});

export { iconPerson };
</code>```

MarkerPinPerson

```<code>import React from 'react';
import { Marker } from 'react-leaflet';
import {  iconPerson  } from './Icons';

export default class MarkerPinPerson extends React.Component {

  render() {

    return (
      <Marker
        position={this.props.markerPosition}
        icon={ iconPerson }
        >
      </Marker>
      );
  }
}
</code>```

Really looking for your help !

答:
in react-leaflet v3 this worked very well for me :
first I made an SVG icon then I encoded it with encodeURIComponent, finally I passed it to Marker

```<code>    import React, {useEffect} from 'react';
    import {MapContainer, Marker, Popup, TileLayer} from 'react-leaflet';
    import Main from "../publicComponents/main";
    import L from "leaflet";

    const position = [35.72428729739558, 51.447000503540046]
    const Red_MARKER = `data:image/svg+xml;utf8,${encodeURIComponent(`<?xml version="1.0" encoding="iso-8859-1"?>
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="36.059" height="36.059" viewBox="0 0 36.059 36.059" style="transform:rotate(${0}deg)">
      <defs>
        <filter id="Path_10080" x="0" y="0" width="36.059" height="36.059" filterUnits="userSpaceOnUse">
          <feOffset input="SourceAlpha"/>
          <feGaussianBlur stdDeviation="2.5" result="blur"/>
          <feFlood flood-opacity="0.161"/>
          <feComposite operator="in" in2="blur"/>
          <feComposite in="SourceGraphic"/>
        </filter>
      </defs>
      <g id="Group_8038" data-name="Group 8038" transform="translate(5719.5 1106.5)">
        <rect id="Rectangle_2670" data-name="Rectangle 2670" width="21" height="21" transform="translate(-5712 -1099)" fill="none"/>
        <g transform="matrix(1, 0, 0, 1, -5719.5, -1106.5)" filter="url(#Path_10080)">
          <path id="Path_10080-2" data-name="Path 10080" d="M15.4,12.766a6.414,6.414,0,0,0,1.781-5.634l-.446-2.55-2.55-.446A6.414,6.414,0,0,0,8.553,5.916L6.746,7.723c.234-.232-.845.866-.626.626l-2.96,2.96a2.644,2.644,0,0,0,0,3.735l3.114,3.114a2.644,2.644,0,0,0,3.735,0l2.96-2.96Z" transform="translate(19.2 2.96) rotate(45)" fill="${"red"}"/>
        </g>
      </g>
    </svg>
    `)}`;

    const BoatIcon = L.icon({
        iconUrl: Red_MARKER,
        iconSize: [40, 40],
        iconAnchor: [12, 12],
        popupAnchor: [0, 0],
    });

    const Index = () => {
        return (<Main>
                <MapContainer center={position} zoom={13}
                              style={{width: "100%", height: "calc(100vh - 80px)", overflow: "hidden"}}>
                    <TileLayer
                        attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                    />
                    <Marker position={position} icon={BoatIcon}>
                        <Popup>
                            A pretty CSS3 popup. <br/> Easily customizable.
                        </Popup>
                    </Marker>
                </MapContainer></Main>
        );
    };

    export default Index;
</code>```

Title: custom marker icon with react-leaflet

Body:
I tried everything I found on the web, Stackoverflow and Github, and I still can't make it.

I want to make a custom marker with a custom icon, but with my code below I always got an error : 'TypeError: options.icon.createIcon is not a function'

Here is my code (no error on the paths to folders, everything is in src/js or src/img)

Icon.js

import L from 'leaflet';

const iconPerson = L.Icon.extend({
  options: {
    iconUrl: require('../img/marker-pin-person.svg'),
    iconRetinaUrl: require('../img/marker-pin-person.svg'),
    iconAnchor: null,
    popupAnchor: null,
    shadowUrl: null,
    shadowSize: null,
    shadowAnchor: null,
    iconSize: new L.Point(60, 75),
    className: 'leaflet-div-icon'
  }
});

export { iconPerson };

MarkerPinPerson

import React from 'react';
import { Marker } from 'react-leaflet';
import {  iconPerson  } from './Icons';

export default class MarkerPinPerson extends React.Component {

  render() {

    return (
      <Marker
        position={this.props.markerPosition}
        icon={ iconPerson }
        >
      </Marker>
      );
  }
}

Really looking for your help !

Body:
in react-leaflet v3 this worked very well for me :
first I made an SVG icon then I encoded it with encodeURIComponent, finally I passed it to Marker

    import React, {useEffect} from 'react';
    import {MapContainer, Marker, Popup, TileLayer} from 'react-leaflet';
    import Main from "../publicComponents/main";
    import L from "leaflet";

    const position = [35.72428729739558, 51.447000503540046]
    const Red_MARKER = `data:image/svg+xml;utf8,${encodeURIComponent(`<?xml version="1.0" encoding="iso-8859-1"?>
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="36.059" height="36.059" viewBox="0 0 36.059 36.059" style="transform:rotate(${0}deg)">
      <defs>
        <filter id="Path_10080" x="0" y="0" width="36.059" height="36.059" filterUnits="userSpaceOnUse">
          <feOffset input="SourceAlpha"/>
          <feGaussianBlur stdDeviation="2.5" result="blur"/>
          <feFlood flood-opacity="0.161"/>
          <feComposite operator="in" in2="blur"/>
          <feComposite in="SourceGraphic"/>
        </filter>
      </defs>
      <g id="Group_8038" data-name="Group 8038" transform="translate(5719.5 1106.5)">
        <rect id="Rectangle_2670" data-name="Rectangle 2670" width="21" height="21" transform="translate(-5712 -1099)" fill="none"/>
        <g transform="matrix(1, 0, 0, 1, -5719.5, -1106.5)" filter="url(#Path_10080)">
          <path id="Path_10080-2" data-name="Path 10080" d="M15.4,12.766a6.414,6.414,0,0,0,1.781-5.634l-.446-2.55-2.55-.446A6.414,6.414,0,0,0,8.553,5.916L6.746,7.723c.234-.232-.845.866-.626.626l-2.96,2.96a2.644,2.644,0,0,0,0,3.735l3.114,3.114a2.644,2.644,0,0,0,3.735,0l2.96-2.96Z" transform="translate(19.2 2.96) rotate(45)" fill="${"red"}"/>
        </g>
      </g>
    </svg>
    `)}`;

    const BoatIcon = L.icon({
        iconUrl: Red_MARKER,
        iconSize: [40, 40],
        iconAnchor: [12, 12],
        popupAnchor: [0, 0],
    });

    const Index = () => {
        return (<Main>
                <MapContainer center={position} zoom={13}
                              style={{width: "100%", height: "calc(100vh - 80px)", overflow: "hidden"}}>
                    <TileLayer
                        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                    />
                    <Marker position={position} icon={BoatIcon}>
                        <Popup>
                            A pretty CSS3 popup. <br/> Easily customizable.
                        </Popup>
                    </Marker>
                </MapContainer></Main>
        );
    };

    export default Index;


问:
Sentry Rate Limiting
We have a couple of aws lambda functions which are using the same Sentry Client Key for error reporting. Recently we started to receive rate limiting error.

```<code>{
    "errorType": "SentryError",
    "errorMessage": "HTTP Error (429)",
    "name": "SentryError",
    "stack": [
        "SentryError: HTTP Error (429)",
        "    at new SentryError (/var/task/node_modules/@sentry/utils/dist/error.js:9:28)",
        "    at ClientRequest.<anonymous> (/var/task/node_modules/@sentry/node/dist/transports/base/index.js:212:44)",
        "    at Object.onceWrapper (events.js:421:26)",
        "    at ClientRequest.emit (events.js:314:20)",
        "    at ClientRequest.EventEmitter.emit (domain.js:483:12)",
        "    at HTTPParser.parserOnIncomingClient (_http_client.js:601:27)",
        "    at HTTPParser.parserOnHeadersComplete (_http_common.js:122:17)",
        "    at TLSSocket.socketOnData (_http_client.js:474:22)",
        "    at TLSSocket.emit (events.js:314:20)",
        "    at TLSSocket.EventEmitter.emit (domain.js:483:12)"
    ]
}
</code>```

However, no actual errors occurs in the lambda function. From what we understand Sentry is recording every lambda executions and sending this information as trace. We are using a low tracesSampleRate, but the error still occurs.

```<code>AWSLambda.init({
  dsn: process.env.SENTRY_DNS,
  sampleRate: 1.0,
  tracesSampleRate: 0.1,
});
</code>```

I don't know if this is relevant, but the functions are not inside our VPC, they are using AWS ip address pool.

We tried to find any indication of errors related to rate limiting in the Sentry dashboard, but without success.

Thanks!

答: I started getting this issue in one of our systems around the same time you posted this. Something that stopped it happening was to disable tracing all together (tracesSampleRate: 0). Not truly a fix, but enough to clear our error logs for now while we investigate a proper fix.

Title: Sentry Rate Limiting

Body:
We have a couple of aws lambda functions which are using the same Sentry Client Key for error reporting. Recently we started to receive rate limiting error.

{
    "errorType": "SentryError",
    "errorMessage": "HTTP Error (429)",
    "name": "SentryError",
    "stack": [
        "SentryError: HTTP Error (429)",
        "    at new SentryError (/var/task/node_modules/@sentry/utils/dist/error.js:9:28)",
        "    at ClientRequest.<anonymous> (/var/task/node_modules/@sentry/node/dist/transports/base/index.js:212:44)",
        "    at Object.onceWrapper (events.js:421:26)",
        "    at ClientRequest.emit (events.js:314:20)",
        "    at ClientRequest.EventEmitter.emit (domain.js:483:12)",
        "    at HTTPParser.parserOnIncomingClient (_http_client.js:601:27)",
        "    at HTTPParser.parserOnHeadersComplete (_http_common.js:122:17)",
        "    at TLSSocket.socketOnData (_http_client.js:474:22)",
        "    at TLSSocket.emit (events.js:314:20)",
        "    at TLSSocket.EventEmitter.emit (domain.js:483:12)"
    ]
}

However, no actual errors occurs in the lambda function. From what we understand Sentry is recording every lambda executions and sending this information as trace. We are using a low tracesSampleRate, but the error still occurs.

AWSLambda.init({
  dsn: process.env.SENTRY_DNS,
  sampleRate: 1.0,
  tracesSampleRate: 0.1,
});

I don't know if this is relevant, but the functions are not inside our VPC, they are using AWS ip address pool.

We tried to find any indication of errors related to rate limiting in the Sentry dashboard, but without success.

Thanks!


问:
How to remove the existing spark environment and related packages from computer?
I had installed spark using the below method to my ubuntu 20.04.3 system. As there are certain dependency issues, im looking for a way to completely remove this environment of spark. But im not able to find the proper way.

Here's the link which has the exact steps that i used to install spark. https://phoenixnap.com/kb/install-spark-on-ubuntu

答: All spark libraries are found by env var SPARK_HOME. You can remove everything from this path.


问:
React Router not passing params through useParams onto my page
I am building a web page that I want to be dynamically routed with the react-router-dom, and useParams() does not hold the passed-in value on the final page that the route ends on.

Here are my routes:

```<code>import React from "react";
import ReactDOM from "react-dom";
import CssBaseline from "@mui/material/CssBaseline";
import {
  BrowserRouter,
  Routes,
  Route,
  } from "react-router-dom";
import "./index.css";
import App from "./App";
import Items from "./routes/items";
import TextContentPage from "./routes/textContentPage";
import reportWebVitals from "./reportWebVitals";
import HomePage from "./routes/homePage";
import TopicPage from "./routes/topicPage";

ReactDOM.render(
  <React.StrictMode>
    <CssBaseline />
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="trees" element={<App />} />
        <Route path="items" element={<Items />} />
        <Route path="text-content" element={<TextContentPage />} />
        <Route path ="topics/:id" element={<TopicPage />} />
      </Routes>
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById("root")
);
</code>```

And here is the page I am trying to render:

```<code>import { useParams } from "react-router-dom"
import Container from "@mui/material/Container";
import Header from "../components/Header";
import Card from '@mui/material/Card'
const topics = [
    {
        id: 1,
        name: "Environement",
        fund: 0
    },
    {
        id: 2,
        name: "Education",
        fund: 0
    },
    {
        id: 3,
        name: "International affairs",
        fund: 0
    }
]

export default function TopicPage(){

    const topicId = useParams()
    let topic = topics.find(topic => topic.id === topicId)
    return (
        <Container maxWidth = "sm">
            <Header title = "Map The Future">
            </Header>
            <main>
                <Card><h2>{topic.name}</h2></Card>
            </main>
        </Container>

    );

}
</code>```

Any Help figuring out how to get useParams() to work would be greatly appreciated!!

答:
Spotted two issues with your code. Try these edits and see if they help.

useParams returns object, so try using the object destructuring syntax:

let { id } = useParams()

Your variable name needs to match what you used in your <Route /> component - "id".

Since the useParams values are grabbed from the URL, they're String types.
To convert to integers:

id = parseInt(id, 10)

Body:
I am building a web page that I want to be dynamically routed with the react-router-dom, and useParams() does not hold the passed-in value on the final page that the route ends on.

Here are my routes:

import React from "react";
import ReactDOM from "react-dom";
import CssBaseline from "@mui/material/CssBaseline";
import {
  BrowserRouter,
  Routes,
  Route,
  } from "react-router-dom";
import "./index.css";
import App from "./App";
import Items from "./routes/items";
import TextContentPage from "./routes/textContentPage";
import reportWebVitals from "./reportWebVitals";
import HomePage from "./routes/homePage";
import TopicPage from "./routes/topicPage";

ReactDOM.render(
  <React.StrictMode>
    <CssBaseline />
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="trees" element={<App />} />
        <Route path="items" element={<Items />} />
        <Route path="text-content" element={<TextContentPage />} />
        <Route path ="topics/:id" element={<TopicPage />} />
      </Routes>
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById("root")
);

And here is the page I am trying to render:

import { useParams } from "react-router-dom"
import Container from "@mui/material/Container";
import Header from "../components/Header";
import Card from '@mui/material/Card'
const topics = [
    {
        id: 1,
        name: "Environement",
        fund: 0
    },
    {
        id: 2,
        name: "Education",
        fund: 0
    },
    {
        id: 3,
        name: "International affairs",
        fund: 0
    }
]

export default function TopicPage(){

    const topicId = useParams()
    let topic = topics.find(topic => topic.id === topicId)
    return (
        <Container maxWidth = "sm">

                <Card>
{topic.name}
</Card>

        </Container>

    );

}

Any Help figuring out how to get useParams() to work would be greatly appreciated!!


问:
Macro definition conflict
I'm running into this issue. This is not about macro functions, just simple string-value macro replacement.

I have two header files

```<code>test1.h
#define TEST 123
test2.h
#define TEST 456
</code>```

Now I have a program included  both these two headers, but I want my actually TEST to be 123.
How can I avoid defining TEST as 456?

You might think I'm crazy not to simply change the macro, but the situation is: I have a third-party decoder, which has this macro (defined in test1.h), and there's another WINAPI macro (defined in test2.h). Both of these files are controlled by others; I should not change either of them.
I don't need the test2.h at all, but I guess it's implicitly included by some other WINAPI header.

So, could anyone please tell me how to work around this issue? To overwrite the WINAPI macro with my third-party macro? Or how to nullify the definition from the WINAPI header in my own code? Is there a way to specify which header I don't want to include.

答: #undef TEST after the include of test2.h and before the include of test1.h. This is a bit of a hack though since you can't fix the macro names.

Title: Macro definition conflict

Body:
I'm running into this issue. This is not about macro functions, just simple string-value macro replacement.

I have two header files

test1.h
#define TEST 123
test2.h
#define TEST 456

Now I have a program included  both these two headers, but I want my actually TEST to be 123.
How can I avoid defining TEST as 456?

You might think I'm crazy not to simply change the macro, but the situation is: I have a third-party decoder, which has this macro (defined in test1.h), and there's another WINAPI macro (defined in test2.h). Both of these files are controlled by others; I should not change either of them.
I don't need the test2.h at all, but I guess it's implicitly included by some other WINAPI header.

So, could anyone please tell me how to work around this issue? To overwrite the WINAPI macro with my third-party macro? Or how to nullify the definition from the WINAPI header in my own code? Is there a way to specify which header I don't want to include.


问:
Pyinstaller speedtest convert to exe error; no module name "__builtin__"
I am trying to convert a program to an exe using pyinstaller.  The program performs a hardware assessment of a user's computer to include running an internet speed test utilizing speedtest-cli.  The program runs fine until I compile it at which point I receive the following error:

```<code>Traceback (most recent call last):   File "speedtest.py", line 156, in <module> ModuleNotFoundError: No module named '__builtin__'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "hw-assesment-tool.py", line 9, in <module>   File "<frozen importlib._bootstrap>", line 1007, in
_find_and_load   File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked   File "<frozen importlib._bootstrap>", line 680, in _load_unlocked   File "PyInstaller\loader\pyimod03_importers.py", line 546, in exec_module   File "speedtest.py", line 179, in <module>   File "speedtest.py", line 166, in __init__ AttributeError: 'NullWriter' object has no attribute 'fileno'
</code>```

I have tried upgrading and re-installing speedtest-cli and it has not corrected the issue.

P.S.  Here is a screenshot of the error:

Compiled Python EXE error originating in Speedtest-cli

答:
First you need to go to C:\Users\user\AppData\Local\Programs\Python\Python38\Lib\site-packages. Then find the speedtest.py and open it with Notepad or any other Text Editor.

Now you need to edit these lines of code

Line 156: to

```<code>import builtins
</code>```

Line 158 : to

```<code>import builtins
</code>```

Line 199: to

```<code>del builtins
</code>```

To confirm, you can find for __builtin__ and replace it with builtins

Body:
I am trying to convert a program to an exe using pyinstaller.  The program performs a hardware assessment of a user's computer to include running an internet speed test utilizing speedtest-cli.  The program runs fine until I compile it at which point I receive the following error:

Traceback (most recent call last):   File "speedtest.py", line 156, in <module> ModuleNotFoundError: No module named '__builtin__'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "hw-assesment-tool.py", line 9, in <module>   File "<frozen importlib._bootstrap>", line 1007, in
_find_and_load   File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked   File "<frozen importlib._bootstrap>", line 680, in _load_unlocked   File "PyInstaller\loader\pyimod03_importers.py", line 546, in exec_module   File "speedtest.py", line 179, in <module>   File "speedtest.py", line 166, in __init__ AttributeError: 'NullWriter' object has no attribute 'fileno'

I have tried upgrading and re-installing speedtest-cli and it has not corrected the issue.

P.S.  Here is a screenshot of the error:

Compiled Python EXE error originating in Speedtest-cli

Body:
First you need to go to C:\Users\user\AppData\Local\Programs\Python\Python38\Lib\site-packages. Then find the speedtest.py and open it with Notepad or any other Text Editor.

Now you need to edit these lines of code

Line 156: to

import builtins

Line 158 : to

import builtins

Line 199: to

del builtins

To confirm, you can find for __builtin__ and replace it with builtins


问:
Unable to get values from switch statement to push in to an array
I've spent hours trying to figure out this exercise and stuck at this point.  I'm unable to get values from my switch statement to push to an array for "displayVal", and "val" variables.</p>
```<code>const getDeck = () => {
  const suits = ['Spades','Hearts','Diamonds','Clubs'];
  let cards = [];

  for(let s=0; s < suits.length; s++){

   for(let d = 0; d < 13; d++){
    let displayVal;
    let val;

     switch (d) {
      case (d === 1):
        displayVal = "Ace";
        val = 11;
        break;
      case (d >=2 && d <= 10):
         displayVal = d;
         val = d;
         break;
        case (d === 11):
          displayVal = "Jack"
          val = 10;
          break;
        case (d === 12):
          displayVal = "Queen"
          val = 10;
          break;
        case (d === 13):
          displayVal = "King"
          val = 10;
     }
    cards.push({
    val,
    displayVal,
    suit: suits[s]
  } );

   }

 }
 return cards;
}

const deck = getDeck();
console.log(`Deck length equals 52? ${deck.length === 52}`);
</code>```

答:
Using Branch if-else

Actually, you are using conditions so go ahead with branched if-else

```<code>const getDeck = () => {
      const suits = ["Spades", "Hearts", "Diamonds", "Clubs"];
      let cards = [];

      for (let s = 0; s < suits.length; s++) {
        for (let d = 0; d < 13; d++) {
          let displayVal;
          let val;

          if (d === 1) {
            displayVal = "Ace";
            val = 11;
          } else if (d >= 2 && d <= 10) {
            displayVal = d;
            val = d;
          } else if (d === 11) {
            displayVal = "Jack";
            val = 10;
          } else if (d === 12) {
            displayVal = "Queen";
            val = 10;
          } else if (d === 13) {
            displayVal = "King";
            val = 10;
          } else {
            displayVal = "";
            val = 0;
          }
          cards.push({
            val,
            displayVal,
            suit: suits[s],
          });
        }
      }
      return cards;
    };

    const deck = getDeck();
    console.log(deck);
    console.log(`Deck length equals 52? ${deck.length === 52}`);
</code>```

Using Switch case

```<code>const getDeck = () => {
    const suits = ['Spades','Hearts','Diamonds','Clubs'];
    let cards = [];

    for(let s=0; s < suits.length; s++){

     for(let d = 0; d < 13; d++){
      let displayVal;
      let val;

       switch (true) {
        case (d === 1):
          displayVal = "Ace";
          val = 11;
          break;
        case (d >=2 && d <= 10):
           displayVal = d;
           val = d;
           break;
          case (d === 11):
            displayVal = "Jack"
            val = 10;
            break;
          case (d === 12):
            displayVal = "Queen"
            val = 10;
            break;
          case (d === 13):
            displayVal = "King"
            val = 10;
          default:
            displayVal =""
            val =0
       }
      cards.push({
      val,
      displayVal,
      suit: suits[s]
    } );

     }

   }
   return cards;
  }

  const deck = getDeck();
  console.log(deck);
  console.log(`Deck length equals 52? ${deck.length === 52}`);
</code>```

Body:
I've spent hours trying to figure out this exercise and stuck at this point.  I'm unable to get values from my switch statement to push to an array for "displayVal", and "val" variables.

const getDeck = () => {
  const suits = ['Spades','Hearts','Diamonds','Clubs'];
  let cards = [];

  for(let s=0; s < suits.length; s++){

   for(let d = 0; d < 13; d++){
    let displayVal;
    let val;

     switch (d) {
      case (d === 1):
        displayVal = "Ace";
        val = 11;
        break;
      case (d >=2 && d <= 10):
         displayVal = d;
         val = d;
         break;
        case (d === 11):
          displayVal = "Jack"
          val = 10;
          break;
        case (d === 12):
          displayVal = "Queen"
          val = 10;
          break;
        case (d === 13):
          displayVal = "King"
          val = 10;
     }
    cards.push({
    val,
    displayVal,
    suit: suits[s]
  } );

   }

 }
 return cards;
}

const deck = getDeck();
console.log(`Deck length equals 52? ${deck.length === 52}`);

Body:
Using Branch if-else

Actually, you are using conditions so go ahead with branched if-else

const getDeck = () => {
      const suits = ["Spades", "Hearts", "Diamonds", "Clubs"];
      let cards = [];

      for (let s = 0; s < suits.length; s++) {
        for (let d = 0; d < 13; d++) {
          let displayVal;
          let val;

          if (d === 1) {
            displayVal = "Ace";
            val = 11;
          } else if (d >= 2 && d <= 10) {
            displayVal = d;
            val = d;
          } else if (d === 11) {
            displayVal = "Jack";
            val = 10;
          } else if (d === 12) {
            displayVal = "Queen";
            val = 10;
          } else if (d === 13) {
            displayVal = "King";
            val = 10;
          } else {
            displayVal = "";
            val = 0;
          }
          cards.push({
            val,
            displayVal,
            suit: suits[s],
          });
        }
      }
      return cards;
    };

    const deck = getDeck();
    console.log(deck);
    console.log(`Deck length equals 52? ${deck.length === 52}`);

Using Switch case

const getDeck = () => {
    const suits = ['Spades','Hearts','Diamonds','Clubs'];
    let cards = [];

    for(let s=0; s < suits.length; s++){

     for(let d = 0; d < 13; d++){
      let displayVal;
      let val;

       switch (true) {
        case (d === 1):
          displayVal = "Ace";
          val = 11;
          break;
        case (d >=2 && d <= 10):
           displayVal = d;
           val = d;
           break;
          case (d === 11):
            displayVal = "Jack"
            val = 10;
            break;
          case (d === 12):
            displayVal = "Queen"
            val = 10;
            break;
          case (d === 13):
            displayVal = "King"
            val = 10;
          default:
            displayVal =""
            val =0
       }
      cards.push({
      val,
      displayVal,
      suit: suits[s]
    } );

     }

   }
   return cards;
  }

  const deck = getDeck();
  console.log(deck);
  console.log(`Deck length equals 52? ${deck.length === 52}`);


问:
How to force proportional scaling using Fabricjs?
There has been multiple changes in the Fabricjs API that affect the way  scaling points behave. One of the latest changes in version 4 (http://fabricjs.com/v4-breaking-changes) states that uniformScaling is now the way to go to force proportional scaling.

This is my test canvas:

```<code><canvas id="c" width="400" height="400" style="border:1px solid #ccc"></canvas>
</code>```

And this is my simple code snippet:

```<code>const canvas = (this.__canvas = new fabric.Canvas("c"));
canvas.uniformScaling = true;

const Add = () => {
  const rect = new fabric.Rect({
    left: 100,
    top: 100,
    fill: "yellow",
    width: 200,
    height: 100,
    stroke: "lightgreen",
  });
  canvas.add(rect);
  canvas.setActiveObject(rect);
};
Add();
</code>```

See a codepen illustrating the issue.

Why are the control points for resizing horizontally and vertically still there? What am I doing wrong?

答:
The uniformScaling property only determines the behavior of the corner resize controls. You can hide the side controls using the setControlsVisibility method.

http://fabricjs.com/docs/fabric.Object.html#setControlsVisibility

```<code>fabric.Rect.prototype.setControlsVisibility({
    ml: false,
    mt: false,
    mr: false,
    mb: false
});
</code>```

Body:
There has been multiple changes in the Fabricjs API that affect the way  scaling points behave. One of the latest changes in version 4 (http://fabricjs.com/v4-breaking-changes) states that uniformScaling is now the way to go to force proportional scaling.

This is my test canvas:

<canvas id="c" width="400" height="400" style="border:1px solid #ccc"></canvas>

And this is my simple code snippet:

const canvas = (this.__canvas = new fabric.Canvas("c"));
canvas.uniformScaling = true;

const Add = () => {
  const rect = new fabric.Rect({
    left: 100,
    top: 100,
    fill: "yellow",
    width: 200,
    height: 100,
    stroke: "lightgreen",
  });
  canvas.add(rect);
  canvas.setActiveObject(rect);
};
Add();

See a codepen illustrating the issue.

Why are the control points for resizing horizontally and vertically still there? What am I doing wrong?

Body:
The uniformScaling property only determines the behavior of the corner resize controls. You can hide the side controls using the setControlsVisibility method.

http://fabricjs.com/docs/fabric.Object.html#setControlsVisibility

fabric.Rect.prototype.setControlsVisibility({
    ml: false,
    mt: false,
    mr: false,
    mb: false
});


问:
Why is table being updated with NULL for foreign key?
I have a table called Paychecks that contains 294 rows. I've created a new table called TaxableEmployerPaidItems. Its primary key is a foreign key to Paychecks.

I am iterating over Paychecks and inserting a row into TaxableEmployerPaidItems for each row in Paychecks, then updating the foreign key. 294 rows are inserted into TaxableEmployerPaidItems as I would expect.

In Paychecks, the first 114 rows contain foreign keys to TaxableEmployerPaidItems, then after the 114th row all foreign keys are NULL.

Why would this be happening?

This is the code in my stored procedure:

```<code>BEGIN
    SET NOCOUNT ON;

    DECLARE @RowCnt INT
    DECLARE @TaxableEmployerPaidItemsIDInserted  INT

    SET @RowCnt = (SELECT COUNT(PaycheckID) FROM [dbo].[Paychecks])

    DECLARE @I INT
    SET @I = 1

    -- LOOP through rows of dbo.Paychecks
    WHILE (@I <= @RowCnt)
    BEGIN
        INSERT INTO [dbo].[TaxableEmployerPaidItems]
                (Item1Amount, Item1Description, Item2Amount, Item2Description, Item3Amount, Item3Description, Deleted)
        VALUES (NULL, NULL, NULL, NULL, NULL, NULL, 0)

        UPDATE [dbo].[Paychecks]
        SET TaxableEmployerPaidItemsId = @@IDENTITY
        WHERE PaycheckID = @I

        SET @I = @I + 1
    END
END
</code>```

答:
Your issue isn't reproducible as presented (see this DBFiddle). However you don't want to be doing this sort of thing in a loop. SQL is a set based language so you should therefore be attempting to solve your problem in a set based manner before reverting to a loop. In this case you just need to make use of the MERGE statement and the OUTPUT clause.

```<code>create table #NewId (id int, OtherId int);

merge dbo.PaidItems with (holdlock) as Target
using dbo.Paychecks as Source
on 1 = 0 -- force insert
when not matched by Target
  then insert (Item1Amount, Item1Description, Item2Amount, Item2Description, Item3Amount, Item3Description, Deleted)
       values (NULL,NULL,NULL,NULL,NULL,NULL,0)
output Inserted.PaidItemID, Source.PaycheckID into #NewId (id, OtherId);

update P set
  TaxableEmployerPaidItemsId = N.id
from dbo.Paychecks P
inner join #NewId N on N.OtherId = P.PaycheckID;

drop table #NewId;
</code>```

The reason you need a MERGE rather than an INSERT is because only in a MERGE are you able to access source table columns in the OUTPUT clause.

Note: If you find yourself at some point needing to use @@IDENTITY then in most cases you are safer using SCOPE_IDENTITY().

More info on MERGE including why to use the locking hint WITH (HOLDLOCK).

Body:
I have a table called Paychecks that contains 294 rows. I've created a new table called TaxableEmployerPaidItems. Its primary key is a foreign key to Paychecks.

I am iterating over Paychecks and inserting a row into TaxableEmployerPaidItems for each row in Paychecks, then updating the foreign key. 294 rows are inserted into TaxableEmployerPaidItems as I would expect.

In Paychecks, the first 114 rows contain foreign keys to TaxableEmployerPaidItems, then after the 114th row all foreign keys are NULL.

Why would this be happening?

This is the code in my stored procedure:

BEGIN
    SET NOCOUNT ON;

    DECLARE @RowCnt INT
    DECLARE @TaxableEmployerPaidItemsIDInserted  INT

    SET @RowCnt = (SELECT COUNT(PaycheckID) FROM [dbo].[Paychecks])

    DECLARE @I INT
    SET @I = 1

    -- LOOP through rows of dbo.Paychecks
    WHILE (@I <= @RowCnt)
    BEGIN
        INSERT INTO [dbo].[TaxableEmployerPaidItems]
                (Item1Amount, Item1Description, Item2Amount, Item2Description, Item3Amount, Item3Description, Deleted)
        VALUES (NULL, NULL, NULL, NULL, NULL, NULL, 0)

        UPDATE [dbo].[Paychecks]
        SET TaxableEmployerPaidItemsId = @@IDENTITY
        WHERE PaycheckID = @I

        SET @I = @I + 1
    END
END

Body:
Your issue isn't reproducible as presented (see this DBFiddle). However you don't want to be doing this sort of thing in a loop. SQL is a set based language so you should therefore be attempting to solve your problem in a set based manner before reverting to a loop. In this case you just need to make use of the MERGE statement and the OUTPUT clause.

create table #NewId (id int, OtherId int);

merge dbo.PaidItems with (holdlock) as Target
using dbo.Paychecks as Source
on 1 = 0 -- force insert
when not matched by Target
  then insert (Item1Amount, Item1Description, Item2Amount, Item2Description, Item3Amount, Item3Description, Deleted)
       values (NULL,NULL,NULL,NULL,NULL,NULL,0)
output Inserted.PaidItemID, Source.PaycheckID into #NewId (id, OtherId);

update P set
  TaxableEmployerPaidItemsId = N.id
from dbo.Paychecks P
inner join #NewId N on N.OtherId = P.PaycheckID;

drop table #NewId;

The reason you need a MERGE rather than an INSERT is because only in a MERGE are you able to access source table columns in the OUTPUT clause.

Note: If you find yourself at some point needing to use @@IDENTITY then in most cases you are safer using SCOPE_IDENTITY().

More info on MERGE including why to use the locking hint WITH (HOLDLOCK).


问:
data access problem in jsf
I have the following class-files:

```<code>class RowData {
...
  ArrayList<String> valueMap;
...
}

class Bean {
...
  public List<RowData> getData() {
  ...
  }
}
</code>```

jsf code snippet:

```<code>...
<h:form>
  <rich:dataTable id="overviewTable" value="#{bean.getData()}" var="row">

    <c:forEach items="#{row.valueMap}" var="r">

      <rich:column>
        <h:outputText value="#{r}" />
      </rich:column>
    </c:forEach>
  </rich:dataTable>
</h:form>
...
</code>```

Unfortunately, the table doesn't appear. What's wrong? The page doesn't show an error or something, the table is just not there (in this version I skipped all the getter and setter...). When I want to access other data from the bean, it works, so the whole setup should be ok.

答:
you should not write the "get" and  the "()" in  "getData()",
also, I dont think you need the "foreach" in a datatable

look at this example from
http://richfaces-showcase.appspot.com/richfaces/component-sample.jsf?demo=dataTable&sample=tableStyling&skin=blueSky

```<code><rich:dataTable value="#{carsBean.allInventoryItems}" var="car"
        id="table" rows="20" rowClasses="odd-row, even-row"
        styleClass="stable">
        <rich:column accept="#{carsFiteringBean.acceptVendor}">
            <f:facet name="header">
                <h:outputText value="Vendor " />
            </f:facet>
            <h:outputText value="#{car.vendor}" />
        </rich:column>
        <rich:column>
            <f:facet name="header">
                <h:outputText value="Model" />
            </f:facet>
            <h:outputText value="#{car.model}" />
        </rich:column>
        <rich:column>
            <f:facet name="header">
                <h:outputText value="Price" />
            </f:facet>
            <h:outputText value="#{car.price}" />
        </rich:column>
        <rich:column filter="#{carsFilteringBean.mileageFilterImpl}">
            <f:facet name="header">
                <h:outputText value="Mileage" />
            </f:facet>
            <h:outputText value="#{car.mileage}" />
        </rich:column>
        <rich:column>
            <f:facet name="header">
                <h:outputText value="VIN " />
            </f:facet>
            <h:outputText value="#{car.vin}" />
        </rich:column>
    </rich:dataTable>
</h:form>
</code>```

Title: data access problem in jsf

Body:
I have the following class-files:

class RowData {
...
  ArrayList<String> valueMap;
...
}

class Bean {
...
  public List<RowData> getData() {
  ...
  }
}

jsf code snippet:

...
<h:form>
  <rich:dataTable id="overviewTable" value="#{bean.getData()}" var="row">

    <c:forEach items="#{row.valueMap}" var="r">

      <rich:column>
        <h:outputText value="#{r}" />
      </rich:column>
    </c:forEach>
  </rich:dataTable>
</h:form>
...

Unfortunately, the table doesn't appear. What's wrong? The page doesn't show an error or something, the table is just not there (in this version I skipped all the getter and setter...). When I want to access other data from the bean, it works, so the whole setup should be ok.

Body:
you should not write the "get" and  the "()" in  "getData()",
also, I dont think you need the "foreach" in a datatable

look at this example from
http://richfaces-showcase.appspot.com/richfaces/component-sample.jsf?demo=dataTable&sample=tableStyling&skin=blueSky

<rich:dataTable value="#{carsBean.allInventoryItems}" var="car"
        id="table" rows="20" rowClasses="odd-row, even-row"
        styleClass="stable">
        <rich:column accept="#{carsFiteringBean.acceptVendor}">
            <f:facet name="header">
                <h:outputText value="Vendor " />
            </f:facet>
            <h:outputText value="#{car.vendor}" />
        </rich:column>
        <rich:column>
            <f:facet name="header">
                <h:outputText value="Model" />
            </f:facet>
            <h:outputText value="#{car.model}" />
        </rich:column>
        <rich:column>
            <f:facet name="header">
                <h:outputText value="Price" />
            </f:facet>
            <h:outputText value="#{car.price}" />
        </rich:column>
        <rich:column filter="#{carsFilteringBean.mileageFilterImpl}">
            <f:facet name="header">
                <h:outputText value="Mileage" />
            </f:facet>
            <h:outputText value="#{car.mileage}" />
        </rich:column>
        <rich:column>
            <f:facet name="header">
                <h:outputText value="VIN " />
            </f:facet>
            <h:outputText value="#{car.vin}" />
        </rich:column>
    </rich:dataTable>
</h:form>


问:
Default Javascript objects are very slow when large?
I am doing a modified version of collecting word co-occurrences, so I wrote my own javascript, and I am tracking the occurrences in three objects. However, once the objects get large (~8 million, 3 million, and 172000) a function that took 5 seconds per 100000 sentences now takes minutes to do one sentence with 30 words (30 tokens). I am nowhere near my RAM cap (I have 12 more GBs of RAM it could be using, and the program is only using 2.2GB). Using Node.js v17.3.1.

Why does my function take so long when the objects get bigger (even though the sentences remain the same length)? Should I be using a different object besides Javascript's default object, or is there a way improve the speed of access and setting these objects when they are so big?

Code:

```<code>  let posCounts = {};
  let negCounts = {};
  // the number of times each word occurs
  let wordCounts = {};
  let tokens = // some function that gets tokens;
    for (let k = 0; k < tokens.length; k++) {
      // count word occurences
      if (tokens[k] in wordCounts) {
        wordCounts[tokens[k]] += 1;
      } else {
        wordCounts[tokens[k]] = 1;
      }
      for(let tok = k + 1; tok < tokens.length; tok++) {
        if (tok == k) {
          // avoid word to self cooccurrence
          // should no longer be possible
          continue;
        } else {
           // check which form of the cooccurence exists already in either count
           actual_tok = (tokens[k] + "-" + tokens[tok]);
           if(actual_tok in posCounts || actual_tok in negCounts) {
             // no-op
           } else {
             actual_tok = (tokens[tok] + "-" + tokens[k]);
           }

           // condition set before this block of code
           if(condition) {
             if (actual_tok in posCounts) {
               posCounts[actual_tok] += 1;
             } else {
               posCounts[actual_tok] = 1;
             }
           } else {
             if (actual_tok in negCounts) {
               negCounts[actual_tok] += 1;
             } else {
               negCounts[actual_tok] = 1;
             }
           }
         }
      }

    }
</code>```

Update: I've tried increasing the heap size via node train_matrices.js --max-old-space-size=12288 and node train_matrices.js --max_old_space_size=12288 (underline instead of dash), and that didn't work either.

答:
The answer was to both use the increase memory flag node <YOUR_FILE_NAME>.js --max-old-space-size=12288 and change to using a Map instead of an object - thanks to @jfriend00 and @Norman Breau for the suggestions. That said, maps have a max capacity of 2^24 items or 1 GB, so I ended up using a modified version of the BigMap from this stackoverflow (modified to limit the total number of items still - ended up running completely out of RAM).

Modified code (you can replace BigMap with Map if you want):

```<code>  let posCounts = new BigMap();
  let negCounts = new BigMap();
  let wordCounts = new BigMap();
  let actual_tok;
    tokens = // some code
    // mark every cooccurrence
    for (let k = 0; k < tokens.length; k++) {
      // count word occurences
      if (wordCounts.has(tokens[k])) {
        wordCounts.set(tokens[k], wordCounts.get(tokens[k]) + 1);
      } else {
        wordCounts.set(tokens[k], 1);
      }
      for(let tok = k + 1; tok < tokens.length; tok++) {
        if (tok == k) {
          // avoid word to self cooccurrence
          // should no longer be possible
          continue;
        } else {
           // check which form of the cooccurence exists already in either count
           actual_tok = (tokens[k] + "-" + tokens[tok]);
           if(posCounts.has(actual_tok) || negCounts.has(actual_tok)) {
             // no-op
           } else {
             actual_tok = (tokens[tok] + "-" + tokens[k]);
           }

           if(condition) {
             if (posCounts.has(actual_tok)) {
               posCounts.set(actual_tok, posCounts.get(actual_tok) + 1);
             } else {
               posCounts.set(actual_tok, 1);
             }
           } else {
             if (negCounts.has(actual_tok)) {
               negCounts.set(actual_tok, negCounts.get(actual_tok) + 1);
             } else {
               negCounts.set(actual_tok, 1);
             }
           }
         }
      }

    }
  }
</code>```

Body:
I am doing a modified version of collecting word co-occurrences, so I wrote my own javascript, and I am tracking the occurrences in three objects. However, once the objects get large (~8 million, 3 million, and 172000) a function that took 5 seconds per 100000 sentences now takes minutes to do one sentence with 30 words (30 tokens). I am nowhere near my RAM cap (I have 12 more GBs of RAM it could be using, and the program is only using 2.2GB). Using Node.js v17.3.1.

Why does my function take so long when the objects get bigger (even though the sentences remain the same length)? Should I be using a different object besides Javascript's default object, or is there a way improve the speed of access and setting these objects when they are so big?

Code:

  let posCounts = {};
  let negCounts = {};
  // the number of times each word occurs
  let wordCounts = {};
  let tokens = // some function that gets tokens;
    for (let k = 0; k < tokens.length; k++) {
      // count word occurences
      if (tokens[k] in wordCounts) {
        wordCounts[tokens[k]] += 1;
      } else {
        wordCounts[tokens[k]] = 1;
      }
      for(let tok = k + 1; tok < tokens.length; tok++) {
        if (tok == k) {
          // avoid word to self cooccurrence
          // should no longer be possible
          continue;
        } else {
           // check which form of the cooccurence exists already in either count
           actual_tok = (tokens[k] + "-" + tokens[tok]);
           if(actual_tok in posCounts || actual_tok in negCounts) {
             // no-op
           } else {
             actual_tok = (tokens[tok] + "-" + tokens[k]);
           }

           // condition set before this block of code
           if(condition) {
             if (actual_tok in posCounts) {
               posCounts[actual_tok] += 1;
             } else {
               posCounts[actual_tok] = 1;
             }
           } else {
             if (actual_tok in negCounts) {
               negCounts[actual_tok] += 1;
             } else {
               negCounts[actual_tok] = 1;
             }
           }
         }
      }

    }

Update: I've tried increasing the heap size via node train_matrices.js --max-old-space-size=12288 and node train_matrices.js --max_old_space_size=12288 (underline instead of dash), and that didn't work either.

Body:
The answer was to both use the increase memory flag node <YOUR_FILE_NAME>.js --max-old-space-size=12288 and change to using a Map instead of an object - thanks to @jfriend00 and @Norman Breau for the suggestions. That said, maps have a max capacity of 2^24 items or 1 GB, so I ended up using a modified version of the BigMap from this stackoverflow (modified to limit the total number of items still - ended up running completely out of RAM).

Modified code (you can replace BigMap with Map if you want):

  let posCounts = new BigMap();
  let negCounts = new BigMap();
  let wordCounts = new BigMap();
  let actual_tok;
    tokens = // some code
    // mark every cooccurrence
    for (let k = 0; k < tokens.length; k++) {
      // count word occurences
      if (wordCounts.has(tokens[k])) {
        wordCounts.set(tokens[k], wordCounts.get(tokens[k]) + 1);
      } else {
        wordCounts.set(tokens[k], 1);
      }
      for(let tok = k + 1; tok < tokens.length; tok++) {
        if (tok == k) {
          // avoid word to self cooccurrence
          // should no longer be possible
          continue;
        } else {
           // check which form of the cooccurence exists already in either count
           actual_tok = (tokens[k] + "-" + tokens[tok]);
           if(posCounts.has(actual_tok) || negCounts.has(actual_tok)) {
             // no-op
           } else {
             actual_tok = (tokens[tok] + "-" + tokens[k]);
           }

           if(condition) {
             if (posCounts.has(actual_tok)) {
               posCounts.set(actual_tok, posCounts.get(actual_tok) + 1);
             } else {
               posCounts.set(actual_tok, 1);
             }
           } else {
             if (negCounts.has(actual_tok)) {
               negCounts.set(actual_tok, negCounts.get(actual_tok) + 1);
             } else {
               negCounts.set(actual_tok, 1);
             }
           }
         }
      }

    }
  }