问:
updating .properties files without a restart?
I updated some properties files (some i18n messages) on a running keycloak. But nothing happens. Do I need to restart keycloak to see the changes? That would be odd, as I instantly see changes to (freemarker) template files.</p>

答:
You can disable theme caching by modifying standalone.xml as follows:

<theme>

    <staticMaxAge>-1</staticMaxAge>
    <cacheThemes>false</cacheThemes>
    <cacheTemplates>false</cacheTemplates>

    <dir>${jboss.home.dir}/themes</dir>
</theme>
```

Body:
You can disable theme caching by modifying standalone.xml as follows:

<theme>
<!-- Change the lines:
    <staticMaxAge>2592000</staticMaxAge>
    <cacheThemes>true</cacheThemes>
    <cacheTemplates>true</cacheTemplates>
to: -->
    <staticMaxAge>-1</staticMaxAge>
    <cacheThemes>false</cacheThemes>
    <cacheTemplates>false</cacheTemplates>

    <dir>${jboss.home.dir}/themes</dir>
</theme>


来源: stackexchange

问:
R - CSV error - unexpected numeric constant
I have a simple csv file with around 20K+ values separated by commas. When I try to load the values in R, it gives me the error:

```<code>r:3: unexpected numeric constant
</code>```

Here is the simple command of R that I executed

```<code>someThing <- c(0.080172405,0.06233087,0.04315185,0.0652015,0.03201301.......n)
n= 70,000 values
</code>```

I cannot copy paste all the 20K+ values here. I googled this error and there is no special character or another thing except for some floating values.

EDIT

http://pastebin.com/FVkUV6kY

答:
The 5682-th entry is "0.0733 7422182", which has a space.

I think this is a simple problem of data processing.

ContentLicense: CC BY-SA 3.0

Body:
I have a simple csv file with around 20K+ values separated by commas. When I try to load the values in R, it gives me the error:

r:3: unexpected numeric constant

Here is the simple command of R that I executed

someThing <- c(0.080172405,0.06233087,0.04315185,0.0652015,0.03201301.......n)
n= 70,000 values

I cannot copy paste all the 20K+ values here. I googled this error and there is no special character or another thing except for some floating values.

EDIT

http://pastebin.com/FVkUV6kY


问:
buildpack error deploying node.js app to heroku - files seem to be at the correct level>?
I am getting an error in the screen shot bellow deploying a node.js app on heroku saying that the buildpack was unable to detect a node.js codebase

I set the build pack, the package.json is at the root level as is the app.js file

https://www.dropbox.com/s/y1bg6eir2w93m8a/Screenshot%202020-05-29%2013.44.36.png?dl=0

Not sure what I am doing wrong - thanks!!

答:
The error is clear:

A Node.js app on Heroku requires a package.json.

In the files listed below, you can see that the package.json file is missing. You have to commit it and repush your code to Heroku.

ContentLicense: CC BY-SA 4.0


问:
javax validation api not working for pojo validation
I have a POJO class where the class variables are getting injected by @Value annotation. I am trying to validate my class variables using javax validation api & so I have tried @NotNull, @NotEmpty and @NotBlank, but all of them seem not to be validating or throwing any kind of exception even when a blank/null value is present in the application.yml file. Any idea as to how can I validate my POJO here using the javax validation api?
PS: I am using lombok to generate my getter/setter.

Below is my sample code!

POJO Class:

```<code>@Component
@Getter
@Setter
public class Credentials {

    @NotBlank
    @Value("${app.username}")
    private String user_name;

    @NotBlank
    @Value("${app.password}")
    private String password;

}
</code>```

Below is the application.yml file:

```<code>app:
    username: '#{null}'
    password: passWord
</code>```

Even if I provide a blank value, I don't get any exception when I try to print these values in the console.

答:
I think this can be applied.</p>

```<code>@Data
@RequiredArgsConstructor
public class Credentials {

    private final String user_name;

    private final String password;

}
</code>```

<p> </p>

```<code>@Configuration
@Validated
public class CredentialsConfiguration {

    @Bean
    public Credentials credentials(
        @NotBlank @Value("${app.username}") final String user_name,
        @NotBlank @Value("${app.password}") final String password) {

        return new Credentials(user_name, password);

    }
}
</code>```

Body:
I have a POJO class where the class variables are getting injected by @Value annotation. I am trying to validate my class variables using javax validation api & so I have tried @NotNull, @NotEmpty and @NotBlank, but all of them seem not to be validating or throwing any kind of exception even when a blank/null value is present in the application.yml file. Any idea as to how can I validate my POJO here using the javax validation api?
PS: I am using lombok to generate my getter/setter.

Below is my sample code!

POJO Class:

@Component
@Getter
@Setter
public class Credentials {

    @NotBlank
    @Value("${app.username}")
    private String user_name;

    @NotBlank
    @Value("${app.password}")
    private String password;

}

Below is the application.yml file:

app:
    username: '#{null}'
    password: passWord

Even if I provide a blank value, I don't get any exception when I try to print these values in the console.

Body:
I think this can be applied.

@Data
@RequiredArgsConstructor
public class Credentials {

    private final String user_name;

    private final String password;

}

@Configuration
@Validated
public class CredentialsConfiguration {

    @Bean
    public Credentials credentials(
        @NotBlank @Value("${app.username}") final String user_name,
        @NotBlank @Value("${app.password}") final String password) {

        return new Credentials(user_name, password);

    }
}


问:
How to remove array if all keys acquired by another array in multidimensional array PHP
can you please help me out in this.
What will be the function to remove 4th and 5th array in PHP.

```<code>Array
(
    [0] => Array
        (
            [10] => 98
            [11] => 1
            [433438] => 8
        )

    [1] => Array
        (
            [10] => 98
            [11] => 1
            [433438] => 1
        )

    [2] => Array
        (
            [13] => 98
            [11] => 2
            [433438] => 8
        )

    [3] => Array
        (
            [14] => 98
            [11] => 2
            [433438] => 1
        )

    [4] => Array
        (
            [10] => 18
            [11] => 1
        )

    [5] => Array
        (
            [14] => 18
            [11] => 2
        )

)
</code>```

Thanks in Advance.

Body:
can you please help me out in this.
What will be the function to remove 4th and 5th array in PHP.

Array
(
    [0] => Array
        (
            [10] => 98
            [11] => 1
            [433438] => 8
        )

    [1] => Array
        (
            [10] => 98
            [11] => 1
            [433438] => 1
        )

    [2] => Array
        (
            [13] => 98
            [11] => 2
            [433438] => 8
        )

    [3] => Array
        (
            [14] => 98
            [11] => 2
            [433438] => 1
        )

    [4] => Array
        (
            [10] => 18
            [11] => 1
        )

    [5] => Array
        (
            [14] => 18
            [11] => 2
        )

)

Thanks in Advance.

Body:
$base = [
    [10 => 98, 11 => 1, 433438 => 8],
    [10 => 98, 11 => 1, 433438 => 1],
    [13 => 98, 11 => 2, 433438 => 8],
    [14 => 98, 11 => 2, 433438 => 1],
    [10 => 18, 11 => 1],
    [14 => 18, 11 => 2],
];

$invalid = [];

for ($i = 0; $i <= count($base) - 1; $i++) {
    for ($j = 0; $j <= count($base) - 1; $j++) {
        $refCount = count($base[$j]);
        $interSectCount = count(array_intersect(array_keys($base[$i]), array_keys($base[$j])));
        if (count($base[$i]) !== $refCount && $interSectCount === $refCount) {
            $invalid[] = $j;
        }
    }
}

foreach ($invalid as $item) {
    unset($base[$item]);
}


问:
MySQL - Multiple Queries or Single Query
So I have a table that contains votes. The relevant columns for this issue being user and timestamp.

I need to grab the user's total vote count, and also their votes this month.

I know the queries - I'm not asking for those. I use these at the same time:

Votes this month / Total votes:

```<code>SELECT COUNT( 0 ) FROM votes WHERE ( timestamp BETWEEN DATE_FORMAT( NOW( ) ,'%Y-%m-01' ) AND NOW( ) ) AND user = ?;

SELECT COUNT( 0 ) FROM votes WHERE user = ?;
</code>```

At the moment, my database isn't large enough (or even queried enough) to where performance is an issue. However, that's expected to change shortly. Should I keep the queries separate, or should I:

```<code>SELECT COUNT( 0 ) AS totalVotes,
       SUM( IF( timestamp BETWEEN DATE_FORMAT( NOW( ) ,'%Y-%m-01' )
                              AND NOW( ), 1, 0 ) ) AS votesThisMonth
    FROM votes WHERE user = ?;
</code>```

What is the best practice? Are there any tips for querying multiple bits of information from the same table to prevent having to search it twice? Is my combined query even what I should be using?

Thanks!

答:
I would recommend the second solution, that uses a unique query with a conditional sum.

Rationale: to produce the second resultset, you need to scan a subset of the first resultset. So the additional processing needed is quite tiny anyway. On the other hand, running two separate queries involves one more roundtrip to the server, one more query parse for the query planner, and an additional scan on the table.

For performance, you want an index on (user, timestamp).

Body:
So I have a table that contains votes. The relevant columns for this issue being user and timestamp.

I need to grab the user's total vote count, and also their votes this month.

I know the queries - I'm not asking for those. I use these at the same time:

Votes this month / Total votes:

SELECT COUNT( 0 ) FROM votes WHERE ( timestamp BETWEEN DATE_FORMAT( NOW( ) ,'%Y-%m-01' ) AND NOW( ) ) AND user = ?;

SELECT COUNT( 0 ) FROM votes WHERE user = ?;

At the moment, my database isn't large enough (or even queried enough) to where performance is an issue. However, that's expected to change shortly. Should I keep the queries separate, or should I:

SELECT COUNT( 0 ) AS totalVotes,
       SUM( IF( timestamp BETWEEN DATE_FORMAT( NOW( ) ,'%Y-%m-01' )
                              AND NOW( ), 1, 0 ) ) AS votesThisMonth
    FROM votes WHERE user = ?;

What is the best practice? Are there any tips for querying multiple bits of information from the same table to prevent having to search it twice? Is my combined query even what I should be using?

Thanks!


问:
Amcharts custom variable color
I want a dynamic color on my chart. I use a imported css file with some identity colors.
Like this:

```<code>:root
{
    --brand-color: {{$color}};
}
</code>```

I am using the AmChart World chart as visualisation but the a4mchart.color() does not like variables. How do I make sure that it does take in variables? here my code:

```<code>let style = getComputedStyle(document.body);
let brandColor = style.getPropertyValue('--brand-color');
const chartWorld = am4core.create(this.$refs.chartdiv, am4maps.MapChart);

polygonSeries.fill = am4core.color(brandColor);
</code>```

And this is what it returns:

```<code>Color {_value: {
alpha: 1
alternative: Color
darkColor: Color
hex: "#000000"
lightColor: Color
rgb: Object
rgba: "rgb(0,0,0)"
_value: {r: 0, g: 0, b: 0, a: 1}
__proto__: Object…}}
</code>```

It didn't change anything but the BrandColor does return the right string when I log it: "#A4A2A3"

Please help

答:
From my testing, getPropertyValue returns everything after the property name, including any whitespace, which causes the color to not get parsed correctly by AmCharts; your log is likely returning " #A4A2A3". You'll want to call trim on the string beforehand:

```<code>polygonSeries.mapPolygons.template.fill = am4core.color(brandColor.trim());
</code>```

Note that you need to set the fill on the series' mapPolygon template for it to apply to your map regions.

Title: Amcharts custom variable color

Body:
I want a dynamic color on my chart. I use a imported css file with some identity colors.
Like this:

:root
{
    --brand-color: {{$color}};
}

I am using the AmChart World chart as visualisation but the a4mchart.color() does not like variables. How do I make sure that it does take in variables? here my code:

let style = getComputedStyle(document.body);
let brandColor = style.getPropertyValue('--brand-color');
const chartWorld = am4core.create(this.$refs.chartdiv, am4maps.MapChart);

polygonSeries.fill = am4core.color(brandColor);

And this is what it returns:

Color {_value: {
alpha: 1
alternative: Color
darkColor: Color
hex: "#000000"
lightColor: Color
rgb: Object
rgba: "rgb(0,0,0)"
_value: {r: 0, g: 0, b: 0, a: 1}
__proto__: Object…}}

It didn't change anything but the BrandColor does return the right string when I log it: "#A4A2A3"

Please help

Body:
From my testing, getPropertyValue returns everything after the property name, including any whitespace, which causes the color to not get parsed correctly by AmCharts; your log is likely returning " #A4A2A3". You'll want to call trim on the string beforehand:

polygonSeries.mapPolygons.template.fill = am4core.color(brandColor.trim());

Note that you need to set the fill on the series' mapPolygon template for it to apply to your map regions.


问:
How to link to user's profile on django
I have been trying to link to user's profile page but everytime I try it, it returns a 404 error. I dont know but maybe the error is on the urls.py file.

views.py

```<code>    def profile(request, username=None):
      if username:
        post_owner = get_object_or_404(User, username=username)

      else:
        post_owner = request.user

      args1 = {
        'post_owner': post_owner,
      }
      return render(request, 'profile.html', args1)
</code>```

urls.py

```<code>    urlpatterns = [
      path('<str:username>/', views.profile, name='profile'),
      path('login', views.login, name='login'),
      path('register', views.register, name='register'),
      path('logout', views.logout, name='logout'),

    ]
</code>```

index.html

```<code>    <a class="nav-link" href="{{ request.user }}">{{ user.username }}</a>
</code>```

答:
"@Willem Van Onsem" has given perfectly correct answer. But one thing I want to add is to prevent the overlap. You can rearrange the rules and put that rule at bottom of all rules. because django checks the rule from top to bottom and stop matching when first match is found.

```<code>urlpatterns = [
        path('login/', views.login, name='login'),
        path('register/', views.register, name='register'),
        path('logout/', views.logout, name='logout'),

        path('<str:username>/', views.profile, name='profile'),
 ]
</code>```

things should work fine.
But, as commented, we have to put validation that user can't use username from any above path name, like login, register or logout.
Also, would like to suggest that don't use these kind of patterns, instead use at least small prefixes like u/<profile> or u/<id> etc, which can be seen in many existing applications like gmail.

Title: How to link to user's profile on django

Body:
I have been trying to link to user's profile page but everytime I try it, it returns a 404 error. I dont know but maybe the error is on the urls.py file.

views.py

    def profile(request, username=None):
      if username:
        post_owner = get_object_or_404(User, username=username)

      else:
        post_owner = request.user

      args1 = {
        'post_owner': post_owner,
      }
      return render(request, 'profile.html', args1)

urls.py

    urlpatterns = [
      path('<str:username>/', views.profile, name='profile'),
      path('login', views.login, name='login'),
      path('register', views.register, name='register'),
      path('logout', views.logout, name='logout'),

    ]

index.html

    {{ user.username }}

Body:
"@Willem Van Onsem" has given perfectly correct answer. But one thing I want to add is to prevent the overlap. You can rearrange the rules and put that rule at bottom of all rules. because django checks the rule from top to bottom and stop matching when first match is found.

urlpatterns = [
        path('login/', views.login, name='login'),
        path('register/', views.register, name='register'),
        path('logout/', views.logout, name='logout'),

        path('<str:username>/', views.profile, name='profile'),
 ]

things should work fine.
But, as commented, we have to put validation that user can't use username from any above path name, like login, register or logout.
Also, would like to suggest that don't use these kind of patterns, instead use at least small prefixes like u/<profile> or u/<id> etc, which can be seen in many existing applications like gmail.


问:
Spring Boot https redirect
I deployed a Spring Boot web application to AWS and configured SSL certificate for a domain. Every time I click a Login button mapped to:

```<code>@RequestMapping("/login")
public String login(){
   return "login";
}
</code>```

I'm redirected to https login page. However, when a user tries to access a page that requires authorization, he is redirected to unsecured http login page.
My Spring Security look like follows:

```<code>http
.authorizeRequests()
.antMatchers(HttpMethod.GET,"/","/css/**","/images/**","/js/**").permitAll()
.antMatchers("/").permitAll()
.antMatchers("/index").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.deleteCookies("remember-me")
.logoutSuccessUrl("/login?logout")
.permitAll();
</code>```

Here is live example: test4test.io

答:
Assuming that connection is secure until it hits application, you will have to add following to security config to make all requests secure. </p>

```<code>http.requiresChannel().anyRequest().requiresSecure();
</code>```

<p>If the tls is terminating at the load balancer(which may not be ideal but there are cases) then this may not work. In such circumstances, in aws alb/nlb, a listener can be added on port 80 which can redirect to port 443. This would not require any change in the application as the redirection happens from hte load balancer before the application gets the request. </p>

Title: Spring Boot https redirect

Body:
I deployed a Spring Boot web application to AWS and configured SSL certificate for a domain. Every time I click a Login button mapped to:

@RequestMapping("/login")
public String login(){
   return "login";
}

I'm redirected to https login page. However, when a user tries to access a page that requires authorization, he is redirected to unsecured http login page.
My Spring Security look like follows:

http
.authorizeRequests()
.antMatchers(HttpMethod.GET,"/","/css/**","/images/**","/js/**").permitAll()
.antMatchers("/").permitAll()
.antMatchers("/index").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.deleteCookies("remember-me")
.logoutSuccessUrl("/login?logout")
.permitAll();

Here is live example: test4test.io

Body:
Assuming that connection is secure until it hits application, you will have to add following to security config to make all requests secure.

http.requiresChannel().anyRequest().requiresSecure();

If the tls is terminating at the load balancer(which may not be ideal but there are cases) then this may not work. In such circumstances, in aws alb/nlb, a listener can be added on port 80 which can redirect to port 443. This would not require any change in the application as the redirection happens from hte load balancer before the application gets the request.


问:
Node Mocha test log save to disk
Need to save the test logging to the disk

I have tried the below code

```<code>  mocha -R spec  test/**/*_test.js   >  report
</code>```

suppose any test case failed it not log into the 'report' file. Please suggest best way to log the test report.

答:
Or you can simplify to just</p>

```<code>mocha --colors  ./test/**/*_test.js 2>&1 | tee ./reports/report.log
</code>```

Title: Node Mocha test log save to disk

Body:
Need to save the test logging to the disk

I have tried the below code

  mocha -R spec  test/**/*_test.js   >  report

suppose any test case failed it not log into the 'report' file. Please suggest best way to log the test report.

Body:
Or you can simplify to just

mocha --colors  ./test/**/*_test.js 2>&1 | tee ./reports/report.log


问:
Nest.js injection of model?
I have the follwoing code from tutorial|:

```<code>constructor(@InjectModel('User') private readonly userModel: Model<User>) {}
</code>```

Where User is:

```<code>export interface User extends Document {
  readonly name: string;
  readonly age: number;
  readonly phone: string;
}
</code>```

Could you explain how @InjectModel works, what is 'User' and why we passed Model<User>, what does it mean?

What I can inject also using @InjectModel?

答:
All right, to get into this, first we have to take to truth that interfaces do not exist at runtime. So the User interface you have is only useful during development. I'll try to break this down step by step, starting from the end of the line and working backwards.

Model<User>: Model is an interface type exposed by mongoose that allows us to know that the model we're using has methods like find and create. By saying Model<User> we are saying "This is a mongoose model object that refers to the User interface. This is especially useful for Typescript because as the functions are typed with generics, it knows what the return of methods like find are: an array of User objects. The model interface is really Model<T> where T is the interface that extends Document (another mongoose type).

What is 'User': 'User' is the string equivalent of the name of the interface. If your interface that extends Document is called Dog you use 'Dog', if it's Animal you use 'Animal'. The reason for not passing the interface is because interfaces do not exist at runtime (unlike classes).

How does @InjectModel() work: Okay, the really fun part of the question to answer. Nest works normally by using Injection Tokens. Normally, these tokens are determined by the type of the injected value. In your case Model<User>. Now, the problem here is that A) interfaces don't exist at runtime and B) Typescript does not reflect generics well, so even if Model was a class, all that could be gotten would be Model which isn't enough information on what to inject. So the next logical step Nest takes is to allow a user to provide injection tokens and use the @Inject() decorator. You can do things like injecting an object this way (like package configuration information). Useful, but a bit hard to work with without building your own providers. Now steps in @InjectModel(). @InjectModel() builds an injection token based on the string that's passed into the function. This token is something along the lines of typeModel where type is actually what you pass into the function. This tells Nest specifically what model we are injecting. This also needs to align with the provider created with MongooseModule.forFeature(), hence why name and the value passed to @InjectModel() need to be aligned. Usually it's easiest to align when they use the same string name as the interface.

Title: Nest.js injection of model?

Body:
I have the follwoing code from tutorial|:

constructor(@InjectModel('User') private readonly userModel: Model<User>) {}

Where User is:

export interface User extends Document {
  readonly name: string;
  readonly age: number;
  readonly phone: string;
}

Could you explain how @InjectModel works, what is 'User' and why we passed Model<User>, what does it mean?

What I can inject also using @InjectModel?


问:
WPF - How do I sort a DataGridTemplateColumn with a list of strings as content
I have the following code:

```<code>    <DataGrid ItemsSource="{Binding FilteredLectureViewModels}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
            <!-- Profs -->
            <DataGridTemplateColumn Header="Profs">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate DataType="viewModels:LectureViewModel">
                        <ItemsControl ItemsSource="{Binding Profs}">
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <TextBlock Text="{Binding ProfString}"/>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
</code>```

I want the datagrid to sort its content by clicking on the header 'Profs' like it's working for a DataGridTextColumn with the header 'Name' already by default. I know the attribute 'SortMemberPath' of the DataGridTemplateColumn, but i don't know how to use that in this situation.

答:
In bindings, you can use brackets [ ] to supply an index for a collection as part of the binding path. Upon testing, this same approach seems to work for SortMemberPath:

```<code><DataGridTemplateColumn Header="Profs" SortMemberPath="Profs[0].ProfString">
</code>```

This sorts based on the ProfString property of the first item in Profs. I'm not sure why you would want to sort based on the first item in a collection, but this does it.

Body:
I have the following code:

    <DataGrid ItemsSource="{Binding FilteredLectureViewModels}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>

            <DataGridTemplateColumn Header="Profs">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate DataType="viewModels:LectureViewModel">
                        <ItemsControl ItemsSource="{Binding Profs}">
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <TextBlock Text="{Binding ProfString}"/>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

I want the datagrid to sort its content by clicking on the header 'Profs' like it's working for a DataGridTextColumn with the header 'Name' already by default. I know the attribute 'SortMemberPath' of the DataGridTemplateColumn, but i don't know how to use that in this situation.

Body:
In bindings, you can use brackets [ ] to supply an index for a collection as part of the binding path. Upon testing, this same approach seems to work for SortMemberPath:

<DataGridTemplateColumn Header="Profs" SortMemberPath="Profs[0].ProfString">

This sorts based on the ProfString property of the first item in Profs. I'm not sure why you would want to sort based on the first item in a collection, but this does it.


问:
Using flask url_for in script tag to pass parameters to a route
I want to pass a token to a route from my script tag but cant find a way to make this work.

So far I have made this:

```<code><script>
some code...
  window.location.href = {{ url_for ("payment_success", token=token ) }};
</script>
</code>```

But it's not returning anything. All my routes are ok. I don't have really much idea about javascript. Thanks in advance

答: The devil hides in details. I forgot to put "" between {{ url_for..... }}

Body:
I want to pass a token to a route from my script tag but cant find a way to make this work.

So far I have made this:

But it's not returning anything. All my routes are ok. I don't have really much idea about javascript. Thanks in advance


问:
c# combobox automaticaly populated by inputed mysql data
I have two user controls. One is to input data and another one has a combobox that displays data from my MySQL table.

The use types in data in the first user control and presses a button.  This adds the data to a MySQL table.  I want to add the data immediately / automatically into the combobox (the other user control).

I would prefer not doing it using an event.  If it is not possible and I have to use an event, what event should I use?  Can it be an event not associated to the button?

Here is the method that reads data from MySQL and adds it to the combobox :

```<code>private void LoadFromDatabase()
{
    string query = "select name from country";
    MySqlConnection conn = new MySqlConnection(connection);
    MySqlCommand command = new MySqlCommand(query,conn);
    MySqlDataReader Read;
    conn.Open();
    Read = command.ExecuteReader();
    while(Read.Read())
    {
        metroComboBox1.Items.Add(Read.GetString("name"));
    }
    conn.Close();
}
</code>```

The current result is that I must reload the windows form to load the new data into thecombobox.  Without the reload, the combobox only displays the old data.  I have put that method under InitializeComponent(); of the combobox user control.

答:
You can use the event click on the comboBox itself, so whenever you click it to open the dropdown it will update the combobox. Make sure to clear the items at the top of the click event to prevent duplicates.

If you truly insist on having no events, you can use a background worker, however for what you're doing it seems like overkill to spawn a thread just for that.

This is an idea of what the final result should look like.

```<code>private void comboBox1_Click(object sender, EventArgs e)
{
    if (comboBox1.Items.Count > 0)
        comboBox1.Items.Clear();

    LoadFromDatabase();

    comboBox1.SelectedItem = 0;
    comboBox1.Text = "Select Item";
}
</code>```

Body:
I have two user controls. One is to input data and another one has a combobox that displays data from my MySQL table.

The use types in data in the first user control and presses a button.  This adds the data to a MySQL table.  I want to add the data immediately / automatically into the combobox (the other user control).

I would prefer not doing it using an event.  If it is not possible and I have to use an event, what event should I use?  Can it be an event not associated to the button?

Here is the method that reads data from MySQL and adds it to the combobox :

private void LoadFromDatabase()
{
    string query = "select name from country";
    MySqlConnection conn = new MySqlConnection(connection);
    MySqlCommand command = new MySqlCommand(query,conn);
    MySqlDataReader Read;
    conn.Open();
    Read = command.ExecuteReader();
    while(Read.Read())
    {
        metroComboBox1.Items.Add(Read.GetString("name"));
    }
    conn.Close();
}

The current result is that I must reload the windows form to load the new data into thecombobox.  Without the reload, the combobox only displays the old data.  I have put that method under InitializeComponent(); of the combobox user control.

Body:
You can use the event click on the comboBox itself, so whenever you click it to open the dropdown it will update the combobox. Make sure to clear the items at the top of the click event to prevent duplicates.

If you truly insist on having no events, you can use a background worker, however for what you're doing it seems like overkill to spawn a thread just for that.

This is an idea of what the final result should look like.

private void comboBox1_Click(object sender, EventArgs e)
{
    if (comboBox1.Items.Count > 0)
        comboBox1.Items.Clear();

    LoadFromDatabase();

    comboBox1.SelectedItem = 0;
    comboBox1.Text = "Select Item";
}


问:
Can VSCodeVim Ignore Windows Key Combination?
I have Windows+I set as a keyboard shortcut to open up chrome, but if I try to use that while keyboard focus is on VSCode with vscodevim enabled, it treats it as if I had just typed I by itself (and enters insert mode).

I'm running mate desktop manager on Arch Linux. The Win-I shortcut is set through system -> preferences -> hardware -> keyboard shortcuts.

I've tried adding the following to settings.json:

```<code>    "vim.handleKeys": {
        "<T-i>": false
    }
</code>```

I've also tried <Win-i>, <T-I>, <Win-I>, <Mod4-I>.

Is there a different syntax to specifiy windows key being pressed? Or a different way to have ideavim register that it's pressed and ignore the input? The key is displayed as Mod4 in the mate keyboard shortcuts menu.

I know I can map the chrome shortcut to something else like Alt+F3, but I'm hoping to keep it as Win+I if possible. Any help appreciated!

答:
Try adding the following setting:

```<code>"keyboard.dispatch": "keyCode"
</code>```

Restart vscode after that.

Body:
I have Windows+I set as a keyboard shortcut to open up chrome, but if I try to use that while keyboard focus is on VSCode with vscodevim enabled, it treats it as if I had just typed I by itself (and enters insert mode).

I'm running mate desktop manager on Arch Linux. The Win-I shortcut is set through system -> preferences -> hardware -> keyboard shortcuts.

I've tried adding the following to settings.json:

    "vim.handleKeys": {
        "<T-i>": false
    }

I've also tried <Win-i>, <T-I>, <Win-I>, <Mod4-I>.

Is there a different syntax to specifiy windows key being pressed? Or a different way to have ideavim register that it's pressed and ignore the input? The key is displayed as Mod4 in the mate keyboard shortcuts menu.

I know I can map the chrome shortcut to something else like Alt+F3, but I'm hoping to keep it as Win+I if possible. Any help appreciated!

Body:
Try adding the following setting:

"keyboard.dispatch": "keyCode"

Restart vscode after that.


问:
Drag and Drop — Only Folders Accepted
I'm writing a custom view that needs to accept folder drops. The condition is: only directories are accepted, so when user drags a file nothing should happen.

I've registered my view with:

```<code>[self registerForDraggedTypes:[NSArray arrayWithObject:NSFilenamesPboardType]];
</code>```

And the basic dragging protocol methods are already implemented. For testing purposes:

```<code>- (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender
{
    NSLog("@Drag Entered");
    return NSDragOperationCopy;
}

- (NSDragOperation)draggingUpdated:(id<NSDraggingInfo>)sender
{
    return NSDragOperationCopy;
}

- (void)draggingExited:(id<NSDraggingInfo>)sender
{
    NSLog(@"Dragging Exited");
}

- (BOOL)prepareForDragOperation:(id<NSDraggingInfo>)sender { return YES; }
- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender    { return YES; }
</code>```

So it works almost correctly: the cursor gets a plus sign when dragging over the view. However I'd like to avoid that if the item is a regular file.

I'll probably need to do that with NSFileManager (though I wonder if there is an easier way) once I get the dragged path, but the question is where. I've tried to include the test right in the draggingEntered: method returning NSDragOperationNone with no success. I'm following a snippet from Apple documentation:

```<code>{
    NSPasteboard *pboard = [sender draggingPasteboard];

    if ( [[pboard types] containsObject:NSFilenamesPboardType] ) {
        NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
        int numberOfFiles = [files count];
        // Perform operation using the list of files
    }
    return YES;
}
</code>```

Where should I implement this test, so the cursor stays the same if a file is dragged instead?

答:
You should implement the test in -draggingEntered: and return NSDragOperationNone if the pasteboard contains a file.

However, since you have also implemented ‑draggingUpdated:, you'll need to add the test for folder types to that method also.

At present you're always returning NSDragOperationCopy in ‑draggingUpdated: without testing for the file type, which means that as soon as the mouse moves inside your dragging destination, the cursor will change to a copy cursor no matter what you do in ‑draggingEntered:.

Note that implementing ‑draggingUpdated: is optional. If you aren't implementing a complex view with multiple possible dragging destinations then you don't need to implement it, just ‑draggingEntered: and ‑draggingExited:.

Title: Drag and Drop — Only Folders Accepted

Body:
I'm writing a custom view that needs to accept folder drops. The condition is: only directories are accepted, so when user drags a file nothing should happen.

I've registered my view with:

[self registerForDraggedTypes:[NSArray arrayWithObject:NSFilenamesPboardType]];

And the basic dragging protocol methods are already implemented. For testing purposes:

- (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender
{
    NSLog("@Drag Entered");
    return NSDragOperationCopy;
}

- (NSDragOperation)draggingUpdated:(id<NSDraggingInfo>)sender
{
    return NSDragOperationCopy;
}

- (void)draggingExited:(id<NSDraggingInfo>)sender
{
    NSLog(@"Dragging Exited");
}

- (BOOL)prepareForDragOperation:(id<NSDraggingInfo>)sender { return YES; }
- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender    { return YES; }

So it works almost correctly: the cursor gets a plus sign when dragging over the view. However I'd like to avoid that if the item is a regular file.

I'll probably need to do that with NSFileManager (though I wonder if there is an easier way) once I get the dragged path, but the question is where. I've tried to include the test right in the draggingEntered: method returning NSDragOperationNone with no success. I'm following a snippet from Apple documentation:

{
    NSPasteboard *pboard = [sender draggingPasteboard];

    if ( [[pboard types] containsObject:NSFilenamesPboardType] ) {
        NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
        int numberOfFiles = [files count];
        // Perform operation using the list of files
    }
    return YES;
}

Where should I implement this test, so the cursor stays the same if a file is dragged instead?


问:
Mapping using ggmap & Stamen maps in R: labelling points and scale
I'm trying to make a map of my study site using ggmap & Stamen maps. I've seen a few similar questions but haven't figured out a way to incorporate the solution into my Stamen map code.

I have two questions regarding this:
1. How can I custom label the points on the map?
2. How can I add a scale to maps in Stamen map? (either as a line indicating distance or something like x cm on map = y km in real life)

```<code>Tcoords <- read.csv("Tcoords.csv")
</code>```

My file looks like this

```<code># trap latitude longitude
1 52.34431 0.5374620
2 52.34281 0.5382080
3 52.34468 0.5406787
4 52.34357 0.5398280
5 52.34431 0.5397050
6 52.34516 0.5406294
</code>```

In response to the suggestion, I've pasted the results to dput(head(Tcoords)) here:

```<code> structure(list(trap = c("1", "2", "3", "4", "5", "6"), latitude = c(52.344312,
52.342809, 52.3446849, 52.343572, 52.34431, 52.3451601), longitude = c(0.537462,
0.538208, 0.5406787, 0.539828, 0.539705, 0.5406294)), row.names = c(NA,
6L), class = "data.frame")
</code>```

This the code I'm using to plot my points

```<code>center = c(lon = 0.5406294, lat = 52.3451601)
qmap(center, zoom = 16, source = "stamen", maptype = "watercolor")+
      geom_point(aes(x = longitude, y = latitude), size = 4, shape = 21,
                 fill = "dark green", data = Tcoords)
</code>```

But somehow trap isn't being recognised as an object. It's probably something elementary but I'm not really sure what I've missed (new to R). I've saved "trap" as a text object here.

Thanks for your help!

答:
Getting the labels onto the map was just a matter of redefining the data source in the geom_text() function.

In order to get the scale to print on the map, it was a matter of following the solution in this question: Is there a way to add a scale bar (for linear distances) to ggmap?

```<code>#get base map
map.base <- get_map(location = center, zoom = 16, source = "stamen", maptype = "watercolor") # could also use zoom = "auto"
#get extent of base map
bb <- attr(map.base,"bb")

#define the location and length of scale bar
sbar <- data.frame(lon.start = c(bb$ll.lon + 0.1*(bb$ur.lon - bb$ll.lon)),
                   lon.end = c(bb$ll.lon + 0.25*(bb$ur.lon - bb$ll.lon)),
                   lat.start = c(bb$ll.lat + 0.1*(bb$ur.lat - bb$ll.lat)),
                   lat.end = c(bb$ll.lat + 0.1*(bb$ur.lat - bb$ll.lat)))

#Calculate distance in meters
library(geosphere)
sbar$distance = distGeo(c(sbar$lon.start,sbar$lat.start), c(sbar$lon.end,sbar$lat.end))

map.scale <- ggmap(map.base, extent="device")   +
   geom_point(aes(x = longitude, y = latitude), size = 4, shape = 21, fill = "dark green", data = Tcoords) +
   geom_text(data=Tcoords, aes(label=trap, x = longitude, y = latitude), nudge_x = 0.0001, nudge_y = 0.0001, color="black") +

   geom_segment(data = sbar,  aes(x = lon.start, xend = lon.end, y = lat.start, yend = lat.end)) +
   geom_text(data = sbar,  aes(x = (lon.start + lon.end)/2,
                 y = lat.start + 0.025*(bb$ur.lat - bb$ll.lat),
                 label = paste(format(distance,   digits = 4, nsmall = 2), 'm')),
             hjust = 0.5, vjust = 0)
map.scale
</code>```

May need to adjust the nudge_x & _y in the geom_text() function for proper label placement.

Body:
I'm trying to make a map of my study site using ggmap & Stamen maps. I've seen a few similar questions but haven't figured out a way to incorporate the solution into my Stamen map code.

I have two questions regarding this:
1. How can I custom label the points on the map?
2. How can I add a scale to maps in Stamen map? (either as a line indicating distance or something like x cm on map = y km in real life)

Tcoords <- read.csv("Tcoords.csv")

My file looks like this

# trap latitude longitude
1 52.34431 0.5374620
2 52.34281 0.5382080
3 52.34468 0.5406787
4 52.34357 0.5398280
5 52.34431 0.5397050
6 52.34516 0.5406294

In response to the suggestion, I've pasted the results to dput(head(Tcoords)) here:

 structure(list(trap = c("1", "2", "3", "4", "5", "6"), latitude = c(52.344312,
52.342809, 52.3446849, 52.343572, 52.34431, 52.3451601), longitude = c(0.537462,
0.538208, 0.5406787, 0.539828, 0.539705, 0.5406294)), row.names = c(NA,
6L), class = "data.frame")

This the code I'm using to plot my points

center = c(lon = 0.5406294, lat = 52.3451601)
qmap(center, zoom = 16, source = "stamen", maptype = "watercolor")+
      geom_point(aes(x = longitude, y = latitude), size = 4, shape = 21,
                 fill = "dark green", data = Tcoords)

But somehow trap isn't being recognised as an object. It's probably something elementary but I'm not really sure what I've missed (new to R). I've saved "trap" as a text object here.

Thanks for your help!

Body:
Getting the labels onto the map was just a matter of redefining the data source in the geom_text() function.

In order to get the scale to print on the map, it was a matter of following the solution in this question: Is there a way to add a scale bar (for linear distances) to ggmap?

#get base map
map.base <- get_map(location = center, zoom = 16, source = "stamen", maptype = "watercolor") # could also use zoom = "auto"
#get extent of base map
bb <- attr(map.base,"bb")

#define the location and length of scale bar
sbar <- data.frame(lon.start = c(bb$ll.lon + 0.1*(bb$ur.lon - bb$ll.lon)),
                   lon.end = c(bb$ll.lon + 0.25*(bb$ur.lon - bb$ll.lon)),
                   lat.start = c(bb$ll.lat + 0.1*(bb$ur.lat - bb$ll.lat)),
                   lat.end = c(bb$ll.lat + 0.1*(bb$ur.lat - bb$ll.lat)))

#Calculate distance in meters
library(geosphere)
sbar$distance = distGeo(c(sbar$lon.start,sbar$lat.start), c(sbar$lon.end,sbar$lat.end))

map.scale <- ggmap(map.base, extent="device")   +
   geom_point(aes(x = longitude, y = latitude), size = 4, shape = 21, fill = "dark green", data = Tcoords) +
   geom_text(data=Tcoords, aes(label=trap, x = longitude, y = latitude), nudge_x = 0.0001, nudge_y = 0.0001, color="black") +

   geom_segment(data = sbar,  aes(x = lon.start, xend = lon.end, y = lat.start, yend = lat.end)) +
   geom_text(data = sbar,  aes(x = (lon.start + lon.end)/2,
                 y = lat.start + 0.025*(bb$ur.lat - bb$ll.lat),
                 label = paste(format(distance,   digits = 4, nsmall = 2), 'm')),
             hjust = 0.5, vjust = 0)
map.scale

May need to adjust the nudge_x & _y in the geom_text() function for proper label placement.


问:
Calculate total in SQL from two different rows by date
I have a table with: date, daily_count and total_count and total_count is empty and has to be calculated with MySQL. Date and daily_count are known and I want to calculate today's total_count from daily_count(today) + total count(yesterday).

I can calculate it with:

```<code>SELECT t2.daily_count + t1.total_count total
 FROM mytbl t1, mytbl t2
 WHERE t1.date = '2020-2-27' AND t2.date = '2020-2-28'
</code>```

How can I do that at once for a table with more than one year of data and with only date en daily count. So all the total_counts have to be calculated. And later I want to UPDATE the total into total_count in mytbl. Or do I have two write down all the 365 SQL lines with different dates for one year of data?

答:
If you are running MySQL 8.0, you can do this easily with window functions:

```<code>select date, daily_count, sum(daily_count) over(order by date) total_count
from mytbl
</code>```

You can turn this to an update query as follows (assuming that date is a unique column):

```<code>update mybtl t
inner join (
    select date, sum(daily_count) over(order by date) total_count
    from mytbl
) t1 on t1.date = t.date
set t.total_count = t1.total_count
</code>```

Body:
I have a table with: date, daily_count and total_count and total_count is empty and has to be calculated with MySQL. Date and daily_count are known and I want to calculate today's total_count from daily_count(today) + total count(yesterday).

I can calculate it with:

SELECT t2.daily_count + t1.total_count total
 FROM mytbl t1, mytbl t2
 WHERE t1.date = '2020-2-27' AND t2.date = '2020-2-28'

How can I do that at once for a table with more than one year of data and with only date en daily count. So all the total_counts have to be calculated. And later I want to UPDATE the total into total_count in mytbl. Or do I have two write down all the 365 SQL lines with different dates for one year of data?

Body:
If you are running MySQL 8.0, you can do this easily with window functions:

select date, daily_count, sum(daily_count) over(order by date) total_count
from mytbl

You can turn this to an update query as follows (assuming that date is a unique column):

update mybtl t
inner join (
    select date, sum(daily_count) over(order by date) total_count
    from mytbl
) t1 on t1.date = t.date
set t.total_count = t1.total_count


问:
expo start on CLI fails
expo start worked well, but after trying to build ios standalone app with expo build:ios, expo start fails with error message:

```<code>Expo DevTools is running at http://localhost:19002
Opening DevTools in the browser... (press shift-d to disable)
error Unrecognized command "start".

info Run "react-native --help" to see a list of all available commands.
Metro Bundler process exited with code 1
Error: Metro Bundler process exited with code 1
    at ChildProcess.<anonymous> (/@expo/xdl@57.9.9/src/Project.ts:1838:16)
    at Object.onceWrapper (events.js:428:26)
    at ChildProcess.emit (events.js:321:20)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
</code>```

I tried reinstalling expo-cli with yarn globally, but it does not fix the problem.

expo diagnotics outputs as:

```<code>  Expo CLI 3.20.9 environment info:
    System:
      OS: macOS 10.15.2
      Shell: 5.7.1 - /bin/zsh
    Binaries:
      Node: 13.6.0 - /usr/local/bin/node
      Yarn: 1.21.1 - /usr/local/bin/yarn
      npm: 6.13.4 - /usr/local/bin/npm
    IDEs:
      Xcode: 11.4.1/11E503a - /usr/bin/xcodebuild
    npmPackages:
      expo: ^36.0.2 => 36.0.2
      react: ~16.9.0 => 16.9.0
      react-dom: ~16.9.0 => 16.9.0
      react-native: https://github.com/expo/react-native/archive/sdk-36.0.0.tar.gz => 0.61.4
      react-native-web: ^0.12.1 => 0.12.2
</code>```

答: I was having the same error after trying to use React native for windows (and then removing it from the project), because of some wrong path references messing in files: react-native.config.js and metro.config.js. I've just deleted them and it works now.</p>

Title: expo start on CLI fails

Body:
expo start worked well, but after trying to build ios standalone app with expo build:ios, expo start fails with error message:

Expo DevTools is running at http://localhost:19002
Opening DevTools in the browser... (press shift-d to disable)
error Unrecognized command "start".

info Run "react-native --help" to see a list of all available commands.
Metro Bundler process exited with code 1
Error: Metro Bundler process exited with code 1
    at ChildProcess.<anonymous> (/@expo/xdl@57.9.9/src/Project.ts:1838:16)
    at Object.onceWrapper (events.js:428:26)
    at ChildProcess.emit (events.js:321:20)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)

I tried reinstalling expo-cli with yarn globally, but it does not fix the problem.

expo diagnotics outputs as:

  Expo CLI 3.20.9 environment info:
    System:
      OS: macOS 10.15.2
      Shell: 5.7.1 - /bin/zsh
    Binaries:
      Node: 13.6.0 - /usr/local/bin/node
      Yarn: 1.21.1 - /usr/local/bin/yarn
      npm: 6.13.4 - /usr/local/bin/npm
    IDEs:
      Xcode: 11.4.1/11E503a - /usr/bin/xcodebuild
    npmPackages:
      expo: ^36.0.2 => 36.0.2
      react: ~16.9.0 => 16.9.0
      react-dom: ~16.9.0 => 16.9.0
      react-native: https://github.com/expo/react-native/archive/sdk-36.0.0.tar.gz => 0.61.4
      react-native-web: ^0.12.1 => 0.12.2


问:
Is it possible for a function to call another function in another function app?
I want to create multiple function apps, but I'd like to know if it's possible for one function in one app to call another function in another app. I can't find any documentation on this. I looked at durable functions, but it appears the functions can talk to each other if they belong to the same task hub (i.e. same app).</p>

答: Durable Functions won't work like this because the orchestrator needs to know about the other Functions, but there's no reason you can't trigger a function in another function app. Just invoke its trigger.</p>


问:
R - CSV error - unexpected numeric constant
I have a simple csv file with around 20K+ values separated by commas. When I try to load the values in R, it gives me the error:

```<code>r:3: unexpected numeric constant
</code>```

Here is the simple command of R that I executed

```<code>someThing <- c(0.080172405,0.06233087,0.04315185,0.0652015,0.03201301.......n)
n= 70,000 values
</code>```

I cannot copy paste all the 20K+ values here. I googled this error and there is no special character or another thing except for some floating values.

EDIT

http://pastebin.com/FVkUV6kY

答:
There's a newline partway through the file, which is causing that section to look something like (replacing that newline with a space) and so after the space, there's an unexpected numeric constant.

```<code>... 0.0068243323,0.0733 7422182,0.07379706 ...
</code>```

Here's how I found it:

```<code>b <- scan(file, what=character(0))
length(b)
</code>```

The length is 2, not 1.

It can be read in as is like this:

```<code>b <- paste(b, collapse="")
b <- substring(b, 3, nchar(b)-1)
b <- strsplit(b,",")[[1]]
b2 <- as.numeric(b)
</code>```

Body:
I have a simple csv file with around 20K+ values separated by commas. When I try to load the values in R, it gives me the error:

r:3: unexpected numeric constant

Here is the simple command of R that I executed

someThing <- c(0.080172405,0.06233087,0.04315185,0.0652015,0.03201301.......n)
n= 70,000 values

I cannot copy paste all the 20K+ values here. I googled this error and there is no special character or another thing except for some floating values.

EDIT

http://pastebin.com/FVkUV6kY

Body:
There's a newline partway through the file, which is causing that section to look something like (replacing that newline with a space) and so after the space, there's an unexpected numeric constant.

... 0.0068243323,0.0733 7422182,0.07379706 ...

Here's how I found it:

b <- scan(file, what=character(0))
length(b)

The length is 2, not 1.

It can be read in as is like this:

b <- paste(b, collapse="")
b <- substring(b, 3, nchar(b)-1)
b <- strsplit(b,",")[[1]]
b2 <- as.numeric(b)


问:
Fragment$InstantiationException on inflating androidx fragment from android.app.Activity
I'm getting the following exception:

```<code>android.app.Fragment$InstantiationException: Trying to instantiate a class com.example.android.btVspTest.StageCollectionFragment that is not a Fragment
</code>```

The exception triggers within the following call to android.app.Activity.setContentView from onCreate() of my VspTestActivity class, which extends android.app.Activity:
setContentView(R.layout.activity_vsp_test);

My com.example.android.btVspTest.StageCollectionFragment extends androidx.fragment.app.Fragment. I am guessing the issue has to do with incompatibility beween android.app.Activity and androidx.fragment.app.Fragment. Is there a fix or work-around?

Application level build.gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 29

    defaultConfig {
        minSdkVersion 26
        targetSdkVersion 29
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

dependencies {
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.1.0'
    /*implementation 'com.google.android.material:material:1.1.0-alpha08'*/
    implementation 'androidx.viewpager2:viewpager2:1.0.0'
}
</code>```

activity_vsp_test.xml:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/test_layout">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/margin_huge"
        android:orientation="horizontal">

        <Button
            android:id="@+id/test_connect_button"
            android:layout_width="126dp"
            android:layout_height="match_parent"
            android:text="@string/connect" />

        <Button
            android:id="@+id/test_disconnect_button"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="@string/disconnect" />

        <Button
            android:id="@+id/test_bluetooth_button"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:onClick="startBluetoothActivity"
            android:text="Bluetooth" />

    </LinearLayout>

    <TextView
        android:id="@+id/vsp_test_connection_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/disconnected" />

    <TextView
        android:id="@+id/test_result_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <!-- 2 irrelevant linear layouts with buttons in them removed -->

    <fragment class="com.example.android.btVspTest.StageCollectionFragment"
        android:id="@+id/test_stage_collection_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
</LinearLayout>
</code>```

StageCollectionFragment.java:

```<code>package com.example.android.btVspTest;

import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.example.android.bluetoothvsp.R;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.android.material.tabs.TabLayoutMediator.TabConfigurationStrategy;

public class StageCollectionFragment extends Fragment implements TabConfigurationStrategy {
    // When requested, this adapter returns a StageFragment,
    // representing an object in the collection.
    StageCollectionAdapter demoCollectionAdapter;
    ViewPager2 viewPager;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.test_stage_layout, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        demoCollectionAdapter = new StageCollectionAdapter(this);
        viewPager = view.findViewById(R.id.test_stage_pager);
        viewPager.setAdapter(demoCollectionAdapter);

        TabLayout tabLayout = view.findViewById(R.id.test_stage_tab_layout);
        new TabLayoutMediator(tabLayout, viewPager, this).attach();

    }

    @Override
    public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
        tab.setText("OBJECT " + (position + 1));
    }
}
</code>```

VspTestActivity.java:

```<code>package com.example.android.btVspTest;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.android.bluetoothvsp.ActivityMessageDataKey;
import com.example.android.bluetoothvsp.BluetoothActivity;
import com.example.android.bluetoothvsp.DeviceListActivity;
import com.example.android.bluetoothvsp.R;
import com.example.android.bluetoothvsp.enums.ConnectionState;
import com.example.android.bluetoothvsp.enums.TestState;
import com.example.android.common.logger.Log;
import com.example.android.common.logger.LogWrapper;
import com.example.android.common.logger.MessageOnlyLogFilter;

public class VspTestActivity extends Activity
{
    /**
     * Debugging.
     */
    private static final String TAG = "VspTestActivity";

    /**
     * UI elements.
     */
    private TextView mConnectionTextView;
    private TextView mTestResultTextView;
    private Button mConnectButton;
    private Button mDisconnectButton;
    private Button mSynchronousTestButton;
    private Button mHostSpamButton;
    private Button mReaderSpamButton;
    private Button mBothSpamButton;

    /**
     * Objects provided by Android to facilitate Bluetooth operations.
     */
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothDevice mDevice;

    /**
     * Manger used to start and handle the communication tests.
     */
    private BluetoothVspTestManager mVspTestManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vsp_test);

        if (savedInstanceState != null) {
            return;
        }

    // Irrelevant code removed
    }

    // Irrelevant code removed

    @Override
    protected  void onStart() {
        super.onStart();
        // Irrelevant code removed
    }

    // Irrelevant code removed
}
</code>```

Some of the code is copy->paste->edit of example at https://developer.android.com/guide/navigation/navigation-swipe-view-2, with following mapping:

My StageCollectionFragment is their CollectionDemoFragment

My StageFragment is their DemoObjectFragment

That developer.android.com example unfortunately isn't complete as the layout resources are missing. I haven't been able to find a full example on the internet, of combining TabLayout & ViewPager2.

I'm trying to do something like the draft screen at https://imgur.com/a/k8Tr52y?. I would eventually have 4 to 5 tabs with actual meaningful tab titles, with the tabs being added dynamically, and specific fragments in each of the tabs.

答:
Since part of your code is using AndroidX libraries, I'll assume you are okay with going all-in and use AndroidX exclusively. You should. Right now, you are mixing old and new Android libraries and that's not a good thing. Simply do the following when declaring (pay attention to the import statements):

your activity:

import androidx.appcompat.app.AppCompatActivity;

public class VspTestActivity extends AppCompatActivity {

and your fragment:

import androidx.fragment.app.Fragment

public class StageCollectionFragment extends Fragment ...

Even easier is to let Android Studio do it all for you. Just select Refactor > Migrate to AndroidX (on the Mac)

Body:
I'm getting the following exception:

android.app.Fragment$InstantiationException: Trying to instantiate a class com.example.android.btVspTest.StageCollectionFragment that is not a Fragment

The exception triggers within the following call to android.app.Activity.setContentView from onCreate() of my VspTestActivity class, which extends android.app.Activity:
setContentView(R.layout.activity_vsp_test);

My com.example.android.btVspTest.StageCollectionFragment extends androidx.fragment.app.Fragment. I am guessing the issue has to do with incompatibility beween android.app.Activity and androidx.fragment.app.Fragment. Is there a fix or work-around?

Application level build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29

    defaultConfig {
        minSdkVersion 26
        targetSdkVersion 29
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

dependencies {
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.1.0'
    /*implementation 'com.google.android.material:material:1.1.0-alpha08'*/
    implementation 'androidx.viewpager2:viewpager2:1.0.0'
}

activity_vsp_test.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/test_layout">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/margin_huge"
        android:orientation="horizontal">

        <Button
            android:id="@+id/test_connect_button"
            android:layout_width="126dp"
            android:layout_height="match_parent"
            android:text="@string/connect" />

        <Button
            android:id="@+id/test_disconnect_button"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="@string/disconnect" />

        <Button
            android:id="@+id/test_bluetooth_button"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:onClick="startBluetoothActivity"
            android:text="Bluetooth" />

    </LinearLayout>

    <TextView
        android:id="@+id/vsp_test_connection_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/disconnected" />

    <TextView
        android:id="@+id/test_result_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <fragment class="com.example.android.btVspTest.StageCollectionFragment"
        android:id="@+id/test_stage_collection_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
</LinearLayout>

StageCollectionFragment.java:

package com.example.android.btVspTest;

import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.example.android.bluetoothvsp.R;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.android.material.tabs.TabLayoutMediator.TabConfigurationStrategy;

public class StageCollectionFragment extends Fragment implements TabConfigurationStrategy {
    // When requested, this adapter returns a StageFragment,
    // representing an object in the collection.
    StageCollectionAdapter demoCollectionAdapter;
    ViewPager2 viewPager;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.test_stage_layout, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        demoCollectionAdapter = new StageCollectionAdapter(this);
        viewPager = view.findViewById(R.id.test_stage_pager);
        viewPager.setAdapter(demoCollectionAdapter);

        TabLayout tabLayout = view.findViewById(R.id.test_stage_tab_layout);
        new TabLayoutMediator(tabLayout, viewPager, this).attach();

    }

    @Override
    public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
        tab.setText("OBJECT " + (position + 1));
    }
}

VspTestActivity.java:

package com.example.android.btVspTest;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.android.bluetoothvsp.ActivityMessageDataKey;
import com.example.android.bluetoothvsp.BluetoothActivity;
import com.example.android.bluetoothvsp.DeviceListActivity;
import com.example.android.bluetoothvsp.R;
import com.example.android.bluetoothvsp.enums.ConnectionState;
import com.example.android.bluetoothvsp.enums.TestState;
import com.example.android.common.logger.Log;
import com.example.android.common.logger.LogWrapper;
import com.example.android.common.logger.MessageOnlyLogFilter;

public class VspTestActivity extends Activity
{
    /**
     * Debugging.
     */
    private static final String TAG = "VspTestActivity";

    /**
     * UI elements.
     */
    private TextView mConnectionTextView;
    private TextView mTestResultTextView;
    private Button mConnectButton;
    private Button mDisconnectButton;
    private Button mSynchronousTestButton;
    private Button mHostSpamButton;
    private Button mReaderSpamButton;
    private Button mBothSpamButton;

    /**
     * Objects provided by Android to facilitate Bluetooth operations.
     */
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothDevice mDevice;

    /**
     * Manger used to start and handle the communication tests.
     */
    private BluetoothVspTestManager mVspTestManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vsp_test);

        if (savedInstanceState != null) {
            return;
        }

    // Irrelevant code removed
    }

    // Irrelevant code removed

    @Override
    protected  void onStart() {
        super.onStart();
        // Irrelevant code removed
    }

    // Irrelevant code removed
}

Some of the code is copy->paste->edit of example at https://developer.android.com/guide/navigation/navigation-swipe-view-2, with following mapping:

My StageCollectionFragment is their CollectionDemoFragment

My StageFragment is their DemoObjectFragment

That developer.android.com example unfortunately isn't complete as the layout resources are missing. I haven't been able to find a full example on the internet, of combining TabLayout & ViewPager2.

I'm trying to do something like the draft screen at https://imgur.com/a/k8Tr52y?. I would eventually have 4 to 5 tabs with actual meaningful tab titles, with the tabs being added dynamically, and specific fragments in each of the tabs.


问:
Cannot match region between Google App Engine & VPC Network
I am setting a private connection between my project's Google App Engine and Compute engine with a serverless VPC network. The region of the GAE is set in northamerica-northeast1 (which can't be changed as described in the documentation), so I am trying to set up the VPC connector to be in the same region, following this guide.

When creating a new serverless VPC connector, it looks like there is no region selection for northamerica-northeast1, as shown in the screenshot. Is there a way to set up the connector to this region already set by app engine? At this point the last thing I want to do is start an entirely new project just to re-setup app engine and other applications on GCP.

I have seen some responses in the past about getting whitelisted to be given access to specific requests such as this, but again, I do not know how to go about that process either, if that is my best option.

答: Because of the current product limitations,to set a connection between App Engine and Compute Engine please file a feature request in our Public Issue Tracker and we will  implement support for the northamerica-northeast1 region. To do so please refer to link[1]</p>


问:
Passing <List> filter values to an action component (REACTADMIN)
How can I get the filter values of my ReactAdmin  Element ?
I can get the size of the List, but I don't know how to get the filter, that I can pass to my custom action component:

in my App.tsx:

```<code>const MyActions = ({
    total,
    filters,
    filterValues,
    ...rest
}) => (
    <MyButton listsize={total} filters={filters} filterValues={filterValues} />
);

export const MyFilter = (props) => (
    <Filter {...props}>
        <TextInput label="Search" source="q" alwaysOn/>
    </Filter>
);

<List {...props} actions={<MyActions {...props}/>} title="My List" perPage={25} filters={<MyFilter/>}>
        <Datagrid rowClick="edit">
            <TextField source="id"/>
            <TextField source="name"/>
            <TextField source="info"/>
        </Datagrid>
    </List>
);
</code>```

My Action Button Component;

```<code>class MyButton extends React.Component {

    constructor(props) {
        super(props)
    }

    render() {
    console.log('this.props.listsize : ' + JSON.stringify(this.props.listsize));
    console.log('this.props.filters : ' + this.props.filters);
console.log('this.props.filterValues.q : ' + this.props.filterValues.q);
        return (
            <anyContent...>
        )
    }
}
</code>```

The Console Output is just:

```<code>this.props.listsize : 145 (Size is correct)

this.props.filters : [object Object]

this.props.filters.filterValues.q : undefined
</code>```

How can I fetch the current filter for the  ?

答:
Filter value can be obtained from the property: filterValues: {q: "test"}
https://marmelab.com/react-admin/List.html#empty-page

Body:
How can I get the filter values of my ReactAdmin  Element ?
I can get the size of the List, but I don't know how to get the filter, that I can pass to my custom action component:

in my App.tsx:

const MyActions = ({
    total,
    filters,
    filterValues,
    ...rest
}) => (
    <MyButton listsize={total} filters={filters} filterValues={filterValues} />
);

export const MyFilter = (props) => (
    <Filter {...props}>
        <TextInput label="Search" source="q" alwaysOn/>
    </Filter>
);

<List {...props} actions={<MyActions {...props}/>} title="My List" perPage={25} filters={<MyFilter/>}>
        <Datagrid rowClick="edit">
            <TextField source="id"/>
            <TextField source="name"/>
            <TextField source="info"/>
        </Datagrid>
    </List>
);

My Action Button Component;

class MyButton extends React.Component {

    constructor(props) {
        super(props)
    }

    render() {
    console.log('this.props.listsize : ' + JSON.stringify(this.props.listsize));
    console.log('this.props.filters : ' + this.props.filters);
console.log('this.props.filterValues.q : ' + this.props.filterValues.q);
        return (
            <anyContent...>
        )
    }
}

The Console Output is just:

this.props.listsize : 145 (Size is correct)

this.props.filters : [object Object]

this.props.filters.filterValues.q : undefined

How can I fetch the current filter for the  ?


问:
Should I be using the django.contrib.auth.models User model? Or is it better to create my own User model?
I'm still a beginner, and for some reason using a built in model such as User seems bugs me a bit. Should I create my own User model to become a more independent programmer, or will the User model do just as fine if not better for my project? Please tell me about the pros and cons about the User model. Any help is much appreciated. </p>

答:
it bugged me a bit too and now I use node, though Django is great for getting started with conventional concepts you'll keep running into over and over. For example, If you use the User module, you get authentication and admin panel with not too much more work. The downside is you'll feel a bit like an outsider in your own code. Modifying a built in model is weird, especially when so many other Django components depend on so many attributes.

If you're weighing your options, consider how much you need the free admin and auth. My personal recommendation is to build your own User model and implement the Django-specific attributes yourself.


问:
Remove special caracters,numbers in an ARABIC text file with python
I want to keep only arabic characters, no numbers, i got this regex instruction from github.

```<code>    generalPath="C:/Users/Desktop/Code/dataset/"
    outputPath= "C:/Users/Desktop/Code/output/"
    files = os.listdir(generalPath)

    for onefile in files:
    # relative or absolute file path, e.g.:
        localPath=generalPath+onefile
        localOutputPath=outputPath+onefile
        print(localPath)
        print(localOutputPath)
        with open(localPath, 'rb') as infile, open(localOutputPath, 'w') as outfile:
            data = infile.read().decode('utf-8')
            new_data = t = re.sub(r'[^0-9\u0600-\u06ff\u0750-\u077f\ufb50-\ufbc1\ufbd3-\ufd3f\ufd50-\ufd8f\ufd50-\ufd8f\ufe70-\ufefc\uFDF0-\uFDFD]+', ' ', data)
            outfile.write(new_data)
</code>```

In this code i got this error:
Traceback (most recent call last):
  File ".\cleanText.py", line 23, in
    outfile.write(new_data)
  File "C:\ProgramData\Anaconda3\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-2: character maps to

my arabic text is diacritised and i want to keep it like that

答:
It looks like your program is trying to read your text file with CP1252 encoding instead of UTF-8. Specify unicode on opening as shown below. Also, since it's a text file you can read using 'r' instead of 'rb'.

```<code>with open(localPath, 'r', encoding='utf8') as infile
</code>```

As for your regex, if you just want to remove numbers, you can use

```<code>data = re.sub(r'[0-9]+', '', data)
</code>```

You don't need to specify the whole Arabic alphabet as characters to keep. But it looks like you have strings like "(1/6)." To get rid of all parentheses and slashes as well, use:

```<code>data = re.sub(r'[0-9\(\)/]+', '', data)
</code>```

Body:
I want to keep only arabic characters, no numbers, i got this regex instruction from github.

    generalPath="C:/Users/Desktop/Code/dataset/"
    outputPath= "C:/Users/Desktop/Code/output/"
    files = os.listdir(generalPath)

    for onefile in files:
    # relative or absolute file path, e.g.:
        localPath=generalPath+onefile
        localOutputPath=outputPath+onefile
        print(localPath)
        print(localOutputPath)
        with open(localPath, 'rb') as infile, open(localOutputPath, 'w') as outfile:
            data = infile.read().decode('utf-8')
            new_data = t = re.sub(r'[^0-9\u0600-\u06ff\u0750-\u077f\ufb50-\ufbc1\ufbd3-\ufd3f\ufd50-\ufd8f\ufd50-\ufd8f\ufe70-\ufefc\uFDF0-\uFDFD]+', ' ', data)
            outfile.write(new_data)

In this code i got this error:
Traceback (most recent call last):
  File ".\cleanText.py", line 23, in
    outfile.write(new_data)
  File "C:\ProgramData\Anaconda3\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-2: character maps to

my arabic text is diacritised and i want to keep it like that

Body:
It looks like your program is trying to read your text file with CP1252 encoding instead of UTF-8. Specify unicode on opening as shown below. Also, since it's a text file you can read using 'r' instead of 'rb'.

with open(localPath, 'r', encoding='utf8') as infile

As for your regex, if you just want to remove numbers, you can use

data = re.sub(r'[0-9]+', '', data)

You don't need to specify the whole Arabic alphabet as characters to keep. But it looks like you have strings like "(1/6)." To get rid of all parentheses and slashes as well, use:

data = re.sub(r'[0-9\(\)/]+', '', data)


问:
this.props.dispatch().then is not a function
I am trying to do something as soon as a dispatch action finishes, and a similar question led me to try to use .then. I get an error that it doesn't exist, this.props.dispatch().then is not a function:

```<code>export function unpackStore(redux_store, namespace) {
    // namespace is determined by what name you gave each reducer in combineReducers; client/reducers/index.js
    let final_props = {};
    let KEYS = Object.keys(redux_store[namespace]);
    for (let key of KEYS) {
        final_props[key] = redux_store[namespace][key];
    }
    return final_props;
}

export function basicUnpackStoreClosure(namespace) {
    return function(store) {
        let props = unpackStore(store, namespace);
        return props;
    }
}

@connect(basicUnpackStoreClosure('login_info'))
export default class LoginPage extends MyComponent {

    constructor(props) {
        let custom_methods = [
            'handleLoginOrRegisterToggle',
            'handleOnKeyDownInInputs',
            'onLoginSubmit',
            'onRegisterSubmit',
        ]
        super(props, custom_methods);
        this.state = {
            mode: 'login',
            email: '',
            password: '',
            password_confirm: ''
        };
        if (props.mode == 'register') {
            this.state.mode = 'register';
        }

    }

    onLoginSubmit() {

        let self = this;

        let reroute = function() {
            browserHistory.push(self.props.destination_url);
        }

        this.props.dispatch({type: 'LOG_IN', payload: "fake@fake.com"})
          .then((response) => {
              browserHistory.push(self.props.destination_url);
          })
    }
</code>```

We also tried the way you do something when this.setState finishes, passing it as a second arg:

```<code>this.props.dispatch({type: 'LOG_IN', payload: "fake@fake.com"}, reroute)
</code>```

neither worked. The this.props.dispatch seems to come for free with using the @connect decorator. How can I run something only after this Redux store is updated with the "LOG_IN" action?

答: You may install 'redux-promise' middleware and include it in your store. The problem here is that the promise is not getting fulfilled. Including 'redux-promise' middleware will solve the problem</p>

Body:
I am trying to do something as soon as a dispatch action finishes, and a similar question led me to try to use .then. I get an error that it doesn't exist, this.props.dispatch().then is not a function:

export function unpackStore(redux_store, namespace) {
    // namespace is determined by what name you gave each reducer in combineReducers; client/reducers/index.js
    let final_props = {};
    let KEYS = Object.keys(redux_store[namespace]);
    for (let key of KEYS) {
        final_props[key] = redux_store[namespace][key];
    }
    return final_props;
}

export function basicUnpackStoreClosure(namespace) {
    return function(store) {
        let props = unpackStore(store, namespace);
        return props;
    }
}

@connect(basicUnpackStoreClosure('login_info'))
export default class LoginPage extends MyComponent {

    constructor(props) {
        let custom_methods = [
            'handleLoginOrRegisterToggle',
            'handleOnKeyDownInInputs',
            'onLoginSubmit',
            'onRegisterSubmit',
        ]
        super(props, custom_methods);
        this.state = {
            mode: 'login',
            email: '',
            password: '',
            password_confirm: ''
        };
        if (props.mode == 'register') {
            this.state.mode = 'register';
        }

    }

    onLoginSubmit() {

        let self = this;

        let reroute = function() {
            browserHistory.push(self.props.destination_url);
        }

        this.props.dispatch({type: 'LOG_IN', payload: "fake@fake.com"})
          .then((response) => {
              browserHistory.push(self.props.destination_url);
          })
    }

We also tried the way you do something when this.setState finishes, passing it as a second arg:

this.props.dispatch({type: 'LOG_IN', payload: "fake@fake.com"}, reroute)

neither worked. The this.props.dispatch seems to come for free with using the @connect decorator. How can I run something only after this Redux store is updated with the "LOG_IN" action?


问:
Iterating through array one at a time in react jsx
How do I iterate one index at a time in the array 'tracks' in react jsx. I want to be able to iterate and display just one track at a time in the array, and go to the next track (index) on the click of a button that'll be labeled 'Next', also go back to previous index when clicking the button 'Previous'.

```<code>  constructor(props){
     super(props);
     this.state=({
        year: (props.location.state && props.location.state.year) || '',
        all_tracks: {tracks:[]},
        currentTrack: 0,
     });
  }
  onClickNext(){ //Next button
      //Nothing done here yet
  }
  onClickPrev(){ //Previous button
      //Nothing done here yet
  }
  render(){
    const {
      currentTrack,
      all_tracks: { tracks }
    } = this.state;
    return (
        window.addEventListener('DOMContentLoaded', (event) => {
            this.gettingTracks() //Have tracks load immediately
        }),
       <div id = "song"> //THIS PART
              <iframe id="track" src={tracks[currentTrack]
                           ? "https://open.spotify.com/embed/track/"+tracks[currentTrack].id
                           : "Song N/A"} ></iframe>
       </div>
       <div>
            <button id="nextBtn"> Next </button>
       </div>
       <div>
            <button id="prevBtn"> Previous </button>
       </div>
     );
  }
</code>```

Here is where I populate the tracks array

```<code>    gettingTracks(){
    // store the current promise in case we need to abort it
    if (prev !== null) {
        prev.abort();
    }
    // store the current promise in case we need to abort it
    prev = spotifyApi.searchTracks('genre: pop year:' + this.state.year, {limit: 20, offset:1});
    prev.then((data) => {
        this.setState({
          all_tracks: {
              tracks: data.tracks.items
            }
        })
        prev = null;
    }, function(err) {
        console.error(err);
    });
}
</code>```

答:
You can store the index of the current track as a state variable. And instead of iterating over the tracks to display them, you can just simply display the current track.

Here is a simple example,

import React from "react";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      all_tracks: {
        tracks: []
      },
      currentTrack: 0
    };

    this.onClickNext = this.onClickNext.bind(this);
    this.onClickPrev = this.onClickPrev.bind(this);
  }

  componentDidMount() {
      // fetch the data  from the Spotify API and update this.state.all_tracks.tracks

  }

  onClickNext() {
    //Next button
    this.setState(prevState => {
      if (this.state.currentTrack === this.state.all_tracks.tracks.length - 1) {
        return;
      }

      return {
        ...prevState,
        currentTrack: prevState.currentTrack + 1
      };
    });
  }
  onClickPrev() {
    //Previous button
    this.setState(prevState => {
      if (this.state.currentTrack === 0) {
        return;
      }

      return { ...prevState, currentTrack: prevState.currentTrack - 1 };
    });
  }
  render() {
    const {
      currentTrack,
      all_tracks: { tracks }
    } = this.state;

    // before rendering tracks[currentTrack].name check if tracks[currentTrack] exist

    return (
      <>

Current Track

           {
             tracks[currentTrack]
                ? tracks[currentTrack].name
                : 'track does not exist'
           }

          <button id="nextBtn" onClick={this.onClickNext}>
            Next
          </button>

          <button id="prevBtn" onClick={this.onClickPrev}>
            Previous
          </button>

      </>
    );
  }
}
```

Check the codesandbox for demo

Body:
How do I iterate one index at a time in the array 'tracks' in react jsx. I want to be able to iterate and display just one track at a time in the array, and go to the next track (index) on the click of a button that'll be labeled 'Next', also go back to previous index when clicking the button 'Previous'.

  constructor(props){
     super(props);
     this.state=({
        year: (props.location.state && props.location.state.year) || '',
        all_tracks: {tracks:[]},
        currentTrack: 0,
     });
  }
  onClickNext(){ //Next button
      //Nothing done here yet
  }
  onClickPrev(){ //Previous button
      //Nothing done here yet
  }
  render(){
    const {
      currentTrack,
      all_tracks: { tracks }
    } = this.state;
    return (
        window.addEventListener('DOMContentLoaded', (event) => {
            this.gettingTracks() //Have tracks load immediately
        }),

 //THIS PART

            <button id="nextBtn"> Next </button>

            <button id="prevBtn"> Previous </button>

     );
  }

Here is where I populate the tracks array

    gettingTracks(){
    // store the current promise in case we need to abort it
    if (prev !== null) {
        prev.abort();
    }
    // store the current promise in case we need to abort it
    prev = spotifyApi.searchTracks('genre: pop year:' + this.state.year, {limit: 20, offset:1});
    prev.then((data) => {
        this.setState({
          all_tracks: {
              tracks: data.tracks.items
            }
        })
        prev = null;
    }, function(err) {
        console.error(err);
    });
}

Body:
You can store the index of the current track as a state variable. And instead of iterating over the tracks to display them, you can just simply display the current track.

Here is a simple example,

import React from "react";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      all_tracks: {
        tracks: []
      },
      currentTrack: 0
    };

    this.onClickNext = this.onClickNext.bind(this);
    this.onClickPrev = this.onClickPrev.bind(this);
  }

  componentDidMount() {
      // fetch the data  from the Spotify API and update this.state.all_tracks.tracks

  }

  onClickNext() {
    //Next button
    this.setState(prevState => {
      if (this.state.currentTrack === this.state.all_tracks.tracks.length - 1) {
        return;
      }

      return {
        ...prevState,
        currentTrack: prevState.currentTrack + 1
      };
    });
  }
  onClickPrev() {
    //Previous button
    this.setState(prevState => {
      if (this.state.currentTrack === 0) {
        return;
      }

      return { ...prevState, currentTrack: prevState.currentTrack - 1 };
    });
  }
  render() {
    const {
      currentTrack,
      all_tracks: { tracks }
    } = this.state;

    // before rendering tracks[currentTrack].name check if tracks[currentTrack] exist

    return (
      <>
        <div>
          <h3>Current Track</h3>
          <h4>
           {
             tracks[currentTrack]
                ? tracks[currentTrack].name
                : 'track does not exist'
           }
          </h4>
        </div>
        <div>
          <button id="nextBtn" onClick={this.onClickNext}>
            Next
          </button>
        </div>
        <div>
          <button id="prevBtn" onClick={this.onClickPrev}>
            Previous
          </button>
        </div>
      </>
    );
  }
}

Check the codesandbox for demo


问:
Can't authenticate to Slack with passport-slack
I'm implementing "Slack authentication" with passport-slack. I only want to use incoming-webhook. I have set up 'incoming-webhook' but I got the error below:

Unapproved permissions requested
  incoming-webhook

The code:

```<code>const SlackStrategy = require('passport-slack').Strategy
passport.use(
  new SlackStrategy(
    {
      clientID: config.slack.client_id,
      clientSecret: config.slack.client_secret,
      scope: ['incoming-webhook'],
      skipUserProfile: true
    },
    (req, profile, done) => {
        // slack data
    }
   )
)

</code>```

答:
I needed to set up scope here.</p>

```<code>app.get('/auth/slack', (req, res, next) => {
  passport.authenticate('slack', { scope: 'incoming-webhook' })(req, res, next)
})
</code>```

Body:
I'm implementing "Slack authentication" with passport-slack. I only want to use incoming-webhook. I have set up 'incoming-webhook' but I got the error below:

Unapproved permissions requested
  incoming-webhook

The code:

const SlackStrategy = require('passport-slack').Strategy
passport.use(
  new SlackStrategy(
    {
      clientID: config.slack.client_id,
      clientSecret: config.slack.client_secret,
      scope: ['incoming-webhook'],
      skipUserProfile: true
    },
    (req, profile, done) => {
        // slack data
    }
   )
)

Body:
I needed to set up scope here.

app.get('/auth/slack', (req, res, next) => {
  passport.authenticate('slack', { scope: 'incoming-webhook' })(req, res, next)
})