Title: How would I vectorize a function in pandas that returns a list?

Body:
I've been reading about how to optimize pandas code for speed, and I'm trying to refactor my code, changing from iterrows() to vectorization. Here is an example of the old code and its result:

Old Code

import pandas as pd
def repeatAsList(value):
    return([value, value])
df = pd.DataFrame({"values": [1,2,3], "repeatedAsList":None})
for index, row in df.iterrows():
    df.at[index,"repeatedAsList"] = repeatAsList(row['values'])
df

Old Result

+--------+----------------+
| values | repeatedAsList |
+--------+----------------+
|      1 | [1, 1]         |
|      2 | [2, 2]         |
|      3 | [3, 3]         |
+--------+----------------+

New Code

import pandas as pd
def repeatAsList(value):
    return([value, value])
df = pd.DataFrame({"values": [1,2,3], "repeatedAsList":None})
df["repeatedAsList"] = repeatAsList(df["values"])

New Result

ValueError: Length of values does not match length of index

I'd like to understand why the new code above fails, and if it's possible to run a different way and achieve speed improvements from the old code. I feel like I'm missing a key point of vectorization, and it would be nice to learn why the values have to be scalar.

Body:
I believe you can do it faster by creating an array using the values:

df['repeatedAsList'] = [[x,x] for x in (df['values'].values)]
print(df)

Output:

  values repeatedAsList
0       1         [1, 1]
1       2         [2, 2]
2       3         [3, 3]

Regarding speed:

Here you can see the speed for larger dataframes and accesing them with values, tolist() and some other functions. I believe the fastest way to access the values is .values for larger datasets (100+ rows): getting value error when tried to make subplots for list of dataframe with matplotlib?

                        1      10     100    1000   10000
len 1               0.0038  0.0046  0.0032  0.0037  0.0035
len 10              0.0032  0.0032  0.0032  0.0034  0.0035
len 100             0.0032  0.0052  0.0052  0.0053  0.0035
len 1000            0.0037  0.0036  0.0041  0.0039  0.0043
len 10000           0.0040  0.0038  0.0045  0.0043  0.0123
len(tolist) 1       0.0051  0.0075  0.0175  0.1629  1.6579
len(tolist) 10      0.0051  0.0059  0.0175  0.1588  1.9253
len(tolist) 100     0.0049  0.0097  0.0196  0.1635  1.7422
len(tolist) 1000    0.0053  0.0065  0.0198  0.1831  1.9897
len(tolist) 10000   0.0057  0.0069  0.0218  0.1995  2.2426
len(values) 1       0.0083  0.0097  0.0073  0.0074  0.0074
len(values) 10      0.0073  0.0072  0.0073  0.0107  0.0087
len(values) 100     0.0075  0.0094  0.0109  0.0072  0.0081
len(values) 1000    0.0081  0.0082  0.0081  0.0085  0.0088
len(values) 10000   0.0087  0.0084  0.0103  0.0101  0.0327
shape   1           0.1108  0.0838  0.0789  0.0779  0.0780
shape   10          0.0764  0.0770  0.0771  0.1118  0.0806
shape   100         0.0952  0.0826  0.1013  0.0800  0.0889
shape   1000        0.0881  0.0863  0.0867  0.0938  0.1063
shape   10000       0.0905  0.0999  0.1043  0.1013  0.2384


来源: stackexchange

问:
Property validation failure in Cloudformation
The following snippet is from a Cloudformation formation template:

```<code>...
LambdaFunctionAssociations:
  - !If
    - ProtectDistribution
    -
      - EventType: viewer-request
        LambdaFunctionARN: !GetAtt LambdaEdgeProtection.Outputs.CheckAuthHandler
      - EventType: origin-response
        LambdaFunctionARN: !GetAtt LambdaEdgeProtection.Outputs.HttpHeadersHandler
    - !Ref AWS::NoValue
...
</code>```

It's a part of a DefaultCacheBehavior within a DistributionConfig of a CloudFront distribution. It's giving me this error when trying to create the stack:

Property validation failure: [Value of property {/DistributionConfig/DefaultCacheBehavior/LambdaFunctionAssociations/0} does not match type {Object}]

Where am I going wrong please?

答:
In - !If condition of your code you have already declared the array before the if condition and if the condition gets true, - - EventType: viewer-request here you are again providing array, which is wrong.
You should try it this way,

```<code>...
LambdaFunctionAssociations:
  - !If
    - ProtectDistribution
    - EventType: viewer-request
      LambdaFunctionARN: !GetAtt LambdaEdgeProtection.Outputs.CheckAuthHandler
    - !Ref AWS::NoValue
  - !If
    - ProtectDistribution
    - EventType: origin-response
      LambdaFunctionARN: !GetAtt LambdaEdgeProtection.Outputs.HttpHeadersHandler
    - !Ref AWS::NoValue
...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The following snippet is from a Cloudformation formation template:

...
LambdaFunctionAssociations:
  - !If
    - ProtectDistribution
    -
      - EventType: viewer-request
        LambdaFunctionARN: !GetAtt LambdaEdgeProtection.Outputs.CheckAuthHandler
      - EventType: origin-response
        LambdaFunctionARN: !GetAtt LambdaEdgeProtection.Outputs.HttpHeadersHandler
    - !Ref AWS::NoValue
...

It's a part of a DefaultCacheBehavior within a DistributionConfig of a CloudFront distribution. It's giving me this error when trying to create the stack:

Property validation failure: [Value of property {/DistributionConfig/DefaultCacheBehavior/LambdaFunctionAssociations/0} does not match type {Object}]

Where am I going wrong please?

Body:
In - !If condition of your code you have already declared the array before the if condition and if the condition gets true, - - EventType: viewer-request here you are again providing array, which is wrong.
You should try it this way,

...
LambdaFunctionAssociations:
  - !If
    - ProtectDistribution
    - EventType: viewer-request
      LambdaFunctionARN: !GetAtt LambdaEdgeProtection.Outputs.CheckAuthHandler
    - !Ref AWS::NoValue
  - !If
    - ProtectDistribution
    - EventType: origin-response
      LambdaFunctionARN: !GetAtt LambdaEdgeProtection.Outputs.HttpHeadersHandler
    - !Ref AWS::NoValue
...


问:
JSON output format for Hive Query results
Is there any way to convert the Hive query result in JSON format?</p>

答:
list of json objects:

If you want to covent the output to json format and then making a collection out of it meaning: [{json1},{json2},{json3}]...
you need to know that collect() function treat it as string which is wrong.

so what is needed for having a collection of json-formatted out put is wrapping them with from-json function too:

```<code>create temporary function collect as 'brickhouse.udf.collect.CollectUDAF';
create temporary function to_json as 'brickhouse.udf.json.ToJsonUDF';
create temporary function from_json as 'brickhouse.udf.json.FromJsonUDF';
collect(from_json(to_json(named_struct("locale", locale, "createdtime",  created_time)), 'map<string,string>')) as list_json_object,
</code>```

ContentLicense: CC BY-SA 3.0

Body:
list of json objects:

If you want to covent the output to json format and then making a collection out of it meaning: [{json1},{json2},{json3}]...
you need to know that collect() function treat it as string which is wrong.

so what is needed for having a collection of json-formatted out put is wrapping them with from-json function too:

create temporary function collect as 'brickhouse.udf.collect.CollectUDAF';
create temporary function to_json as 'brickhouse.udf.json.ToJsonUDF';
create temporary function from_json as 'brickhouse.udf.json.FromJsonUDF';
collect(from_json(to_json(named_struct("locale", locale, "createdtime",  created_time)), 'map<string,string>')) as list_json_object,


问:
Mocking raw String in unit testing for Spring Boot service layer
I am trying to write unit tests for a service layer method finding Players by name. The method calls a JPA repository method and returns a Page object.
I want the test to verify that the correct method from repository was indeed called.

The test class

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = {PlayerService.class})
public class PlayerServiceTest {

    @Autowired
    PlayerService playerService;

    @MockBean
    PlayerRepository playerRepository;

    @Test
    public void whenListPlayersByName_thenShouldCallFindMethodWithPageableArgAndNameArg(){
        Pageable pageableStub = Mockito.mock(Pageable.class);
        String name = "xxx";
        Mockito.when(playerRepository.findByNameContainingIgnoreCase(any(String.class), any(Pageable.class)))
                .thenReturn(any(Page.class));

        //1st attempt:
        //playerService.listPlayersByName(name, pageableStub);
        playerService.listPlayersByName(eq(name), pageableStub);

        verify(playerRepository).findByNameContainingIgnoreCase(any(String.class), any(Pageable.class));
    }
</code>```

My problem

The test fails with a message:

```<code>org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
2 matchers expected, 1 recorded:
-> at com.domin0x.player.PlayerServiceTest.whenListPlayersByName_thenShouldCallFindMethodWithPageableArgAndNameArg(PlayerServiceTest.java:60)

This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq("String by matcher"));
</code>```

Following the advice I changed the name to eq(name) but that results in a different issue:

```<code>Argument(s) are different! Wanted:
com.domin0x.player.PlayerRepository#0 bean.findByNameContainingIgnoreCase(
    <any java.lang.String>, <any org.springframework.data.domain.Pageable>);

Actual invocation has different arguments:
com.domin0x.player.PlayerRepository#0 bean.findByNameContainingIgnoreCase(
null,     Mock for Pageable, hashCode: 309271464
;
</code>```

Any advice what should I change in the test?

The service class

```<code>@Service
public class PlayerService {
    public Page<Player> listPlayersByName(String name, Pageable pageable) {
        return repository.findByNameContainingIgnoreCase(name, pageable);
    }
</code>```

The repository interface

```<code>@Repository
public interface PlayerRepository extends JpaRepository<Player, Integer> {

    Page<Player> findByNameContainingIgnoreCase(String name, Pageable pageable);
}

</code>```

答:
It took me a while to figure this one out.

in thenReturn, you are calling any(Page.class).  Instead, you should return either an actual Page object, or a mock Page object).

It's also better to avoid using "any" unless you have no way to know the identity.

```<code>Page<Player> pageStub = (Page<Player>)Mockito.mock(Page.class);
Mockito.when(playerRepository.findByNameContainingIgnoreCase(name, pageableStub))
            .thenReturn(pageStub);

Page<PlayerStub> result = playerService.listPlayersByName(name, pageableStub);

assertSame(pageStub, result);

// No need to call verify, since it couldn't get pageStub without calling the correctly stubbed method.
</code>```

To clarify:  eq(), any(), and other "matchers" should only be used as arguments to methods in when and verify.  They should never be passed to  the test subject, nor returned from any mocked object.

Body:
I am trying to write unit tests for a service layer method finding Players by name. The method calls a JPA repository method and returns a Page object.
I want the test to verify that the correct method from repository was indeed called.

The test class

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {PlayerService.class})
public class PlayerServiceTest {

    @Autowired
    PlayerService playerService;

    @MockBean
    PlayerRepository playerRepository;

    @Test
    public void whenListPlayersByName_thenShouldCallFindMethodWithPageableArgAndNameArg(){
        Pageable pageableStub = Mockito.mock(Pageable.class);
        String name = "xxx";
        Mockito.when(playerRepository.findByNameContainingIgnoreCase(any(String.class), any(Pageable.class)))
                .thenReturn(any(Page.class));

        //1st attempt:
        //playerService.listPlayersByName(name, pageableStub);
        playerService.listPlayersByName(eq(name), pageableStub);

        verify(playerRepository).findByNameContainingIgnoreCase(any(String.class), any(Pageable.class));
    }

My problem

The test fails with a message:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
2 matchers expected, 1 recorded:
-> at com.domin0x.player.PlayerServiceTest.whenListPlayersByName_thenShouldCallFindMethodWithPageableArgAndNameArg(PlayerServiceTest.java:60)

This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq("String by matcher"));

Following the advice I changed the name to eq(name) but that results in a different issue:

Argument(s) are different! Wanted:
com.domin0x.player.PlayerRepository#0 bean.findByNameContainingIgnoreCase(
    <any java.lang.String>, <any org.springframework.data.domain.Pageable>);

Actual invocation has different arguments:
com.domin0x.player.PlayerRepository#0 bean.findByNameContainingIgnoreCase(
null,     Mock for Pageable, hashCode: 309271464
;

Any advice what should I change in the test?

The service class

@Service
public class PlayerService {
    public Page<Player> listPlayersByName(String name, Pageable pageable) {
        return repository.findByNameContainingIgnoreCase(name, pageable);
    }

The repository interface

@Repository
public interface PlayerRepository extends JpaRepository<Player, Integer> {

    Page<Player> findByNameContainingIgnoreCase(String name, Pageable pageable);
}

Body:
It took me a while to figure this one out.

in thenReturn, you are calling any(Page.class).  Instead, you should return either an actual Page object, or a mock Page object).

It's also better to avoid using "any" unless you have no way to know the identity.

Page<Player> pageStub = (Page<Player>)Mockito.mock(Page.class);
Mockito.when(playerRepository.findByNameContainingIgnoreCase(name, pageableStub))
            .thenReturn(pageStub);

Page<PlayerStub> result = playerService.listPlayersByName(name, pageableStub);

assertSame(pageStub, result);

// No need to call verify, since it couldn't get pageStub without calling the correctly stubbed method.

To clarify:  eq(), any(), and other "matchers" should only be used as arguments to methods in when and verify.  They should never be passed to  the test subject, nor returned from any mocked object.


问:
Grab form values to avoid page reload when submitting a MVC form
I have a ASP.NET razor form that looks something like:

```<code>@using (Html.BeginForm("CreateUser", "Users", FormMethod.Post, new { role = "form", id="create-user-form" }))
{

@Html.LabelFor(model => model.LastName)
                            @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })

}

Then in my controller:

public ActionResult CreateUser(UserViewModel viewModel)
{

}
</code>```

Using jQuery, is it possible for me to grab the variables in the form and submit it to my controller such that the page doesn't reload when the form submits?

Currently it does a post back and the page reloads, which I am trying to avoid in this situation.

答:
You can either set up an AJAX call in jQuery, or you can utilize the jQuery Unobtrusive Ajax Nuget Package (I am more familiar with setting up this).

Using this package, you can take advantage of the Ajax submitform helper attribute.

The main purpose of this is to have one div section (encapsulated within the AJAX form element) that contains the input fields that are submitted. Then, when submitted, it calls a Partial View Result (that requires a return PartialView(); ) and displays it in your original parent view, without reloading the page.

Here is an example setup:

```<code><div class="row">
    <div class="col-md-4"></div>
    <div class="col-md-4">
    @{using (Ajax.BeginForm("PartialViewResultName", "ControllerName", null, new AjaxOptions
      {
          HttpMethod = "GET",
          UpdateTargetId = "targetDivID",
          InsertionMode = InsertionMode.Replace,
          LoadingElementId = "targetDivLoadingID"
      }, new
      {
          id = "formID"
      }))
      {
          // Where your Html code that will be submitted goes
          <button type="submit">submit</button>
      }}
    </div>
    <div class="col-md-4"></div>
</div>
<div class="row">
    <div class="col-md-12">
        <div id="targetDivID"></div>
    </div>
</div>
</code>```

Body:
I have a ASP.NET razor form that looks something like:

@using (Html.BeginForm("CreateUser", "Users", FormMethod.Post, new { role = "form", id="create-user-form" }))
{

@Html.LabelFor(model => model.LastName)
                            @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })

}

Then in my controller:

public ActionResult CreateUser(UserViewModel viewModel)
{

}

Using jQuery, is it possible for me to grab the variables in the form and submit it to my controller such that the page doesn't reload when the form submits?

Currently it does a post back and the page reloads, which I am trying to avoid in this situation.

Body:
You can either set up an AJAX call in jQuery, or you can utilize the jQuery Unobtrusive Ajax Nuget Package (I am more familiar with setting up this).

Using this package, you can take advantage of the Ajax submitform helper attribute.

The main purpose of this is to have one div section (encapsulated within the AJAX form element) that contains the input fields that are submitted. Then, when submitted, it calls a Partial View Result (that requires a return PartialView(); ) and displays it in your original parent view, without reloading the page.

Here is an example setup:

<div class="row">
    <div class="col-md-4"></div>
    <div class="col-md-4">
    @{using (Ajax.BeginForm("PartialViewResultName", "ControllerName", null, new AjaxOptions
      {
          HttpMethod = "GET",
          UpdateTargetId = "targetDivID",
          InsertionMode = InsertionMode.Replace,
          LoadingElementId = "targetDivLoadingID"
      }, new
      {
          id = "formID"
      }))
      {
          // Where your Html code that will be submitted goes
          <button type="submit">submit</button>
      }}
    </div>
    <div class="col-md-4"></div>
</div>
<div class="row">
    <div class="col-md-12">
        <div id="targetDivID"></div>
    </div>
</div>


问:
How to detect if app is being operating by automated testing tools?
Sometimes, hackers may use automation tools, such as Robotium、Espresso、UiAutomator2、Appium, to automatically operate my customers' apps, which will integrate our SDK, to earn profits.

So how to detect if current app is being operating by such automated testing tools (except checking the service and process) without editting the app itself? Thanks~

答:
Well, the easiest way is the strict Proguard configuration when you make a release build.

If you are assuming somebody will create a script using Appium+Espresso/UiAutmator to communicate with your app, make sure you don't have the following in your proguard rules:

```<code>-dontwarn com.google.android.material.**
-keep class com.google.android.material.** { *; }

-dontwarn androidx.**.
-keep class androidx.** { *; }
-keep interface androidx.** { *; }

-dontwarn android.support.v4.**
-keep class android.support.v4.** { *; }

-dontwarn android.support.v7.**
-keep class android.support.v7.** { *; }
</code>```

In this case, your app simply won't be suitable for test automation.

Also, if you do have your own tests, make sure there is no way to start them for release APK. Mostly like no harm, but I have seen it once :)

Body:
Well, the easiest way is the strict Proguard configuration when you make a release build.

If you are assuming somebody will create a script using Appium+Espresso/UiAutmator to communicate with your app, make sure you don't have the following in your proguard rules:

-dontwarn com.google.android.material.**
-keep class com.google.android.material.** { *; }

-dontwarn androidx.**.
-keep class androidx.** { *; }
-keep interface androidx.** { *; }

-dontwarn android.support.v4.**
-keep class android.support.v4.** { *; }

-dontwarn android.support.v7.**
-keep class android.support.v7.** { *; }

In this case, your app simply won't be suitable for test automation.

Also, if you do have your own tests, make sure there is no way to start them for release APK. Mostly like no harm, but I have seen it once :)


问:
Getting back the exact address using building number and postcode - UWP - MapService
so i'm trying to retrieve the full address using the MapLocationFinder class in MapService for UWP.

I'm using the function FindLocationsAsync and I'm passing in the following:

```<code>MapLocationFinderResult result = await
                    MapLocationFinder.FindLocationsAsync(BuildingNumber + ", " + PostCode, null);
</code>```

Where building number is 20 and postcode is SW11 1BP. For some reason, this isn't returning the street name... the Address variable does not contain anything apart from that it is in London. What am I doing wrong? I thought I could do a full address lookup by postcode and street number.

答: The string you're searching for "20, SW11 1BP" isn't a well defined query string. If you want an exact address match you'll need to supply the house number and street, the service can't work with just a house number and post code. The result you're getting is the best match given the ambiguous string - it's finding just the post code. The lat/long returned will be the center of the post code which may or may not be near the street, so a reverse geocode on that lat/long may not return the correct street and definitely won't be accurate to that building number.</p>

Body:
so i'm trying to retrieve the full address using the MapLocationFinder class in MapService for UWP.

I'm using the function FindLocationsAsync and I'm passing in the following:

MapLocationFinderResult result = await
                    MapLocationFinder.FindLocationsAsync(BuildingNumber + ", " + PostCode, null);

Where building number is 20 and postcode is SW11 1BP. For some reason, this isn't returning the street name... the Address variable does not contain anything apart from that it is in London. What am I doing wrong? I thought I could do a full address lookup by postcode and street number.


问:
Show full trace of errors during mvn test
When I run Junit tests mvn test it gives me the following trace for a given error:

```<code>InvalidEmailTest.setUp:45->BasicTest.getAssertedSubElement:461 » StaleElementReference
</code>```

So it shows me the entry point method and the method where the exception occurred. Is it possible to see the same thing with every function called in between? That would make debugging a lot easier

What it makes my call trace look like:

```<code>* InvalidEmailTest.setUp
  * BasicTest.getAssertSubElement
</code>```

What it actually is:

```<code>* InvalidEmailTest.setUp
  * cHelper.accessSpecificGestion
     * mHelper.goTab
         * mHelper.accessOffice
             * BasicTest.getFirstChildByText
                 * BasicTest.getAssertSubElement
</code>```

Is there a way to see on which line of each the exception occurred so I can pinpoint exactly where the error occurs in the mvn test results?

答:
As @khmarbaise mentioned, you can configure the trimStackTrace property to false in the maven surefire plugin. Your build section will look like:

```<code><build>
  <plugins>
    <!-- Others plugins declaration -->
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <configuration>
        <trimStackTrace>false</trimStackTrace>
      </configuration>
    </plugin>
  </plugins>
</build>
</code>```

Also if you like you could control the behavior via command line:

You could declare a property:

```<code><properties>
  <!-- Others properties declaration -->
  <trimStackTrace>true</trimStackTrace>
</properties>
</code>```

And controlling the plugin with it:

```<code><build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <configuration>
        <trimStackTrace>${trimStackTrace}</trimStackTrace>
      </configuration>
    </plugin>
  </plugins>
</build>
</code>```

Then if you run the mvn test, you will get the default trimmed output, or if you run the mvn test -DtrimStackTrace=false, you will get the output with the details.

Body:
When I run Junit tests mvn test it gives me the following trace for a given error:

InvalidEmailTest.setUp:45->BasicTest.getAssertedSubElement:461 » StaleElementReference

So it shows me the entry point method and the method where the exception occurred. Is it possible to see the same thing with every function called in between? That would make debugging a lot easier

What it makes my call trace look like:

* InvalidEmailTest.setUp
  * BasicTest.getAssertSubElement

What it actually is:

* InvalidEmailTest.setUp
  * cHelper.accessSpecificGestion
     * mHelper.goTab
         * mHelper.accessOffice
             * BasicTest.getFirstChildByText
                 * BasicTest.getAssertSubElement

Is there a way to see on which line of each the exception occurred so I can pinpoint exactly where the error occurs in the mvn test results?

Body:
As @khmarbaise mentioned, you can configure the trimStackTrace property to false in the maven surefire plugin. Your build section will look like:

<build>
  <plugins>
    <!-- Others plugins declaration -->
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <configuration>
        <trimStackTrace>false</trimStackTrace>
      </configuration>
    </plugin>
  </plugins>
</build>

Also if you like you could control the behavior via command line:

You could declare a property:

<properties>
  <!-- Others properties declaration -->
  <trimStackTrace>true</trimStackTrace>
</properties>

And controlling the plugin with it:

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <configuration>
        <trimStackTrace>${trimStackTrace}</trimStackTrace>
      </configuration>
    </plugin>
  </plugins>
</build>

Then if you run the mvn test, you will get the default trimmed output, or if you run the mvn test -DtrimStackTrace=false, you will get the output with the details.


问:
How to write collapsable navbar from Bootstrap 3 in Bootstrap 4?
I need a little help. Here's my code i wrote in Bootstrap-3 for collapse-navbar but when i want to write it in Bootstrap-4 it doesn't work. Whatever I tried from the commands failed. Can someone help me and tell me what to do or write.</p>

```<code><button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#collapsable-nav" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>

    <div id="collapsable-nav" class="collapse navbar-collapse">
       <ul id="nav-list" class="nav navbar-nav navbar-right">
        <li>
          <a href="menu-categories.html">
            <span class="cutlery"></span><br class="hidden-xs"> Menu</a>
        </li>
        <li>
          <a href="#">
            <span class="info-sign"></span><br class="hidden-xs"> About</a>
        </li>
        <li>
          <a href="#">
            <span class="certificate"></span><br class="hidden-xs"> Awards</a>
        </li>
        <li id="phone" class="hidden-xs">
          <a href="tel:111-111-111">
            <span>111-111-111</span></a><div>* We Deliver</div>
        </li>
      </ul>
</code>```

答:
```<code>  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
      </li>
    </ul>
    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>
  </div>
</nav>```

**Here is your Responsive Bootstrap navigation bar**
</code>```

Body:
I need a little help. Here's my code i wrote in Bootstrap-3 for collapse-navbar but when i want to write it in Bootstrap-4 it doesn't work. Whatever I tried from the commands failed. Can someone help me and tell me what to do or write.

<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#collapsable-nav" aria-expanded="false">
        Toggle navigation

      </button>

 Menu

 About

 Awards

            111-111-111
* We Deliver


问:
Should metrics calls be awaited? Is it safe to not await them?
In my backend web service, metrics are sent at multiple moments to keep track of its behavior. To send a metric, I do an http call. I fear that awaiting it adds useless latency to the responses of the service. To me, it seems they should be fire and forget. Is it safe and/or recommended to not await those kinds of calls?

Note: My service is in c#, dotnet core.

PS: Call failures could be logged by the metrics package itself. A failure of a metrics call should not break the user call.

答:
Whether or not it's safe to fire and forget the call depends on the metrics library's implementation and potentially the error handling (e.g. logging). The forgotten task can keep executing after its parent HTTP request context gets disposed and if the task tries to use a disposed resource it could crash.

Whether or not you'll run into problems depends on the specific components and how they're configured, for example if the task's dependencies rely on the garbage collector for cleanup then you're OK. However if ASP.NET DI container calls Dispose() on the task's dependency then that dependency can start throwing InvalidOperationException.


问:
Why isn't my updated .gitignore working for files that are being tracked?
I have the following .gitignore file

```<code># file named .gitignore

system/application/config/database.php
system/application/config/config.php
system/logs
modules/recaptcha/config/*
</code>```

However when I add any changes in config and recapcha.php, git status warns me as following.
When I add any changes to database.php. it does not show it in status

```<code>shin@shin-Latitude-E5420:/var/www/myapp$ git status
# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   modules/recaptcha/config/recaptcha.php
#   modified:   system/application/config/config.php
#
no changes added to commit (use "git add" and/or "git commit -a")
</code>```

How can I fix this?

I am using git version 1.7.5.1 on Ubuntu 11.04

答:
The files are already stored in your local commit tree. You'll need to first remove them from the repository. This can be done via:

```<code>git rm --cached system/application/config/config.php modules/recaptcha/config/recaptcha.php
</code>```

After that you'll need to make one more commit and you're good to go.

Body:
I have the following .gitignore file

# file named .gitignore

system/application/config/database.php
system/application/config/config.php
system/logs
modules/recaptcha/config/*

However when I add any changes in config and recapcha.php, git status warns me as following.
When I add any changes to database.php. it does not show it in status

shin@shin-Latitude-E5420:/var/www/myapp$ git status
# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   modules/recaptcha/config/recaptcha.php
#   modified:   system/application/config/config.php
#
no changes added to commit (use "git add" and/or "git commit -a")

How can I fix this?

I am using git version 1.7.5.1 on Ubuntu 11.04

Body:
The files are already stored in your local commit tree. You'll need to first remove them from the repository. This can be done via:

git rm --cached system/application/config/config.php modules/recaptcha/config/recaptcha.php

After that you'll need to make one more commit and you're good to go.


问:
Django deleted DDBB table and cannot migrate anymore: no such table error
I've deleted a table from the sqlite DDBB because I wanted to make some changes and wasn't able to do those with a simple update of the models in Django. Since then, I am not able to perform migrations again and get a new table for my models, getting the error "django.db.utils.OperationalError: no such table: shop_productitem".

I've tried to follow many hints in other similar threads with no luck. I've tried this and this for example and I cannot solve the issue. My understanding is that if I run makemigrations and then migrate the models the ddbb should update itself with the new specifications, but I'm probably mistaken in this specific case.

Can someone address me where the problem would sit? I fear I have not the necessary knowledge to figure this out of my own, I've been looking for ages.

Please find below the whole error message I'm getting:

```<code>    Applying shop.0002_auto_20200218_1958...Traceback (most recent call last):
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: shop_productitem

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute
    output = self.handle(*args, **options)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 200, in handle
    fake_initial=fake_initial,
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/migrations/migration.py", line 122, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards
    schema_editor.alter_field(from_model, from_field, to_field)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 133, in alter_field
    super().alter_field(model, old_field, new_field, strict=strict)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 509, in alter_field
    old_db_params, new_db_params, strict)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 330, in _alter_fi
eld
    self._remake_table(model, alter_field=(old_field, new_field))
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 260, in _remake_t
able
    disable_constraints=False,
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 95, in alter_db_t
able
    super().alter_db_table(model, old_db_table, new_db_table)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 383, in alter_db_tab
le
    "new_table": self.quote_name(new_db_table),
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 117, in execute
    cursor.execute(sql, params)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute
    return super().execute(sql, params)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrapp
ers
    return executor(sql, params, many, context)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: shop_productitem
</code>```

Thank you so much,
Askew

答:
If you can afford lose data from db, then just remove old db file from it's folder. delete all migrations from migrate folders. and then run makemigrations and migrate this will create new sqllight DB

Another option if data loss is not an option, you can try recreate deleted table manually with DB Browser for SQLite or with Command Line Shell For SQLite. And then delete them correctly using migrations

For future, if you need to delete table, you should delete or comment it model code and then run makemigrations, migrate and this will delete table correctly from db

Body:
I've deleted a table from the sqlite DDBB because I wanted to make some changes and wasn't able to do those with a simple update of the models in Django. Since then, I am not able to perform migrations again and get a new table for my models, getting the error "django.db.utils.OperationalError: no such table: shop_productitem".

I've tried to follow many hints in other similar threads with no luck. I've tried this and this for example and I cannot solve the issue. My understanding is that if I run makemigrations and then migrate the models the ddbb should update itself with the new specifications, but I'm probably mistaken in this specific case.

Can someone address me where the problem would sit? I fear I have not the necessary knowledge to figure this out of my own, I've been looking for ages.

Please find below the whole error message I'm getting:

    Applying shop.0002_auto_20200218_1958...Traceback (most recent call last):
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: shop_productitem

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute
    output = self.handle(*args, **options)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 200, in handle
    fake_initial=fake_initial,
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/migrations/migration.py", line 122, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards
    schema_editor.alter_field(from_model, from_field, to_field)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 133, in alter_field
    super().alter_field(model, old_field, new_field, strict=strict)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 509, in alter_field
    old_db_params, new_db_params, strict)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 330, in _alter_fi
eld
    self._remake_table(model, alter_field=(old_field, new_field))
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 260, in _remake_t
able
    disable_constraints=False,
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 95, in alter_db_t
able
    super().alter_db_table(model, old_db_table, new_db_table)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 383, in alter_db_tab
le
    "new_table": self.quote_name(new_db_table),
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 117, in execute
    cursor.execute(sql, params)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute
    return super().execute(sql, params)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrapp
ers
    return executor(sql, params, many, context)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: shop_productitem

Thank you so much,
Askew


问:
How do I limit a number of workers running in parallel in WorkManager?
I enqueue files (chosen by the user) to upload and then update sync status with WorkManager like this:

```<code>fun schedule(files: List<String>) {
    var cont = workManager
                .beginUniqueWork(issueId, APPEND, files.map { workRequest(it) })
                .then(updateSyncStatusWork)
                .enqueue()
}
</code>```

It works well. But when user choose a lot of files looking to logs I see that a lot of files are uploading at the same time (around 10 or even all of them). And quite a lot of timeouts happens. I believe that reducing a number of parallel uploads will decrease the number of timeouts but I can not find any API in WorkManager or WorkRequest that allows doing that.

PS I do not consider chaining them as failed upload will drop upload of all the files after it.

答:
The number of jobs that can run at the same time are actually determined by a thread pool that you configure. The default Executor is defined here.

Typically when you are using the Worker base class, you are associating an instance of the Worker to a thread on this Executor. If you want greater control on which thread your Worker is associated with, you might want to take a look at CoroutineWorker or ListenableWorker.

The number of threads in the default Executor are determined by the number  of cores on the device. If you want only N jobs to run at the same time you have to do the following:

Disable the default WorkManager initializer (by disabling manifest merging for the content provider).

Initialize WorkManager on Application.onCreate() or your own ContentProvider. You need to do this here because the OS can ask previously scheduled Workers to run. For more information look at this.

```<code>val configuration = Configuration.Builder()
    // Defines a thread pool with 2 threads.
    // This can be N (typically based on the number of cores on the device)
    .setExecutor(Executors.newFixedThreadPool(2))
    .build()

WorkManager.initialize(context, configuration)
</code>```

In the above example I am creating a fixed size thread pool with 2 threads (which in turn can handle 2 Workers simultaneously). Now when you enqueue your Workers you will see only 2 of them execute at the same time.

Body:
I enqueue files (chosen by the user) to upload and then update sync status with WorkManager like this:

fun schedule(files: List<String>) {
    var cont = workManager
                .beginUniqueWork(issueId, APPEND, files.map { workRequest(it) })
                .then(updateSyncStatusWork)
                .enqueue()
}

It works well. But when user choose a lot of files looking to logs I see that a lot of files are uploading at the same time (around 10 or even all of them). And quite a lot of timeouts happens. I believe that reducing a number of parallel uploads will decrease the number of timeouts but I can not find any API in WorkManager or WorkRequest that allows doing that.

PS I do not consider chaining them as failed upload will drop upload of all the files after it.

Body:
The number of jobs that can run at the same time are actually determined by a thread pool that you configure. The default Executor is defined here.

Typically when you are using the Worker base class, you are associating an instance of the Worker to a thread on this Executor. If you want greater control on which thread your Worker is associated with, you might want to take a look at CoroutineWorker or ListenableWorker.

The number of threads in the default Executor are determined by the number  of cores on the device. If you want only N jobs to run at the same time you have to do the following:

Disable the default WorkManager initializer (by disabling manifest merging for the content provider).

Initialize WorkManager on Application.onCreate() or your own ContentProvider. You need to do this here because the OS can ask previously scheduled Workers to run. For more information look at this.

val configuration = Configuration.Builder()
    // Defines a thread pool with 2 threads.
    // This can be N (typically based on the number of cores on the device)
    .setExecutor(Executors.newFixedThreadPool(2))
    .build()

WorkManager.initialize(context, configuration)

In the above example I am creating a fixed size thread pool with 2 threads (which in turn can handle 2 Workers simultaneously). Now when you enqueue your Workers you will see only 2 of them execute at the same time.


答:
You can do this by using an Ajax function. If you do this, you can remove the @using block altogether.

First, add a button to your view and give it an id. also give your input field an id.

```<code>@Html.LabelFor(model => model.LastName)
@Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control", @id = "lastName" } })
@Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
<button type="button" class="btn btn-success" id="createButton">Add user</button>
</code>```

Then add a script at the bottom of your code. The following assumes you have this code in your _Layout.cshtml file: @RenderSection("scripts", required: false)
If not, don't wrap the script tags in this bit of code: @section Scripts {}

```<code>@section Scripts {
<script>
        // listen for button click event
        $('#createButton').click(function (e) {
            e.preventDefault();

            let lastName = $('#lastName').val();

            // Check for empty input -> exit if empty
            if ($.trim(lastName) == "") {
                return;
            }

            let data = JSON.stringify({
                lastName: lastName
            });

            // call saveUser ajax function, pass in data
            $.when(saveUser(data)).then(function (response) {
                alert(response);
            }).fail(function (err) {
                console.log(err);
            });
        });

        // Pass all data to Controller for saving
        function saveUser(data) {
            return $.ajax({
                url: '/Users/CreateUser',
                dataType: 'json',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                processData: false,
                cache: false,
                data: data,
                success: function (result) {
                    console.log(result);
                },
                error: function () {
                    alert('Error! Please contact an administrator if the problem persists.')
                }
            });
        }
    </script>
}
</code>```

Finally, set up your controller action something like this:

```<code>[HttpPost]
public JsonResult CreateUser(string lastName)
{
    // prepare a return statement
    string result = "Error! Please contact an administrator if the problem persists.";

    // perform your create logic here, then check if it succeeded or not

    if (createSucceeded == true)
    {
        // change result string to a success message
        result = "Success! User created!";
    }

    // Return the result string
    return Json(result, JsonRequestBehavior.AllowGet);
}
</code>```

Title: Grab form values to avoid page reload when submitting a MVC form

Body:
You can do this by using an Ajax function. If you do this, you can remove the @using block altogether.

First, add a button to your view and give it an id. also give your input field an id.

@Html.LabelFor(model => model.LastName)
@Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control", @id = "lastName" } })
@Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
<button type="button" class="btn btn-success" id="createButton">Add user</button>

Then add a script at the bottom of your code. The following assumes you have this code in your _Layout.cshtml file: @RenderSection("scripts", required: false)
If not, don't wrap the script tags in this bit of code: @section Scripts {}

@section Scripts {
<script>
        // listen for button click event
        $('#createButton').click(function (e) {
            e.preventDefault();

            let lastName = $('#lastName').val();

            // Check for empty input -> exit if empty
            if ($.trim(lastName) == "") {
                return;
            }

            let data = JSON.stringify({
                lastName: lastName
            });

            // call saveUser ajax function, pass in data
            $.when(saveUser(data)).then(function (response) {
                alert(response);
            }).fail(function (err) {
                console.log(err);
            });
        });

        // Pass all data to Controller for saving
        function saveUser(data) {
            return $.ajax({
                url: '/Users/CreateUser',
                dataType: 'json',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                processData: false,
                cache: false,
                data: data,
                success: function (result) {
                    console.log(result);
                },
                error: function () {
                    alert('Error! Please contact an administrator if the problem persists.')
                }
            });
        }
    </script>
}

Finally, set up your controller action something like this:

[HttpPost]
public JsonResult CreateUser(string lastName)
{
    // prepare a return statement
    string result = "Error! Please contact an administrator if the problem persists.";

    // perform your create logic here, then check if it succeeded or not

    if (createSucceeded == true)
    {
        // change result string to a success message
        result = "Success! User created!";
    }

    // Return the result string
    return Json(result, JsonRequestBehavior.AllowGet);
}


问:
Publishing more than actual messages in Google Pub/Sub using Node.js and csv-parse
Using Node.js, Google Pub/Sub, csv-parse.

Use case  -
I have a large csv file to process and import in my DB. It has few third party APIs which take 1 second to process each row. So process flow is below -

User uploads the file

node server upload the file in storage and send message to PubSubNo.1

Now My listener listens to above pubsub and starts processing these messages , it download the file and start breaking each row and publishes to another PubSub for further processing

In the end I parallel process these smaller row messages and achieve faster processing.

Problem -
As soon as my listener downloads the file it send x no. of row messages to next PubSubNo2 but when i check its subscription it shows more than x messages.
e.g. I upload a 6000 record csv and on subscriber it shows more than 40K-50K messages.

Package.json

```<code>"dependencies": {
    "@google-cloud/pubsub": "1.5.0",
    "axios": "^0.19.2",
    "csv-parse": "^4.8.5",
    "dotenv": "^8.2.0",
    "google-gax": "1.14.1",
    "googleapis": "47.0.0",
    "moment": "^2.24.0",
    "path": "^0.12.7",
    "pg": "^7.18.1",
    "winston": "^3.0.0"
  }
</code>```

Publisher Code

```<code>async processFile(filename) {
    let cnt = 0;
    let index = null;
    let rowCounter = 0;
    const handler = (resolve, reject) => {
      const parser = CsvParser({
          delimiter: ',',
        })
        .on('readable', () => {
          let row;
          let hello = 0;
          let busy = false;
          this.meta.totalRows = (parser.info.records - 1);
          while (row = parser.read()) {
            if (cnt++ === 0) {
              index = row;
              continue;
            }
            let messageObject = {
              customFieldsMap: this.customFieldsMap,
              importAttributes: this.jc.attrs,
              importColumnData: row,
              rowCount: cnt,
              importColumnList: index,
              authToken: this.token
            }
            let topicPublishResult = PubSubPublish.publishToTopic(process.env.IMPORT_CSV_ROW_PUBLISHING_TOPIC, messageObject);
            topicPublishResult.then((response) => {
              rowCounter += 1;
              const messageInfo = "Row " + rowCounter + " published" +
                " | MessageId = " + response +
                " | importId = " + this.data.importId +
                " | fileId = " + this.data.fileId +
                " | orgId = " + this.data.orgId;
              console.info(messageInfo);
            })
          }
        })
        .on('end', () => {
          console.log("File consumed!");
          resolve(this.setStatus("queued"))
        })
        .on('error', reject);
      fs.createReadStream(filename).pipe(parser);
    };
    await new Promise(handler);
  }
</code>```

And Publish module code

```<code>const {
  PubSub
} = require('@google-cloud/pubsub');

const pubsub = new PubSub({
  projectId: process.env.PROJECT_ID
});
module.exports = {
  publishToTopic: function(topicName, data) {
    return pubsub.topic(topicName, {
      batching: {
        maxMessages: 500,
        maxMilliseconds: 5000,
      }
    }).publish(Buffer.from(JSON.stringify(data)));
  },
};
</code>```

This works without any issues for file os 10, 100,200,2000 records but giving trouble with more as in for 6K records.
After I publish 6K records there is an error of UnhandledPromiseRejection for all 6K records e.g.

```<code>(node:49994) UnhandledPromiseRejectionWarning: Error: Retry total timeout exceeded before any response was received
    at repeat (/Users/tarungupta/office/import-processor/node_modules/google-gax/build/src/normalCalls/retries.js:65:31)
    at Timeout._onTimeout (/Users/tarungupta/office/import-processor/node_modules/google-gax/build/src/normalCalls/retries.js:100:25)
    at listOnTimeout (internal/timers.js:531:17)
    at processTimers (internal/timers.js:475:7)
(node:49994) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 6000)
</code>```

Any help is appreciated!

答: It's possible that your publisher is getting overwhelmed when you have 6,000 messages to publish. The reason is that you create a new instance of the publisher for each message that you create in your publishToTopic method. Consequently, you are not getting to take advantage of any batching and you are waiting 5 seconds to send every message. That's a lot of overhead for each message. It could mean that callbacks are not getting processed in a timely fashion, resulting in timeouts and attempts to resend. You want to create your pubsub.topic object a single time and then reuse it across publish calls.

Body:
Using Node.js, Google Pub/Sub, csv-parse.

Use case  -
I have a large csv file to process and import in my DB. It has few third party APIs which take 1 second to process each row. So process flow is below -

User uploads the file

node server upload the file in storage and send message to PubSubNo.1

Now My listener listens to above pubsub and starts processing these messages , it download the file and start breaking each row and publishes to another PubSub for further processing

In the end I parallel process these smaller row messages and achieve faster processing.

Problem -
As soon as my listener downloads the file it send x no. of row messages to next PubSubNo2 but when i check its subscription it shows more than x messages.
e.g. I upload a 6000 record csv and on subscriber it shows more than 40K-50K messages.

Package.json

"dependencies": {
    "@google-cloud/pubsub": "1.5.0",
    "axios": "^0.19.2",
    "csv-parse": "^4.8.5",
    "dotenv": "^8.2.0",
    "google-gax": "1.14.1",
    "googleapis": "47.0.0",
    "moment": "^2.24.0",
    "path": "^0.12.7",
    "pg": "^7.18.1",
    "winston": "^3.0.0"
  }

Publisher Code

async processFile(filename) {
    let cnt = 0;
    let index = null;
    let rowCounter = 0;
    const handler = (resolve, reject) => {
      const parser = CsvParser({
          delimiter: ',',
        })
        .on('readable', () => {
          let row;
          let hello = 0;
          let busy = false;
          this.meta.totalRows = (parser.info.records - 1);
          while (row = parser.read()) {
            if (cnt++ === 0) {
              index = row;
              continue;
            }
            let messageObject = {
              customFieldsMap: this.customFieldsMap,
              importAttributes: this.jc.attrs,
              importColumnData: row,
              rowCount: cnt,
              importColumnList: index,
              authToken: this.token
            }
            let topicPublishResult = PubSubPublish.publishToTopic(process.env.IMPORT_CSV_ROW_PUBLISHING_TOPIC, messageObject);
            topicPublishResult.then((response) => {
              rowCounter += 1;
              const messageInfo = "Row " + rowCounter + " published" +
                " | MessageId = " + response +
                " | importId = " + this.data.importId +
                " | fileId = " + this.data.fileId +
                " | orgId = " + this.data.orgId;
              console.info(messageInfo);
            })
          }
        })
        .on('end', () => {
          console.log("File consumed!");
          resolve(this.setStatus("queued"))
        })
        .on('error', reject);
      fs.createReadStream(filename).pipe(parser);
    };
    await new Promise(handler);
  }

And Publish module code

const {
  PubSub
} = require('@google-cloud/pubsub');

const pubsub = new PubSub({
  projectId: process.env.PROJECT_ID
});
module.exports = {
  publishToTopic: function(topicName, data) {
    return pubsub.topic(topicName, {
      batching: {
        maxMessages: 500,
        maxMilliseconds: 5000,
      }
    }).publish(Buffer.from(JSON.stringify(data)));
  },
};

This works without any issues for file os 10, 100,200,2000 records but giving trouble with more as in for 6K records.
After I publish 6K records there is an error of UnhandledPromiseRejection for all 6K records e.g.

(node:49994) UnhandledPromiseRejectionWarning: Error: Retry total timeout exceeded before any response was received
    at repeat (/Users/tarungupta/office/import-processor/node_modules/google-gax/build/src/normalCalls/retries.js:65:31)
    at Timeout._onTimeout (/Users/tarungupta/office/import-processor/node_modules/google-gax/build/src/normalCalls/retries.js:100:25)
    at listOnTimeout (internal/timers.js:531:17)
    at processTimers (internal/timers.js:475:7)
(node:49994) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 6000)

Any help is appreciated!


问:
Remove ObjectId from mongodb document serialized to JSON in C#
I'm having a bit of an issue here. I am getting all my products from a mongodb collection with this function:

```<code>public async Task<string> getAllProducts()
        {
            List<string> all = new List<string>();

            var document = await getCollection("produits").Find(new BsonDocument()).ToCursorAsync();
            foreach (var doc in document.ToEnumerable())
            {
                var res = doc.ToJson();
                all.Add(res);
            }
            return JsonConvert.SerializeObject(all);
        }
</code>```

and it returns a JSON that looks like this to my react front end.

```<code>{ "_id" : ObjectId("5e49bdf5f040e808847a17d7"),
"email" : "example@gmail.com",
"quantite" : 1,
"matricule" : 1}
</code>```

problem is i cant parse this in my javascript because of this : ObjectId("5e49bdf5f040e808847a17d7")

Of course I could do some string magic before I parse it, but id rather it be corrected on the server side. So is there a way I can get rid of this problem and get a result like this?

```<code>{ "_id" : "5e49bdf5f040e808847a17d7",
    "email" : "example@gmail.com",
    "quantite" : 1,
    "matricule" : 1}
</code>```

答:
Fixed by creating a class for the mongodb object.

```<code>public class Product
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
    public int matricule { get; set; }
    public int quantite { get; set; }
    public string email { get; set; }
    public float prix { get; set; }
    public string image { get; set; }
}
</code>```

get them and deserialize with BsonSerializer :

```<code>public async Task<List<Product>> getAllProducts(){
    var collection = await getCollection("produits").Find(new BsonDocument()).ToListAsync();
    List<Product> all = new List<Product>();
    foreach(var doc in collection){
        all.Add(BsonSerializer.Deserialize<Product>(doc));
    }
    return all;
}
</code>```

return them on request :

```<code>[HttpGet]
public async Task<string> ShowProductsAsync()
{
    MongodbModel model = new MongodbModel();
    var products = await model.getAllProducts();
    Console.WriteLine(products);
    return JsonConvert.SerializeObject(products);
}
</code>```

Body:
I'm having a bit of an issue here. I am getting all my products from a mongodb collection with this function:

public async Task<string> getAllProducts()
        {
            List<string> all = new List<string>();

            var document = await getCollection("produits").Find(new BsonDocument()).ToCursorAsync();
            foreach (var doc in document.ToEnumerable())
            {
                var res = doc.ToJson();
                all.Add(res);
            }
            return JsonConvert.SerializeObject(all);
        }

and it returns a JSON that looks like this to my react front end.

{ "_id" : ObjectId("5e49bdf5f040e808847a17d7"),
"email" : "example@gmail.com",
"quantite" : 1,
"matricule" : 1}

problem is i cant parse this in my javascript because of this : ObjectId("5e49bdf5f040e808847a17d7")

Of course I could do some string magic before I parse it, but id rather it be corrected on the server side. So is there a way I can get rid of this problem and get a result like this?

{ "_id" : "5e49bdf5f040e808847a17d7",
    "email" : "example@gmail.com",
    "quantite" : 1,
    "matricule" : 1}

Body:
Fixed by creating a class for the mongodb object.

public class Product
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
    public int matricule { get; set; }
    public int quantite { get; set; }
    public string email { get; set; }
    public float prix { get; set; }
    public string image { get; set; }
}

get them and deserialize with BsonSerializer :

public async Task<List<Product>> getAllProducts(){
    var collection = await getCollection("produits").Find(new BsonDocument()).ToListAsync();
    List<Product> all = new List<Product>();
    foreach(var doc in collection){
        all.Add(BsonSerializer.Deserialize<Product>(doc));
    }
    return all;
}

return them on request :

[HttpGet]
public async Task<string> ShowProductsAsync()
{
    MongodbModel model = new MongodbModel();
    var products = await model.getAllProducts();
    Console.WriteLine(products);
    return JsonConvert.SerializeObject(products);
}


问:
Question about using PowerShell Select-String, exiftool(-k)
In a PowerShell script I'm trying to filter the output of the exiftool(-k).exe command below, using Select-String.

I've tried numerous permutations, but none work, and I always see the unfiltered output.  What do I need to do to filter the output of this command?

```<code>Start-Process -FilePath "C:\PowerShell\exiftool(-k).exe" -ArgumentList test.jpg |
  Select-String -pattern 'GPS' -SimpleMatch
</code>```

答:
The naming is inconvenient.  Rename it to exiftool.exe and run it without start-process.

```<code>rename-item 'exiftool(-k).exe' exiftool.exe

C:\Users\bfbarton\PowerShell\exiftool.exe test-jpg | Select-String GPS
</code>```

Or

```<code>$env:path += ';C:\Users\bfbarton\PowerShell'
exiftool test.jpg | Select-String GPS
</code>```

The website recommends to 'rename to "exiftool.exe" for command-line use'.   https://exiftool.org .  Even in unix, it wouldn't work without escaping the parentheses.

There's also the option of using the call operator.  Using tab completion actually does this:

```<code>& '.\exiftool(-k).exe' test.jpg | select-string gps
</code>```

Body:
In a PowerShell script I'm trying to filter the output of the exiftool(-k).exe command below, using Select-String.

I've tried numerous permutations, but none work, and I always see the unfiltered output.  What do I need to do to filter the output of this command?

Start-Process -FilePath "C:\PowerShell\exiftool(-k).exe" -ArgumentList test.jpg |
  Select-String -pattern 'GPS' -SimpleMatch

Body:
The naming is inconvenient.  Rename it to exiftool.exe and run it without start-process.

rename-item 'exiftool(-k).exe' exiftool.exe

C:\Users\bfbarton\PowerShell\exiftool.exe test-jpg | Select-String GPS

Or

$env:path += ';C:\Users\bfbarton\PowerShell'
exiftool test.jpg | Select-String GPS

The website recommends to 'rename to "exiftool.exe" for command-line use'.   https://exiftool.org .  Even in unix, it wouldn't work without escaping the parentheses.

There's also the option of using the call operator.  Using tab completion actually does this:

& '.\exiftool(-k).exe' test.jpg | select-string gps


问:
plugin request for plugin already on the classpath must not include a version
I've done web search for "plugin request for plugin already on the classpath must not include a version site:stackoverflow.com" and found nothing that particular. Search for "plugin request for plugin already on the classpath must not include a version" (w/out SO) found:
https://discuss.gradle.org/t/error-plugin-already-on-the-classpath-must-not-include-a-version/31814 where I've read in answers e.g.:

I didn’t find any reference to this use case in Grade plugins
  documentation.

The error

Build file '/Users/username/github/OpCon/app/build.gradle'
  line: 4 Error resolving plugin [id: 'com.android.application',
  version: '3.4.1']

Plugin request for plugin already on the classpath must not include a version

appears in IntelliJ IDEA, build.gradle (OpCon):

```<code>buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.2'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenCentral()
        maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
    }
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

app/build.gradle:

```<code>plugins {
    id 'com.android.application' version '3.4.1' apply true
}

... and then other stuff
</code>```

I don't understand, classpath 'com.android.tools.build:gradle:3.5.2' does not seem to include 'com.android.application'...
"classpath" has only one occurrence if searched in the project.

ADDED:

Interestingly on https://maven.google.com/web/index.html I can find 'com.android.tools.build:gradle:3.5.2' but no 'com.android.application' branch.

ADDED 2:
I've downloaded (quite many files actually was downloaded for some reason) by command taken from here How can I download a specific Maven artifact in one command line?:

mvn org.apache.maven.plugins:maven-dependency-plugin:2.8:get -DrepoUrl='https://maven.google.com/' -Dartifact='com.android.tools.build:gradle:3.4.1'

found path com.android.tools.build:gradle in file manager and looked inside only jar there:

```<code>username$ jar tvf /Users/username/.m2/repository/com/android/tools/build/gradle/3.4.1/gradle-3.4.1.jar | grep application
  1115 Wed May 01 20:30:18 MSK 2019 com/android/build/gradle/internal/tasks/ApplicationIdWriterTask$applicationIdSupplier$1.class
    55 Wed May 01 20:29:18 MSK 2019 META-INF/gradle-plugins/com.android.application.properties
</code>```

So there is a mention gradle plugin com.android.application in jar META-INF.

File com.android.application.properties is one liner: implementation-class=com.android.build.gradle.AppPlugin.

Web search for "implementation class java" finds info on interfaces. In wiki https://en.wikipedia.org/wiki/Interface_(Java):

An interface in the Java programming language is an abstract type that
  is used to specify a behavior that classes must implement.

So gradle plugin could be an interface? How can I dig in further?

答:
I was facing same problem, I was using spring boot with plugins as follows

```<code>plugins {
    id 'org.springframework.boot' version '2.2.0.RELEASE'
    id 'io.spring.dependency-management' version '1.0.8.RELEASE'
    id 'java'
    id 'war'
}
</code>```

Since this plugin was present in one dependency gradle was complaining about it. I simply removed those dependencies and it worked:

```<code>plugins {
    id 'java'
    id 'war'
}
</code>```

Body:
I've done web search for "plugin request for plugin already on the classpath must not include a version site:stackoverflow.com" and found nothing that particular. Search for "plugin request for plugin already on the classpath must not include a version" (w/out SO) found:
https://discuss.gradle.org/t/error-plugin-already-on-the-classpath-must-not-include-a-version/31814 where I've read in answers e.g.:

I didn’t find any reference to this use case in Grade plugins
  documentation.

The error

Build file '/Users/username/github/OpCon/app/build.gradle'
  line: 4 Error resolving plugin [id: 'com.android.application',
  version: '3.4.1']

Plugin request for plugin already on the classpath must not include a version

appears in IntelliJ IDEA, build.gradle (OpCon):

buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.2'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenCentral()
        maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
    }
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}

app/build.gradle:

plugins {
    id 'com.android.application' version '3.4.1' apply true
}

... and then other stuff

I don't understand, classpath 'com.android.tools.build:gradle:3.5.2' does not seem to include 'com.android.application'...
"classpath" has only one occurrence if searched in the project.

ADDED:

Interestingly on https://maven.google.com/web/index.html I can find 'com.android.tools.build:gradle:3.5.2' but no 'com.android.application' branch.

ADDED 2:
I've downloaded (quite many files actually was downloaded for some reason) by command taken from here How can I download a specific Maven artifact in one command line?:

mvn org.apache.maven.plugins:maven-dependency-plugin:2.8:get -DrepoUrl='https://maven.google.com/' -Dartifact='com.android.tools.build:gradle:3.4.1'

found path com.android.tools.build:gradle in file manager and looked inside only jar there:

username$ jar tvf /Users/username/.m2/repository/com/android/tools/build/gradle/3.4.1/gradle-3.4.1.jar | grep application
  1115 Wed May 01 20:30:18 MSK 2019 com/android/build/gradle/internal/tasks/ApplicationIdWriterTask$applicationIdSupplier$1.class
    55 Wed May 01 20:29:18 MSK 2019 META-INF/gradle-plugins/com.android.application.properties

So there is a mention gradle plugin com.android.application in jar META-INF.

File com.android.application.properties is one liner: implementation-class=com.android.build.gradle.AppPlugin.

Web search for "implementation class java" finds info on interfaces. In wiki https://en.wikipedia.org/wiki/Interface_(Java):

An interface in the Java programming language is an abstract type that
  is used to specify a behavior that classes must implement.

So gradle plugin could be an interface? How can I dig in further?

Body:
I was facing same problem, I was using spring boot with plugins as follows

plugins {
    id 'org.springframework.boot' version '2.2.0.RELEASE'
    id 'io.spring.dependency-management' version '1.0.8.RELEASE'
    id 'java'
    id 'war'
}

Since this plugin was present in one dependency gradle was complaining about it. I simply removed those dependencies and it worked:

plugins {
    id 'java'
    id 'war'
}


问:
How do I prevent a component from rendering twice?
I want to initialize a component but it keeps rendering all the time.

According to the documentation I use React.memo but that doesn't prevent the component from rerendering: console.log("re-render") prints more than once. How do I make that component exactly static no matter what happens above in the tree?

```<code>const Canvas = React.memo((props) => {
    const context = useContext(Context);
    const width = "500%";
    const height = "500%";

    const count = useRef(0);

    useEffect(() => {
        context.initCanvas("c");
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []); //runs only once on mount

    console.log("re-render"); //outputs all the time when I cange something above in the tree.

    return (
        <>
            <canvas
                style={{border: "1px dashed black", margin: "10px"}}
                id="c"
                width={width}
                height={height}
            >
            </canvas>
        </>
    );
});
</code>```

答:
From documentation:

Even if an ancestor uses React.memo or shouldComponentUpdate, a rerender will still happen starting at the component itself using useContext.

Therefore, the component wil rerender because of the fact we are using useContext.

There is a discussion in github where 3 solutions are propoosed for this case. Here is the link.

Body:
I want to initialize a component but it keeps rendering all the time.

According to the documentation I use React.memo but that doesn't prevent the component from rerendering: console.log("re-render") prints more than once. How do I make that component exactly static no matter what happens above in the tree?

const Canvas = React.memo((props) => {
    const context = useContext(Context);
    const width = "500%";
    const height = "500%";

    const count = useRef(0);

    useEffect(() => {
        context.initCanvas("c");
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []); //runs only once on mount

    console.log("re-render"); //outputs all the time when I cange something above in the tree.

    return (
        <>
            <canvas
                style={{border: "1px dashed black", margin: "10px"}}
                id="c"
                width={width}
                height={height}
            >
            </canvas>
        </>
    );
});


问:
How do I set up a id for animations?
I am trying to set a id to the animation.

Code:

```<code>    def on_anim1_start(self, *args):
        self.x = 0
        sound1 = SoundLoader.load("C:\\Users\\kanna\\Music\\OpenCity1.mp3")
        sound1.play()

    def on_enter(self):
        self.label1.opacity = 0
        animation = Animation(d=3) + Animation(d=4, opacity=1) + Animation(d=5) + Animation(d=4, opacity=0)
        animation.bind(on_start=self.on_anim1_start)
        animation.start(self.label1)
</code>```

答: You don't, the Animation doesn't have an id property or accept an id argument. Why do you want to?</p>

Title: How do I set up a id for animations?

Body:
I am trying to set a id to the animation.

Code:

    def on_anim1_start(self, *args):
        self.x = 0
        sound1 = SoundLoader.load("C:\\Users\\kanna\\Music\\OpenCity1.mp3")
        sound1.play()

    def on_enter(self):
        self.label1.opacity = 0
        animation = Animation(d=3) + Animation(d=4, opacity=1) + Animation(d=5) + Animation(d=4, opacity=0)
        animation.bind(on_start=self.on_anim1_start)
        animation.start(self.label1)


问:
Having issues running the result of an Xargs find to get version of found items
I'm able to return the path to the java executable but what i really want is the version of java so want to run the path returned with -version attached to the end.

Any help appreciated.

```<code>locate -b '\java' | xargs -ri  find {} -prune -type f -executable
</code>```

Thanks

答:
Here was the eventual answer. </p>

```<code>locate -b '\java' | xargs -ri  find {} -prune -type f -executable | xargs  bash -c '$0 -version'
</code>```

```<code> java version "1.6.0_41"
 OpenJDK Runtime Environment (IcedTea6 1.13.13) (rhel-1.13.13.1.el6_8-x86_64)
 OpenJDK 64-Bit Server VM (build 23.41-b41, mixed mode)```
</code>```

Body:
I'm able to return the path to the java executable but what i really want is the version of java so want to run the path returned with -version attached to the end.

Any help appreciated.

locate -b '\java' | xargs -ri  find {} -prune -type f -executable

Thanks

Body:
Here was the eventual answer.

locate -b '\java' | xargs -ri  find {} -prune -type f -executable | xargs  bash -c '$0 -version'

 java version "1.6.0_41"
 OpenJDK Runtime Environment (IcedTea6 1.13.13) (rhel-1.13.13.1.el6_8-x86_64)
 OpenJDK 64-Bit Server VM (build 23.41-b41, mixed mode)```


问:
How to get read of automatic checked radio button in a Boolean data type in Thymeleaf, Springboot?
Im using spring-boot back-end with the fontend thyme-leaf . But the problem is when im putting Boolean data type in a radio button then the value which is set to 0 is automatically checked in the font end, event if i try to add th:checked="unchecked" its not working. My code is given bellow

```<code>  <div class="form-group">
        <label for="isDownloadable"> Is Downloadable</label> <br>
        <input type="radio" th:field="*{isDownloadable}" value="1" th:checked="checked">Yes
        <input type="radio" th:field="*{isDownloadable}" value="0"> No<br>
    </div>
</code>```

As here iv tried to cheack Yes radio button but its checked the No radio button in the front end.How to solve this problem ?

here is the output of my code given

答:
If you want to use 0 and 1, you put need to condition and show data.Solution is</p>

```<code><div class="form-group">
    <label for="isDownloadable"> Is Downloadable</label> <br>
    <input type="radio" value="1" th:checked="${history.Shift == 1} ? ${true}">Yes
    <input type="radio" value="0" th:checked="${history.Shift == 0} ? ${true}"> No<br>
</div>
</code>```

Body:
Im using spring-boot back-end with the fontend thyme-leaf . But the problem is when im putting Boolean data type in a radio button then the value which is set to 0 is automatically checked in the font end, event if i try to add th:checked="unchecked" its not working. My code is given bellow

         Is Downloadable

        <input type="radio" th:field="*{isDownloadable}" value="1" th:checked="checked">Yes
        <input type="radio" th:field="*{isDownloadable}" value="0"> No

As here iv tried to cheack Yes radio button but its checked the No radio button in the front end.How to solve this problem ?

here is the output of my code given

Body:
If you want to use 0 and 1, you put need to condition and show data.Solution is

<div class="form-group">
    <label for="isDownloadable"> Is Downloadable</label> <br>
    <input type="radio" value="1" th:checked="${history.Shift == 1} ? ${true}">Yes
    <input type="radio" value="0" th:checked="${history.Shift == 0} ? ${true}"> No<br>
</div>


问:
Get whole row using database package execute function
I am using databases package in my fastapi app.  databases has execute and fetch functions, when I tried to return column values after inserting or updating using execute, it returns only the first value, how to get all the values without using fetch..

This is  my query

INSERT INTO table (col1, col2, col3, col4)
  VALUES ( val1, val2, val3, val4 ) RETURNING col1, col2;

答:
I had trouble with this also, this was my query:

INSERT INTO notes (text, completed) VALUES (:text, :completed) RETURNING notes.id, notes.text, notes.completed

Using database.execute(...) will only return the first column.

But.. using database.fetch_one(...) inserts the data and returns all the columns.

Hopes this helps


问:
Debugging OpenCL on CPU
I'm trying to debug OpenCL kernels on CPU target, following this guide without success.
The kernel builds, app runs, but the breakpoints are not hit.
There is a statement "The Debugger requires setting the global ID of the work-item to debug before the debugging session starts.", but no information on where to set or how the global ID.
Anybody has a working boilerplate project for this or suggestions? thanks!</p>

答:
Try to debug with Oclgrind
https://github.com/jrprice/Oclgrind
https://github.com/jrprice/Oclgrind/wiki
example: Oclgrind -i ./appl</p>

Title: Debugging OpenCL on CPU


问:
Href Anchor Text - Open Chat Widget
I am using this anchor text to open the Hubspot widget Open chat which works fine.

However, if the user closes the chat widget and clicks on the link again it doesn't open anymore. I suppose this is a bug with the browser and the way anchor links are handled, is there another way around this without refreshing the page?

答:
yes you can easily reopen the widget just by calling the open function using javascript

   window.HubSpotConversations.widget.open();
```

Title: Href Anchor Text - Open Chat Widget


问:
How to find the total of an 2d array?
Have to input numbers of students & subjects. (Using random marks) I want to print the total marks of students & the total marks of subjects. Here is the code given below.

```<code>import java.util.*;
class Example{
    public static void readMarks(int[][] x){
        Random r=new Random();
        for(int i=0; i<x.length; i++){
            for(int j=0; j<x[i].length; j++){
                x[i][j]=r.nextInt(101);
            }
        }
    }
    public static void printMarks(int[][] x){
        for(int i=0; i<x.length; i++){
            for(int j=0; j<x[i].length; j++){
                System.out.print(x[i][j]+"  ");
            }
            System.out.println();
        }
    }
    public static int[] findStudenTot(int[][] x){
        int tot[]=new int[x.length];

        for(int i=0; i<x.length; i++){
            for (int j = 0; j<x[i].length; j++){
                tot[i]+=x[i][j];
            }
        }
        return tot;
    }
    public static int[] findSubjectTot(int[][] x){
        int tot1[]=new int[x.length];

        for(int i=0; i<x.length; i++){
            for (int j = 0; j<x[i].length; j++){
                tot1[i]+=x[i][j];
            }
        }
        return tot1;
    }

    public static void main(String args[]){
        Scanner input=new Scanner(System.in);
        System.out.print("Input no of students : ");
        final int N=input.nextInt();

        System.out.print("Input no of subject : ");
        final int S=input.nextInt();

        int[][] marks=new int[N][S];
        readMarks(marks);

        int[] stTotal=findStudenTot(marks);
        int[] subTotal=findSubjectTot(marks);

        System.out.println("total is : "+stTotal);
        System.out.println("total is : "+subTotal);

    }
}
</code>```

How to print stTotal , subTotal?

If we assume enter 5 for both inputs this output total is : [I@3d4eac69 ...why?
what are these characters & how can I avoid these?

答:
i think the issue lies in findStudentTot Method, you seem to have return type of 2D array but is returning a 1D array so this should solve it</p>

```<code>public static int[] findStudenTot(int[][] x){
    int tot[]=new int[x.length];

    for(int i=0; i<x.length; i++){
        for (int j = 0; j<x[i].length; j++){
            tot[i]+=x[i][j];
        }
    }
    return tot;
}
</code>```

Title: How to find the total of an 2d array?

Body:
Have to input numbers of students & subjects. (Using random marks) I want to print the total marks of students & the total marks of subjects. Here is the code given below.

import java.util.*;
class Example{
    public static void readMarks(int[][] x){
        Random r=new Random();
        for(int i=0; i<x.length; i++){
            for(int j=0; j<x[i].length; j++){
                x[i][j]=r.nextInt(101);
            }
        }
    }
    public static void printMarks(int[][] x){
        for(int i=0; i<x.length; i++){
            for(int j=0; j<x[i].length; j++){
                System.out.print(x[i][j]+"  ");
            }
            System.out.println();
        }
    }
    public static int[] findStudenTot(int[][] x){
        int tot[]=new int[x.length];

        for(int i=0; i<x.length; i++){
            for (int j = 0; j<x[i].length; j++){
                tot[i]+=x[i][j];
            }
        }
        return tot;
    }
    public static int[] findSubjectTot(int[][] x){
        int tot1[]=new int[x.length];

        for(int i=0; i<x.length; i++){
            for (int j = 0; j<x[i].length; j++){
                tot1[i]+=x[i][j];
            }
        }
        return tot1;
    }

    public static void main(String args[]){
        Scanner input=new Scanner(System.in);
        System.out.print("Input no of students : ");
        final int N=input.nextInt();

        System.out.print("Input no of subject : ");
        final int S=input.nextInt();

        int[][] marks=new int[N][S];
        readMarks(marks);

        int[] stTotal=findStudenTot(marks);
        int[] subTotal=findSubjectTot(marks);

        System.out.println("total is : "+stTotal);
        System.out.println("total is : "+subTotal);

    }
}

How to print stTotal , subTotal?

If we assume enter 5 for both inputs this output total is : [I@3d4eac69 ...why?
what are these characters & how can I avoid these?

Body:
i think the issue lies in findStudentTot Method, you seem to have return type of 2D array but is returning a 1D array so this should solve it

public static int[] findStudenTot(int[][] x){
    int tot[]=new int[x.length];

    for(int i=0; i<x.length; i++){
        for (int j = 0; j<x[i].length; j++){
            tot[i]+=x[i][j];
        }
    }
    return tot;
}


问:
Configure aliases for webpack with lerna and typescript
I created a repository that shows the issue that I have: https://github.com/vileen/lerna-webpack-typescript-aliases-issue (it won't start the app properly for some reason but it doesn't matter).

Basically the question is how to improve importing from the shared package, even more, to get rid of src part of the import. Or maybe there is a better approach to avoid reexporting?

I tried defining webpack aliases which didn't do anything.
What did work was adding "main": "src/index.tsx" to package.json from the shared component but that breaks typescript IntelliSense so it's not a proper solution.

I was thinking about adding definition files, even defining shared module manually but that's not ideal as well since currently I'm able to view the actual code, creating a definition wouldn't bring me that much value and I'd need to update it constantly for every new package.

答:
You need to bundle your code first. It won't work to just pass in the .tsx files. Have a look at this library: https://www.npmjs.com/package/create-react-library

And yes, if you use typescript you need to make a .d.ts file as well, that says what your consumer can expect to receive.


答:
Not certain what you want but try this.  Change int[][] to int[] as the return type.

```<code>  public static int[] findStudenTot(int[][] x){
        int tot[]=new int[x.length];
    // rest of code here.
</code>```

Title: How to find the total of an 2d array?

Body:
Not certain what you want but try this.  Change int[][] to int[] as the return type.

  public static int[] findStudenTot(int[][] x){
        int tot[]=new int[x.length];
    // rest of code here.


问:
avoiding sqlite reader starvation
I have two processes with a shared sqlite database, each one has its own connection to the database. one process writes to the database in a high rate, and one process reads from the database. My concern is how to avoid "reader starvation" issue, since the writer accesses the database in a high rate, thus locking the database for the reader.

I'm using sqlite3_busy_timeout so the reader waits if the database is locked, but from the sqlite3_busy_timeout description I understand that the busy handler simply sleeps a few times with retries. if the writer happnens to lock the database at those times, non of the retries will succeed.

The sqlite file locking documentation describes an opposite problem: "writer starvation" and the mitigations in sqlite version 3. but I couldn't find any reference to the opposite problem "reader starvation". are there any best practices to avoid such issue?

答:
Put the database in WAL mode.

WAL provides more concurrency as readers do not block writers and a writer does not block readers. Reading and writing can proceed concurrently.

Title: avoiding sqlite reader starvation