问:
Different results with using curl vs python requests
I'm working on a python wrapper for Nozbe (GTD / Task organizer).
Per the documentation, this curl command works to create a task.

curl -i https://api.nozbe.com:3000/task?access_token=<ACCESS_TOKEN> -XPOST -d'name=some task'

The task created is "some task"

If I attempt the equivalent behavior using python requests , the task entry is created but instead of "some task" , it results in "some+task".

The initial python code looks like this:

```<code>url = 'https://api.nozbe.com:3000/task?access_token=<ACCESS_TOKEN>'
data = {"name":"some task"}
response = requests.post(url, data=data)
</code>```

I thought it might be a difference in the headers, so I ran the curl command with -vvv
and confirmed value passed as

Content-Type: application/x-www-form-urlencoded

if I replicate this in the python code as follows, it produces the same "some+task" entry.

```<code>url = 'https://api.nozbe.com:3000/task?access_token=<ACCESS_TOKEN>'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
data = {"name":"some task"}
response = requests.post(url, headers=headers, data=data)
</code>```

I'm at a loss for what I'm missing to consider with this.

答:
I believe the x-www-form-urlencoded is encoding the data, and that's the reason you are getting a + in place of a space.

Add ContentType as JSON:

```<code>headers = {'Content-Type': 'application/json'}
</code>```

And, your requests call should be

```<code>response = requests.post(url, headers=headers, data=json.dumps(data))
</code>```

Body:
I'm working on a python wrapper for Nozbe (GTD / Task organizer).
Per the documentation, this curl command works to create a task.

curl -i https://api.nozbe.com:3000/task?access_token=<ACCESS_TOKEN> -XPOST -d'name=some task'

The task created is "some task"

If I attempt the equivalent behavior using python requests , the task entry is created but instead of "some task" , it results in "some+task".

The initial python code looks like this:

url = 'https://api.nozbe.com:3000/task?access_token=<ACCESS_TOKEN>'
data = {"name":"some task"}
response = requests.post(url, data=data)

I thought it might be a difference in the headers, so I ran the curl command with -vvv
and confirmed value passed as

Content-Type: application/x-www-form-urlencoded

if I replicate this in the python code as follows, it produces the same "some+task" entry.

url = 'https://api.nozbe.com:3000/task?access_token=<ACCESS_TOKEN>'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
data = {"name":"some task"}
response = requests.post(url, headers=headers, data=data)

I'm at a loss for what I'm missing to consider with this.

Body:
I believe the x-www-form-urlencoded is encoding the data, and that's the reason you are getting a + in place of a space.

Add ContentType as JSON:

headers = {'Content-Type': 'application/json'}

And, your requests call should be

response = requests.post(url, headers=headers, data=json.dumps(data))


来源: stackexchange

问:
AWS ElasticBeanstalk update without modifing Django wsgi.conf
I have a django app deployed in AWS EB using autoscaling.
This app uses Django Rest with Token Authentication.
In order for this to work, I have to add the following lines in etc/httpd/conf.d/wsgi.conf file:

```<code>RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

WSGIPassAuthorization On
</code>```

The problem is: when AWS do an autoscale or ElasticBeanstalk environment upgrade, the wsgi.conf file is updated and the custom settings are deleted.

How can I avoid that?

Thanks in advance

答: This is not working i have tried all options nothing seems to work with ebs. I don't really know what else to try.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a django app deployed in AWS EB using autoscaling.
This app uses Django Rest with Token Authentication.
In order for this to work, I have to add the following lines in etc/httpd/conf.d/wsgi.conf file:

RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

WSGIPassAuthorization On

The problem is: when AWS do an autoscale or ElasticBeanstalk environment upgrade, the wsgi.conf file is updated and the custom settings are deleted.

How can I avoid that?

Thanks in advance

ContentLicense: CC BY-SA 4.0


问:
Twitter search : avoid keyword matching replied username
The body of a tweet reply is having a list of @username at the beginning.

When you search for a keyword, it can match a username in this list.

For example, searching keyword will match:

Tweet A :

This is an exemple tweet speaking about keyword

Tweet B : (a reply tweet)

@keyword Speaking about random topic

There is multiple solution to exclude tweet replies using -filter:replies or exclude:replies, but it will remove all replies. It won't be possible to match tweet like :

Tweet C :

@username Reply speaking about keyword

Is it possible to search a keyword only within tweet content, without matching to a name in front of a reply tweet ? Having a query to match only Tweet A and C.

答:
Try

```<code>[keyword] -from:[keyword] -@[keyword] -to:[keyword]
</code>```

Where [keyword] is, of course, any keyword you choose.

-from:[keyword] will exclude tweets from the @keyword user

-@[keyword] will exclude tweets mentioning the user @keyword

-to:[keyword] will exclude tweets replying to the user @keyword

Body:
Try

[keyword] -from:[keyword] -@[keyword] -to:[keyword]

Where [keyword] is, of course, any keyword you choose.

-from:[keyword] will exclude tweets from the @keyword user

-@[keyword] will exclude tweets mentioning the user @keyword

-to:[keyword] will exclude tweets replying to the user @keyword


问:
Spring - Sort Aggregation
I have an aggregation similar to this one:

```<code>public Flux<Example> listWithFilters (int pageNumber, int size , String sortField, String sort, String userName) {

    Criteria criteria = new Criteria();
    criteria = criteria.where("orgId").is(orgId).and("category").all(category);
    criteria = criteria.orOperator(Criteria.where(DELETED).isNull(), Criteria.where(DELETED).is(false));

    AggregationExpression condition = ConditionalOperators.when(ArrayOperators.arrayOf(ConditionalOperators
                    .ifNull("favourite").then(Collections.emptyList())).containsValue(userName))
            .then(true)
            .otherwise(false);

    Pageable pageableRequest = PageRequest.of(pageNumber, size);
    Aggregation aggregation = Aggregation.newAggregation(
            Aggregation.match(criteria),
            Aggregation.skip((long) (pageableRequest.getPageNumber() * pageableRequest.getPageSize())),
            Aggregation.limit(pageableRequest.getPageSize()),
            Aggregation.addFields().addField("isFav").withValue(condition).build());

    filterResponse.setListExample(
            mongo.aggregate(aggregation, mongo.getCollectionName(ExampleClass.class), ExampleClass.class).collectList().share().block()
    );
    return Flux.just(Example);
}
</code>```

I would like to be able to sort it with variable data (sortField and Sort), but I don't know how to add it to the aggregation. To get an idea I would like something like:

```<code>if(sort.equals("asc")){
Aggregation.sort(Sort.Direction.ASC, sortField));
}else{
Aggregation.sort(Sort.Direction.DESC, sortField));}
</code>```

Does anyone have any idea how to do it?

答:
Aggregation.newAggregation() can take a list of AggregationOperation.

You could do something like this :

```<code>    List<AggregationOperation> aggregationOperations = new ArrayList<>();
    aggregationOperations.add(Aggregation.match(criteria));
    aggregationOperations.add(Aggregation.skip((long) (pageableRequest.getPageNumber() * pageableRequest.getPageSize())));
    aggregationOperations.add(Aggregation.limit(pageableRequest.getPageSize()));
    aggregationOperations.add(Aggregation.limit(pageableRequest.getPageSize()));
    aggregationOperations.add(Aggregation.addFields().addField("isFav").withValue(condition).build());

    if (sort.equals("asc")) {
        aggregationOperations.add(Aggregation.sort(Sort.Direction.ASC, sortField));
    }else{
        aggregationOperations.add(Aggregation.sort(Sort.Direction.DESC, sortField));
    }

    Aggregation aggregation = Aggregation.newAggregation(aggregationOperations);
    filterResponse.setListExample(
            mongo.aggregate(aggregation, mongo.getCollectionName(ExampleClass.class), ExampleClass.class).collectList().share().block()
    );
</code>```

Title: Spring - Sort Aggregation

Body:
I have an aggregation similar to this one:

public Flux<Example> listWithFilters (int pageNumber, int size , String sortField, String sort, String userName) {

    Criteria criteria = new Criteria();
    criteria = criteria.where("orgId").is(orgId).and("category").all(category);
    criteria = criteria.orOperator(Criteria.where(DELETED).isNull(), Criteria.where(DELETED).is(false));

    AggregationExpression condition = ConditionalOperators.when(ArrayOperators.arrayOf(ConditionalOperators
                    .ifNull("favourite").then(Collections.emptyList())).containsValue(userName))
            .then(true)
            .otherwise(false);

    Pageable pageableRequest = PageRequest.of(pageNumber, size);
    Aggregation aggregation = Aggregation.newAggregation(
            Aggregation.match(criteria),
            Aggregation.skip((long) (pageableRequest.getPageNumber() * pageableRequest.getPageSize())),
            Aggregation.limit(pageableRequest.getPageSize()),
            Aggregation.addFields().addField("isFav").withValue(condition).build());

    filterResponse.setListExample(
            mongo.aggregate(aggregation, mongo.getCollectionName(ExampleClass.class), ExampleClass.class).collectList().share().block()
    );
    return Flux.just(Example);
}

I would like to be able to sort it with variable data (sortField and Sort), but I don't know how to add it to the aggregation. To get an idea I would like something like:

if(sort.equals("asc")){
Aggregation.sort(Sort.Direction.ASC, sortField));
}else{
Aggregation.sort(Sort.Direction.DESC, sortField));}

Does anyone have any idea how to do it?

Body:
Aggregation.newAggregation() can take a list of AggregationOperation.

You could do something like this :

    List<AggregationOperation> aggregationOperations = new ArrayList<>();
    aggregationOperations.add(Aggregation.match(criteria));
    aggregationOperations.add(Aggregation.skip((long) (pageableRequest.getPageNumber() * pageableRequest.getPageSize())));
    aggregationOperations.add(Aggregation.limit(pageableRequest.getPageSize()));
    aggregationOperations.add(Aggregation.limit(pageableRequest.getPageSize()));
    aggregationOperations.add(Aggregation.addFields().addField("isFav").withValue(condition).build());

    if (sort.equals("asc")) {
        aggregationOperations.add(Aggregation.sort(Sort.Direction.ASC, sortField));
    }else{
        aggregationOperations.add(Aggregation.sort(Sort.Direction.DESC, sortField));
    }

    Aggregation aggregation = Aggregation.newAggregation(aggregationOperations);
    filterResponse.setListExample(
            mongo.aggregate(aggregation, mongo.getCollectionName(ExampleClass.class), ExampleClass.class).collectList().share().block()
    );


问:
Wordpress user login causes all plugins to fail
When users register and log in to my wordpress site, it seems that users with the .nl (Netherlands) email address (being used as the username) somehow causes none of the plugins to trip.

I put some debugging around two of them on a particular page, and although the sidebar initiates and makes room for the plugins, the sidebar contents are empty (both visually and in the DOM).

I have tested other email extensions, .com, .net, .ca, .cz, .it, and .au and all of them work normally. But all of my email tests ending in .nl are causing this issue.

Any insight would be appreciated.

Wordpress 3.2.1 (latest)

答:
Is your login page customized? have you tried changing the theme?

There some good advice on the below page which you might find useful, if you haven't already checked it yet.

http://codex.wordpress.org/Login_Trouble

The one i'm referring to in particular is on New Login File section inside the above link: http://codex.wordpress.org/Login_Trouble#New_Login_File

Also something that you might find helpful:
http://wordpress.org/support/topic/allowing-registration-with-the-email-as-username

P.S:- I'm starting to believe wordpress wasn't meant to allow any user to register with such usernames by default 'email@domain.com'. What i've seen is people mostly use plugins to do this, and also as far i've researched about this topic - it is considered a bad idea to implement it.

Wordpress Plugin: http://wordpress.org/extend/plugins/wp-email-login/


问:
Printing list elements on separate lines in Python
I am trying to print out Python path folders using this:

```<code>import sys
print sys.path
</code>```

The output is like this:

```<code>>>> print sys.path
['.', '/usr/bin', '/home/student/Desktop', '/home/student/my_modules', '/usr/lib/pyth
on2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/pyth
on2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/local/lib/python2.6/dist-pack
ages', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/
usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/pymodules/python2.6', '/usr/lib/
python2.6/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.6/gtk-2.0', '/usr/lib/p
ython2.6/dist-packages/wx-2.8-gtk2-unicode']
</code>```

How do I print them into separate lines so I can parse them properly?

It should be like this:

```<code>/usr/bin
/home/student/Desktop
/home/student/my_modules
etc
</code>```

答:
For printing list elements on separate lines, you can use:</p>
```<code>files = ['test1.txt', 'test2.txt', 'test3.txt']
for i in range(len(files)): print(files[i])
</code>```

Body:
I am trying to print out Python path folders using this:

import sys
print sys.path

The output is like this:

>>> print sys.path
['.', '/usr/bin', '/home/student/Desktop', '/home/student/my_modules', '/usr/lib/pyth
on2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/pyth
on2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/local/lib/python2.6/dist-pack
ages', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/
usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/pymodules/python2.6', '/usr/lib/
python2.6/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.6/gtk-2.0', '/usr/lib/p
ython2.6/dist-packages/wx-2.8-gtk2-unicode']

How do I print them into separate lines so I can parse them properly?

It should be like this:

/usr/bin
/home/student/Desktop
/home/student/my_modules
etc

Body:
For printing list elements on separate lines, you can use:

files = ['test1.txt', 'test2.txt', 'test3.txt']
for i in range(len(files)): print(files[i])


问:
Is there a way to extend multiple templates with resources in Azure DevOps?
I have one pipeline that is referencing several templates with resources and I know you can extend a template with resources by using the extend keyword. I've been looking at this documentation trying to make it work.

azure-pipeline.yaml

```<code>trigger: none

resources:
  repositories:
    - repository: repoName
      type: git
      name: project/repoName
    - repository: 'Release Notes'
      name: 'project/Release Notes'
      type: git
  pipelines:
    - pipeline: ooi-adf-ci
      source: ooi-adf-ci

extends:
  - {template: '/cicd/pipelines/templates/stages-deploy-app-registration.yaml'}
  - {template: '/cicd/pipelines/templates/stages-set-app-credentials.yaml'}
  - {template: '/cicd/pipelines/templates/stages-buying-release-apps.yaml'}
  - {template: '/cicd/pipelines/templates/stages-buying-adf.yaml'}
</code>```

I also tried something like:

```<code>extends:
  template:
    [
      '/cicd/pipelines/templates/stages-deploy-app-registration.yaml',
      '/cicd/pipelines/templates/stages-set-app-credentials.yaml',
      '/cicd/pipelines/templates/stages-buying-release-apps.yaml',
      '/cicd/pipelines/templates/stages-buying-adf.yaml',
    ]
</code>```

template.yaml where the resource is consumed:

```<code>...
resources:
  pipelines:
    - pipeline: ooi-adf-ci
      source: ooi-adf-ci
...
</code>```

I get an error in my azure-pipeline.yaml file saying "A sequence was not expected". I'm wondering if this is actually possible as I haven't been able to find any documentation on it or if I'm just incorrectly doing it.

答:
I dont think you can infinitely extend templates at the root level, as in your example.

What you can do is compose a azure-pipeline.yaml file where each job / step is from a template. I do this a lot and works perfectly.

Here is the official docs:
enter link description here

Body:
I have one pipeline that is referencing several templates with resources and I know you can extend a template with resources by using the extend keyword. I've been looking at this documentation trying to make it work.

azure-pipeline.yaml

trigger: none

resources:
  repositories:
    - repository: repoName
      type: git
      name: project/repoName
    - repository: 'Release Notes'
      name: 'project/Release Notes'
      type: git
  pipelines:
    - pipeline: ooi-adf-ci
      source: ooi-adf-ci

extends:
  - {template: '/cicd/pipelines/templates/stages-deploy-app-registration.yaml'}
  - {template: '/cicd/pipelines/templates/stages-set-app-credentials.yaml'}
  - {template: '/cicd/pipelines/templates/stages-buying-release-apps.yaml'}
  - {template: '/cicd/pipelines/templates/stages-buying-adf.yaml'}

I also tried something like:

extends:
  template:
    [
      '/cicd/pipelines/templates/stages-deploy-app-registration.yaml',
      '/cicd/pipelines/templates/stages-set-app-credentials.yaml',
      '/cicd/pipelines/templates/stages-buying-release-apps.yaml',
      '/cicd/pipelines/templates/stages-buying-adf.yaml',
    ]

template.yaml where the resource is consumed:

...
resources:
  pipelines:
    - pipeline: ooi-adf-ci
      source: ooi-adf-ci
...

I get an error in my azure-pipeline.yaml file saying "A sequence was not expected". I'm wondering if this is actually possible as I haven't been able to find any documentation on it or if I'm just incorrectly doing it.


问:
How to add multiple http request calls in foreach | Mule 3
I am using scatter-gather to call many endpoints with the same host and  different paths. How can I add the HTTP request connector inside For Each scope, that can loop into the different paths and add the payload to the same file?

My code is as below, I would like to loop over the HTTP request;

```<code><?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:tracking="http://www.mulesoft.org/schema/mule/ee/tracking" xmlns:ftp="http://www.mulesoft.org/schema/mule/ee/ftp" xmlns:http="http://www.mulesoft.org/schema/mule/http"
    xmlns:file="http://www.mulesoft.org/schema/mule/file" xmlns:dw="http://www.mulesoft.org/schema/mule/ee/dw"
    xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
    xmlns:spring="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd
http://www.mulesoft.org/schema/mule/ee/dw http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/ee/ftp http://www.mulesoft.org/schema/mule/ee/ftp/current/mule-ftp-ee.xsd
http://www.mulesoft.org/schema/mule/ee/tracking http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd">
    <http:request-config name="HTTP_Request_Configuration-testt" protocol="HTTPS" host="servicenow.com" port="443" doc:name="HTTP Request Configuration"/>
    <http:listener-config name="HTTP_Listener_Configuration1" host="0.0.0.0" port="8081" doc:name="HTTP Listener Configuration"/>
    <flow name="servicenow-call">
        <http:listener config-ref="HTTP_Listener_Configuration1" path="/test" doc:name="HTTP"/>
        <scatter-gather doc:name="Scatter-Gather">
            <http:request config-ref="HTTP_Request_Configuration-testt" path="/repo/cat1" method="GET" doc:name="HTTP Request 1"/>
            <http:request config-ref="HTTP_Request_Configuration-testt" path="/repo/cat2" method="GET" doc:name="HTTP Request 2"/>
            <http:request config-ref="HTTP_Request_Configuration-testt" path="/repo/cat3"" method="GET" doc:name="HTTP Request 4"/>

        </scatter-gather>
        <dw:transform-message doc:name="Set JSON">
            <dw:set-payload><![CDATA[%dw 1.0
%output application/json
---
payload]]></dw:set-payload>
        </dw:transform-message>
        <file:outbound-endpoint path="D:\Local\NewFile.json" outputPattern="first-#[function:datestamp:ddMMyyyy-HHmmss].json" responseTimeout="10000" doc:name="Write FIle"/>
        <exception-strategy ref="ImplementationChoice_Exception_Strategy" doc:name="Reference Exception Strategy"/>
    </flow>
</mule>
</code>```

答: Set a variable with an empty list before the foreach, and for each iteration concatenate the results. I guess you can set a list of the paths and use it to iterate the foreach.</p>

Body:
I am using scatter-gather to call many endpoints with the same host and  different paths. How can I add the HTTP request connector inside For Each scope, that can loop into the different paths and add the payload to the same file?

My code is as below, I would like to loop over the HTTP request;

<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:tracking="http://www.mulesoft.org/schema/mule/ee/tracking" xmlns:ftp="http://www.mulesoft.org/schema/mule/ee/ftp" xmlns:http="http://www.mulesoft.org/schema/mule/http"
    xmlns:file="http://www.mulesoft.org/schema/mule/file" xmlns:dw="http://www.mulesoft.org/schema/mule/ee/dw"
    xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
    xmlns:spring="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd
http://www.mulesoft.org/schema/mule/ee/dw http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/ee/ftp http://www.mulesoft.org/schema/mule/ee/ftp/current/mule-ftp-ee.xsd
http://www.mulesoft.org/schema/mule/ee/tracking http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd">
    <http:request-config name="HTTP_Request_Configuration-testt" protocol="HTTPS" host="servicenow.com" port="443" doc:name="HTTP Request Configuration"/>
    <http:listener-config name="HTTP_Listener_Configuration1" host="0.0.0.0" port="8081" doc:name="HTTP Listener Configuration"/>
    <flow name="servicenow-call">
        <http:listener config-ref="HTTP_Listener_Configuration1" path="/test" doc:name="HTTP"/>
        <scatter-gather doc:name="Scatter-Gather">
            <http:request config-ref="HTTP_Request_Configuration-testt" path="/repo/cat1" method="GET" doc:name="HTTP Request 1"/>
            <http:request config-ref="HTTP_Request_Configuration-testt" path="/repo/cat2" method="GET" doc:name="HTTP Request 2"/>
            <http:request config-ref="HTTP_Request_Configuration-testt" path="/repo/cat3"" method="GET" doc:name="HTTP Request 4"/>

        </scatter-gather>
        <dw:transform-message doc:name="Set JSON">
            <dw:set-payload><![CDATA[%dw 1.0
%output application/json
---
payload]]></dw:set-payload>
        </dw:transform-message>
        <file:outbound-endpoint path="D:\Local\NewFile.json" outputPattern="first-#[function:datestamp:ddMMyyyy-HHmmss].json" responseTimeout="10000" doc:name="Write FIle"/>
        <exception-strategy ref="ImplementationChoice_Exception_Strategy" doc:name="Reference Exception Strategy"/>
    </flow>
</mule>


问:
Spring Boot API Post Mapping to read in Array
I currently have an API that has this payload (from a react-select using isMulti):

```<code> {
    "college_school_code": [
        {
            "label": "College Name - College Address",
            "value": "1234"
        },
        {
            "label": "College Name - College Address",
            "value": "5678"
        }
    ],
    "userid": "email@email.com"
}
</code>```

I need to read that API in, and write the userid and value of each college_school_codes to a database (so this call would write out two rows, both with the same userid, but different college_school_codes).

Here's some more code that clearly doesn't work.  It should looks to see if there's any current rows for the user, remove those, then add the new rows:

{ @Entity
public class CollegeSchoolCode {

```<code>@Id
private String label;
private String value;

public String getLabel() {
    return label;
}

public void setLabel(String label) {
    this.label = label;
}

public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}
</code>```

}
}

```<code>@Entity
</code>```

public class CollegeSchoolCode {

```<code>@Id
private String label;
private String value;

public String getLabel() {
    return label;
}

public void setLabel(String label) {
    this.label = label;
}

public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}
</code>```

}

```<code> public void insertColleges(@RequestBody CollegesInfo newCollegesInfo, CollegeSchoolCode newCollegeSchoolCode){

    String userid = newCollegesInfo.getUserid();
    List college_school_code  = newCollegesInfo.getCollege_school_code();

    System.out.println("colleges="+college_school_code);

    int rowCount = insertCollegesRepository.getRowCount(userid);

    if (rowCount > 0){
        insertCollegesRepository.deleteColleges(userid);
    }

    for (int i = 0; i < college_school_code.size(); i++) {
        String value = newCollegeSchoolCode.getValue();
        insertCollegesRepository.insertColleges(userid, value);
    }
}
</code>```

At this point, the app is stepping through my college_school_code list and inserting into the database as expected, but the value for the school code is always null, so there's a disconnect there somewhere that I cannot figure out.

Thanks for any help!

答:
Well, I figured it out, and it was a simple one!  I updated the value string to:

```<code>String value = college_school_code.get(i).getValue();
</code>```

I didn't actually need to add the newCollegeSchoolCode piece like I though, it's always the simple solutions.

Body:
I currently have an API that has this payload (from a react-select using isMulti):

 {
    "college_school_code": [
        {
            "label": "College Name - College Address",
            "value": "1234"
        },
        {
            "label": "College Name - College Address",
            "value": "5678"
        }
    ],
    "userid": "email@email.com"
}

I need to read that API in, and write the userid and value of each college_school_codes to a database (so this call would write out two rows, both with the same userid, but different college_school_codes).

Here's some more code that clearly doesn't work.  It should looks to see if there's any current rows for the user, remove those, then add the new rows:

{ @Entity
public class CollegeSchoolCode {

@Id
private String label;
private String value;

public String getLabel() {
    return label;
}

public void setLabel(String label) {
    this.label = label;
}

public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}

}
}

@Entity

public class CollegeSchoolCode {

@Id
private String label;
private String value;

public String getLabel() {
    return label;
}

public void setLabel(String label) {
    this.label = label;
}

public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}

}

 public void insertColleges(@RequestBody CollegesInfo newCollegesInfo, CollegeSchoolCode newCollegeSchoolCode){

    String userid = newCollegesInfo.getUserid();
    List college_school_code  = newCollegesInfo.getCollege_school_code();

    System.out.println("colleges="+college_school_code);

    int rowCount = insertCollegesRepository.getRowCount(userid);

    if (rowCount > 0){
        insertCollegesRepository.deleteColleges(userid);
    }

    for (int i = 0; i < college_school_code.size(); i++) {
        String value = newCollegeSchoolCode.getValue();
        insertCollegesRepository.insertColleges(userid, value);
    }
}

At this point, the app is stepping through my college_school_code list and inserting into the database as expected, but the value for the school code is always null, so there's a disconnect there somewhere that I cannot figure out.

Thanks for any help!

Body:
Well, I figured it out, and it was a simple one!  I updated the value string to:

String value = college_school_code.get(i).getValue();

I didn't actually need to add the newCollegeSchoolCode piece like I though, it's always the simple solutions.


问:
MySQL dump file has some issue with foreign key constraint. referenced column '**' in foreign key constraint '**' are incompatible
I would like to import SQL dump file, some how it's not working.
I got this error when I try to import data.</p>
```<code>Referencing column 'originator_id' and referenced column 'name' in foreign key constraint 'fk_rails_79d8c4ccda' are incompatible.
</code>```
```<code>DROP TABLE IF EXISTS `loan_fee_shares`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `loan_fee_shares` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `originator_id` varchar(255) DEFAULT NULL,
  `percent` decimal(6,2) DEFAULT NULL COMMENT 'belongs to [0,1] set',
  `active` tinyint(1) DEFAULT '0',
  `deactivated_at` timestamp NULL DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_rails_79d8c4ccda` (`originator_id`),
  CONSTRAINT `fk_rails_79d8c4ccda` FOREIGN KEY (`originator_id`) REFERENCES `originators` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

DROP TABLE IF EXISTS `originators`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `originators` (
  `name` varchar(255) DEFAULT NULL,
  `description` varchar(100) DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`name`),
  UNIQUE KEY `index_originators_on_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
</code>```

答:
I am posting this for someone who might have the same issue in the future.

Barmar has a good point. and I moved originators table to before loan_fee_shares. But I still had an issue.

and It had an issue with DEFAULT CHARSET=latin1, I had to change it to DEFAULT CHARSET=utf8. and It works.

I suggest that change all your tables to the same character set.

How to change all the tables in my database to UTF8 character set?

Body:
I would like to import SQL dump file, some how it's not working.
I got this error when I try to import data.

Referencing column 'originator_id' and referenced column 'name' in foreign key constraint 'fk_rails_79d8c4ccda' are incompatible.

DROP TABLE IF EXISTS `loan_fee_shares`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `loan_fee_shares` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `originator_id` varchar(255) DEFAULT NULL,
  `percent` decimal(6,2) DEFAULT NULL COMMENT 'belongs to [0,1] set',
  `active` tinyint(1) DEFAULT '0',
  `deactivated_at` timestamp NULL DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_rails_79d8c4ccda` (`originator_id`),
  CONSTRAINT `fk_rails_79d8c4ccda` FOREIGN KEY (`originator_id`) REFERENCES `originators` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

DROP TABLE IF EXISTS `originators`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `originators` (
  `name` varchar(255) DEFAULT NULL,
  `description` varchar(100) DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`name`),
  UNIQUE KEY `index_originators_on_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;


问:
Error: Expected undefined to be a GraphQL schema
I am getting an error which says " Error: Expected undefined to be a GraphQL schema." Please check what issue is this
when I move to localhost:3000/graphiql it shows the above error.
Maybe i am doing some mistake please anyone check and help me if possible.

My Server.js

```<code>const express = require ('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

//importing the Schema
const Story = require('./models/Story');
const User = require('./models/Story');

//Bring in GraphQl-Express middleware
const { graphiqlExpress, graphqlExpress } = require('apollo-server-express');
const { makeExecutableSchema } = require('graphql-tools');

const { resolvers } = require('./resolvers');
const { typeDefs } = require('./schema');

//create schema
const Schema = makeExecutableSchema({
    typeDefs,
    resolvers
})

require('dotenv').config({ path: 'variables.env' });
// connecting mongoose to database
mongoose
.connect(process.env.MONGO_URI)
.then(()=> console.log('DB Connected'))
.catch(err => console.log(err));

//initializing express
const app = express();

//create GraphiQl application
app.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql'}))

//connect schemas with GraphQl
app.use('/graphql',bodyParser.json(), graphqlExpress({
    Schema,
    context:{
        Story,
        User
    }
}))

const PORT = process.env.PORT || 3000;

app.listen(PORT, ()=> {
    console.log(`Server Running on PORT ${PORT}`);
})
</code>```

my Schema.js

```<code>exports.typeDefs = `

type Story {
    name: String!
    category: String!
    description: String!
    instructions: String!
    createDate: String
    likes: Int
    username: String
}

type User {
    username: String! @unique
    password: String!
    email: String!
    joinDate: String
    favorites: [Story]
}

type Query {
    getAllStories: [Story]
}

`;
</code>```

My Resolvers.js

```<code>exports.resolvers= {

    Query:{
        getAllStories: ()=> {}
    }

};
</code>```

My Story.js

```<code>const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const StorySchema = new Schema({
    name: {
        type: String,
        required:true,
    },
    category:{
        type:String,
        required:true
    },
    description:{
        type:String,
        required:true
    },
    instructions:{
        type:String,
        required:true
    },
    createdDate:{
        type:Date,
        default: Date.now
    },
    likes:{
        type:Number,
        default:0
    },
    username:{
        type:String
    }

})

module.exports = mongoose.model('Story', StorySchema );
</code>```

My User.js

```<code>const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const UserSchema = new Schema({
    username:{
        type:String,
        required:true,
        unique:true
    },
    password:{
        type:String,
        required:true
    },
    email:{
        type:String,
        required:true
    },
    joinDate:{
        type:Date,
        default:Date.now
    },
    favorites:{
        type:[Schema.Types.ObjectId],
        refs:'Story'
    }
})

module.exports = mongoose.model('User', UserSchema);
</code>```

答:
I faced this with latest version of graphql and @nestjs/graphql :"9.1.2" version.

Downgraded the version to 15.8.0 and it's started working.

npm i graphql@15.8.0

Body:
I am getting an error which says " Error: Expected undefined to be a GraphQL schema." Please check what issue is this
when I move to localhost:3000/graphiql it shows the above error.
Maybe i am doing some mistake please anyone check and help me if possible.

My Server.js

const express = require ('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

//importing the Schema
const Story = require('./models/Story');
const User = require('./models/Story');

//Bring in GraphQl-Express middleware
const { graphiqlExpress, graphqlExpress } = require('apollo-server-express');
const { makeExecutableSchema } = require('graphql-tools');

const { resolvers } = require('./resolvers');
const { typeDefs } = require('./schema');

//create schema
const Schema = makeExecutableSchema({
    typeDefs,
    resolvers
})

require('dotenv').config({ path: 'variables.env' });
// connecting mongoose to database
mongoose
.connect(process.env.MONGO_URI)
.then(()=> console.log('DB Connected'))
.catch(err => console.log(err));

//initializing express
const app = express();

//create GraphiQl application
app.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql'}))

//connect schemas with GraphQl
app.use('/graphql',bodyParser.json(), graphqlExpress({
    Schema,
    context:{
        Story,
        User
    }
}))

const PORT = process.env.PORT || 3000;

app.listen(PORT, ()=> {
    console.log(`Server Running on PORT ${PORT}`);
})

my Schema.js

exports.typeDefs = `

type Story {
    name: String!
    category: String!
    description: String!
    instructions: String!
    createDate: String
    likes: Int
    username: String
}

type User {
    username: String! @unique
    password: String!
    email: String!
    joinDate: String
    favorites: [Story]
}

type Query {
    getAllStories: [Story]
}

`;

My Resolvers.js

exports.resolvers= {

    Query:{
        getAllStories: ()=> {}
    }

};

My Story.js

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const StorySchema = new Schema({
    name: {
        type: String,
        required:true,
    },
    category:{
        type:String,
        required:true
    },
    description:{
        type:String,
        required:true
    },
    instructions:{
        type:String,
        required:true
    },
    createdDate:{
        type:Date,
        default: Date.now
    },
    likes:{
        type:Number,
        default:0
    },
    username:{
        type:String
    }

})

module.exports = mongoose.model('Story', StorySchema );

My User.js

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const UserSchema = new Schema({
    username:{
        type:String,
        required:true,
        unique:true
    },
    password:{
        type:String,
        required:true
    },
    email:{
        type:String,
        required:true
    },
    joinDate:{
        type:Date,
        default:Date.now
    },
    favorites:{
        type:[Schema.Types.ObjectId],
        refs:'Story'
    }
})

module.exports = mongoose.model('User', UserSchema);


问:
Optional parameters, "index seek" plan
In my SELECT statement i use optional parameters in a way like this:

```<code>DECLARE @p1 INT = 1
DECLARE @p2 INT = 1
SELECT name FROM some_table WHERE (id = @p1 OR @p1 IS NULL) AND (name = @p2 OR @p2 IS NULL)
</code>```

In this case the optimizer generates "index scan" (not seek) operations for the entity which is not most effective when parameters are supplied with not null values.

If i add the RECOMPILE hint to the query the optimizer builds more effective plan which uses "seek". It works on my MSSQL 2008 R2 SP1 server and it also means that the optimizer CAN build a plan which consider only one logic branch of my query.

How can i make it to use that plan everywhere i want with no recompiling? The USE PLAN hint seemes not to work in this case.

Below is test code:

```<code>-- see plans
CREATE TABLE test_table(
    id INT IDENTITY(1,1) NOT NULL,
    name varchar(10),
    CONSTRAINT [pk_test_table] PRIMARY KEY CLUSTERED (id ASC))
GO
INSERT INTO test_table(name) VALUES ('a'),('b'),('c')
GO
DECLARE @p INT = 1
SELECT name FROM test_table WHERE id = @p OR @p IS NULL
SELECT name FROM test_table WHERE id = @p OR @p IS NULL OPTION(RECOMPILE)
GO
DROP TABLE test_table
GO
</code>```

Note that not all versions of SQL server will change the plan the way i shown.

答:
Response to Comment on Andreas' Answer

The problem is that you need two different plans.

If @p1 = 1 then you can use a SEEK on the index.

If @p1 IS NULL, however, it is not a seek, by definition it's a SCAN.

This means that when the optimiser is generating a plan Prior to knowledge of the parameters, it needs to create a plan that can fullfil all possibilities.  Only a Scan can cover the needs of Both @p1 = 1 And @p1 IS NULL.

It also means that if the plan is recompiled at the time when the parameters are known, and @p1 = 1, a SEEK plan can be created.

This is the reason that, as you mention in your comment, IF statements resolve your problem; Each IF block represents a different portion of the problem space, and each can be given a different execution plan.

Title: Optional parameters, "index seek" plan

Body:
In my SELECT statement i use optional parameters in a way like this:

DECLARE @p1 INT = 1
DECLARE @p2 INT = 1
SELECT name FROM some_table WHERE (id = @p1 OR @p1 IS NULL) AND (name = @p2 OR @p2 IS NULL)

In this case the optimizer generates "index scan" (not seek) operations for the entity which is not most effective when parameters are supplied with not null values.

If i add the RECOMPILE hint to the query the optimizer builds more effective plan which uses "seek". It works on my MSSQL 2008 R2 SP1 server and it also means that the optimizer CAN build a plan which consider only one logic branch of my query.

How can i make it to use that plan everywhere i want with no recompiling? The USE PLAN hint seemes not to work in this case.

Below is test code:

-- see plans
CREATE TABLE test_table(
    id INT IDENTITY(1,1) NOT NULL,
    name varchar(10),
    CONSTRAINT [pk_test_table] PRIMARY KEY CLUSTERED (id ASC))
GO
INSERT INTO test_table(name) VALUES ('a'),('b'),('c')
GO
DECLARE @p INT = 1
SELECT name FROM test_table WHERE id = @p OR @p IS NULL
SELECT name FROM test_table WHERE id = @p OR @p IS NULL OPTION(RECOMPILE)
GO
DROP TABLE test_table
GO

Note that not all versions of SQL server will change the plan the way i shown.


问:
how to use enter key after cell edit in DataGridView c#
im trying to go next cell in datagridview after typing in the cell but it go to next row in same Column
** if not typing any thing in cell it working fine
how can solve that</p>
```<code>private void dgvacc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {

                int row = dgvacc.CurrentCell.RowIndex;
                int col = dgvacc.CurrentCell.ColumnIndex;

                try
                {
                    if (col < dgvacc.Columns.Count - 1)
                    {
                        dgvacc.CurrentCell = dgvacc.Rows[row -1].Cells[col + 1];
                        dgvacc.Focus();
                    }
                    else if (col == dgvacc.Columns.Count - 1)
                    {

                        dgvacc.CurrentCell = dgvacc.Rows[row].Cells[0];
                        dgvacc.Focus();
                    }
                }
                catch (Exception)
                {

                }
            }

        }

</code>```

答:
Option 1

Override the Form's ProcessCmdKey to trap the Keys.Enter presses and select the next cell IF the gird is focused OR the DataGridView.EditingControl property is not null/Nothing.

public partial class YourForm : Form
{
    public YourForm()
    {
        InitializeComponent();
    }

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if ((dataGridView1.Focused || dataGridView1.EditingControl != null)
            && keyData == Keys.Enter)
        {
            SelectNextCell();
            return true;
        }
        else
            return base.ProcessCmdKey(ref msg, keyData);
    }

    private void SelectNextCell()
    {
        var col = dataGridView1.CurrentCell.ColumnIndex;
        var row = dataGridView1.CurrentCell.RowIndex;

        if (col < dataGridView1.ColumnCount - 1) col++;
        else
        {
            col = 0;
            row++;
        }

        // Optional, select the first cell if the current cell is the last one.
        // You can return; here instead or add new row.
        if (row == dataGridView1.RowCount) row = 0;

        dataGridView1.CurrentCell = dataGridView1[col, row];
    }
}
```
<p><strong>Option 2</strong></p>
<p>Derive a new class from <code>DataGridView</code> and do the same except the <em>focus</em> and <em>EditingControl</em> checks:</p>
<pre class="lang-cs prettyprint-override"><code>[DesignerCategory("Code")]
public class DataGridViewEx : DataGridView
{
    public DataGridViewEx() : base() { }

    // Optional to enable/disable this feature...
    public bool SelectNextCellOnEnter { get; set; } = true;

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (SelectNextCellOnEnter && keyData == Keys.Enter)
        {
            SelectNextCell();
            return true;
        }
        else
        {
            return base.ProcessCmdKey(ref msg, keyData);
        }
    }

    private void SelectNextCell()
    {
        var col = CurrentCell.ColumnIndex;
        var row = CurrentCell.RowIndex;

        if (col < ColumnCount - 1) col++;
        else
        {
            col = 0;
            row++;
        }

        if (row == RowCount) row = 0;

        CurrentCell = this[col, row];
    }
}
</code>```

Body:
im trying to go next cell in datagridview after typing in the cell but it go to next row in same Column
** if not typing any thing in cell it working fine
how can solve that

private void dgvacc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {

                int row = dgvacc.CurrentCell.RowIndex;
                int col = dgvacc.CurrentCell.ColumnIndex;

                try
                {
                    if (col < dgvacc.Columns.Count - 1)
                    {
                        dgvacc.CurrentCell = dgvacc.Rows[row -1].Cells[col + 1];
                        dgvacc.Focus();
                    }
                    else if (col == dgvacc.Columns.Count - 1)
                    {

                        dgvacc.CurrentCell = dgvacc.Rows[row].Cells[0];
                        dgvacc.Focus();
                    }
                }
                catch (Exception)
                {

                }
            }

        }

Body:
Option 1

Override the Form's ProcessCmdKey to trap the Keys.Enter presses and select the next cell IF the gird is focused OR the DataGridView.EditingControl property is not null/Nothing.

public partial class YourForm : Form
{
    public YourForm()
    {
        InitializeComponent();
    }

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if ((dataGridView1.Focused || dataGridView1.EditingControl != null)
            && keyData == Keys.Enter)
        {
            SelectNextCell();
            return true;
        }
        else
            return base.ProcessCmdKey(ref msg, keyData);
    }

    private void SelectNextCell()
    {
        var col = dataGridView1.CurrentCell.ColumnIndex;
        var row = dataGridView1.CurrentCell.RowIndex;

        if (col < dataGridView1.ColumnCount - 1) col++;
        else
        {
            col = 0;
            row++;
        }

        // Optional, select the first cell if the current cell is the last one.
        // You can return; here instead or add new row.
        if (row == dataGridView1.RowCount) row = 0;

        dataGridView1.CurrentCell = dataGridView1[col, row];
    }
}

Option 2

Derive a new class from DataGridView and do the same except the focus and EditingControl checks:

[DesignerCategory("Code")]
public class DataGridViewEx : DataGridView
{
    public DataGridViewEx() : base() { }

    // Optional to enable/disable this feature...
    public bool SelectNextCellOnEnter { get; set; } = true;

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (SelectNextCellOnEnter && keyData == Keys.Enter)
        {
            SelectNextCell();
            return true;
        }
        else
        {
            return base.ProcessCmdKey(ref msg, keyData);
        }
    }

    private void SelectNextCell()
    {
        var col = CurrentCell.ColumnIndex;
        var row = CurrentCell.RowIndex;

        if (col < ColumnCount - 1) col++;
        else
        {
            col = 0;
            row++;
        }

        if (row == RowCount) row = 0;

        CurrentCell = this[col, row];
    }
}


问:
Count unique register in numpy array
I have a numpy array with letters "a", "b" or "c",

```<code>import numpy as np

my_array = np.array(["a", "a", "c", "c", "a"]) # In this example "b" is not present

</code>```

I want to fuild a function f that counts the unique records of each letter present in the array, for my example f should respond [3, 0, 2] meaning that "a" has appeared 3 times, "b" 0 times and "c" 2 times.

I'm looking for solution (if it possible) that use numpy functions and not explicit for loops over the array. Maybe a kind of group by

答:
If my_array has a typical length of about 10 or more, it can be worthwhile to convert your array to the integers [0, 1, 2] and then apply bincount().

Here's an example with your my_array:

```<code>In [31]: my_array = np.array(["a", "a", "c", "c", "a"])

In [32]: b = my_array.view(np.int32) - ord('a')

In [33]: b
Out[33]: array([0, 0, 2, 2, 0], dtype=int32)

In [34]: np.bincount(b, minlength=3)
Out[34]: array([3, 0, 2])
</code>```

Here's a timing comparison of that method and collections.Counter using an input with length 100:

```<code>In [34]: rng = np.random.default_rng()

In [35]: a = rng.choice(['a', 'a', 'b', 'c'], size=100)

In [36]: %timeit Counter(a)
32.1 µs ± 723 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [37]: %timeit b = a.view(np.int32) - ord('a'); np.bincount(b, minlength=3)
3.86 µs ± 50.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

The approach with bincount() is much faster.

It is also faster than using np.unique() with the parameter return_counts=True:

```<code>In [41]: %timeit values, counts = np.unique(a, return_counts=True)
19.7 µs ± 274 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

Title: Count unique register in numpy array

Body:
I have a numpy array with letters "a", "b" or "c",

import numpy as np

my_array = np.array(["a", "a", "c", "c", "a"]) # In this example "b" is not present

I want to fuild a function f that counts the unique records of each letter present in the array, for my example f should respond [3, 0, 2] meaning that "a" has appeared 3 times, "b" 0 times and "c" 2 times.

I'm looking for solution (if it possible) that use numpy functions and not explicit for loops over the array. Maybe a kind of group by

Body:
If my_array has a typical length of about 10 or more, it can be worthwhile to convert your array to the integers [0, 1, 2] and then apply bincount().

Here's an example with your my_array:

In [31]: my_array = np.array(["a", "a", "c", "c", "a"])

In [32]: b = my_array.view(np.int32) - ord('a')

In [33]: b
Out[33]: array([0, 0, 2, 2, 0], dtype=int32)

In [34]: np.bincount(b, minlength=3)
Out[34]: array([3, 0, 2])

Here's a timing comparison of that method and collections.Counter using an input with length 100:

In [34]: rng = np.random.default_rng()

In [35]: a = rng.choice(['a', 'a', 'b', 'c'], size=100)

In [36]: %timeit Counter(a)
32.1 µs ± 723 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [37]: %timeit b = a.view(np.int32) - ord('a'); np.bincount(b, minlength=3)
3.86 µs ± 50.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

The approach with bincount() is much faster.

It is also faster than using np.unique() with the parameter return_counts=True:

In [41]: %timeit values, counts = np.unique(a, return_counts=True)
19.7 µs ± 274 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)


问:
How to calculate a running total with Apache Beam
Using the Apache Beam SDK for Google Dataflow I'd like to calculate a daily balance from a set of transactions.

An example data set may look like this with the name of the payee, the transaction date, and an amount:

```<code>John, 2017-12-01, 100
John, 2017-12-01, 200
Jane, 2017-12-01, 150
John, 2017-12-02, -100
John, 2017-12-02, 300
</code>```

The desired result set would look like:

```<code>John, 2017-12-01, 300  (100 + 200)
Jane, 2017-12-01, 150
John, 2017-12-02, 500  (300 + -100 + 300)
</code>```

I've tried using a KV<Pair, BigDecimal> with a Combine.perKey function that calculated the sum of the BigDecimal but that doesn't account for the previous day's ending balance as the starting balance for the next day.

答:
This is simpler usecase of State in Beam. Once you have the key,value collection, you can apply GlobalWindow on that PCollection and then update the count by using State.

With Timers and State, we can actually output the data periodically if needed. In this case, it will output data only when new word or same word arrives, so if no data arrives for a given day, it will not output anything which may or may not be the behaviour you want.

If you're looking at more complicated output scenario, please review this post on Timely and Stateful processing

PCollection<String> input; // read input
PCollection<String> output = input.apply(MapElements.into(TypeDescriptors.kvs(TypeDescriptors.strings(), TypeDescriptors.longs()))
    .via((String elem) -> KV.of(elem, 1L)))
  .apply(Window.<KV<String, Long>>into(new GlobalWindows())
  .apply(ParDo.of(new UpdateOccurrenceCountByWord()))
```
<p>The <code>UpdateOccurrenceCountByWord</code> is the one where I am using State to store previous values. In this case, I only need to store the previous count.</p>
<pre class="lang-java prettyprint-override"><code>private static class UpdateOccurrenceCountByWord extends DoFn<KV<String, Long>, String> {
        private static final String WORD_COUNT = "word_count";

        @StateId(WORD_COUNT)
        private final StateSpec<BagState<Long>> wordsSeen = StateSpecs.bag();

        @ProcessElement
        public void process(@Element KV<String, Long> in, OutputReceiver<String> out, @StateId(WORD_COUNT) BagState<Long> counter) {
            List<Long> countsSoFar = Lists.newArrayList(counter.read());
            Long sum = in.getValue();
            for (Long value: countsSoFar) {
                sum += value;
            }
            countsSoFar.add(sum);
            counter.add(in.getValue());
            out.output(in.getKey().toString() + "," + sum.toString());
        }
}
</code>```

Body:
Using the Apache Beam SDK for Google Dataflow I'd like to calculate a daily balance from a set of transactions.

An example data set may look like this with the name of the payee, the transaction date, and an amount:

John, 2017-12-01, 100
John, 2017-12-01, 200
Jane, 2017-12-01, 150
John, 2017-12-02, -100
John, 2017-12-02, 300

The desired result set would look like:

John, 2017-12-01, 300  (100 + 200)
Jane, 2017-12-01, 150
John, 2017-12-02, 500  (300 + -100 + 300)

I've tried using a KV<Pair, BigDecimal> with a Combine.perKey function that calculated the sum of the BigDecimal but that doesn't account for the previous day's ending balance as the starting balance for the next day.

Body:
This is simpler usecase of State in Beam. Once you have the key,value collection, you can apply GlobalWindow on that PCollection and then update the count by using State.

With Timers and State, we can actually output the data periodically if needed. In this case, it will output data only when new word or same word arrives, so if no data arrives for a given day, it will not output anything which may or may not be the behaviour you want.

If you're looking at more complicated output scenario, please review this post on Timely and Stateful processing

PCollection<String> input; // read input
PCollection<String> output = input.apply(MapElements.into(TypeDescriptors.kvs(TypeDescriptors.strings(), TypeDescriptors.longs()))
    .via((String elem) -> KV.of(elem, 1L)))
  .apply(Window.<KV<String, Long>>into(new GlobalWindows())
  .apply(ParDo.of(new UpdateOccurrenceCountByWord()))

The UpdateOccurrenceCountByWord is the one where I am using State to store previous values. In this case, I only need to store the previous count.

private static class UpdateOccurrenceCountByWord extends DoFn<KV<String, Long>, String> {
        private static final String WORD_COUNT = "word_count";

        @StateId(WORD_COUNT)
        private final StateSpec<BagState<Long>> wordsSeen = StateSpecs.bag();

        @ProcessElement
        public void process(@Element KV<String, Long> in, OutputReceiver<String> out, @StateId(WORD_COUNT) BagState<Long> counter) {
            List<Long> countsSoFar = Lists.newArrayList(counter.read());
            Long sum = in.getValue();
            for (Long value: countsSoFar) {
                sum += value;
            }
            countsSoFar.add(sum);
            counter.add(in.getValue());
            out.output(in.getKey().toString() + "," + sum.toString());
        }
}


问:
Best practices for creating a data model
For a current project I'm creating a data model. Are there any sources where I can find "best practices" for a good data model? Good means flexible, efficient, with good performance, style, ... Some example questions would be "naming of columns", "what data should be normalized", or "which attributes should be exported into an own table".  The source should be a book :-)</p>

答:
The best book I've read on the design of database systems was "An Introduction to Database Systems". Joe Celko's SQL for Smarties books are also worth reading.
Assuming you're building an application and not just a database, and assuming you're using an Object Oriented language, Applying UML and Patterns by Craig Larman has a good discussion on mapping databases to objects.

In terms of defining "good", in my experience "maintainable" is probably top of the list. Maintainability in database design means many things, such as sticking to conventions - I often recommend http://justinsomnia.org/2003/04/essential-database-naming-conventions-and-style/. Normalization is another obvious maintainability strategy. I often recommend being generous with column types - it's hard to change an application if you find out that postal codes in different countries are longer than in the US. I often recommend using views to abstract complex data relations away for less experienced developers.

A key thing with maintainability is the ability to test and deploy. It's worth reading up about Continuous Database Integration (http://www.codeproject.com/KB/architecture/Database_CI.aspx) - whilst not strictly associated with the design of the database schema, it's important context.

As for performance - I believe you should design for maintainability first, and only design for performance if you know you have a problem. Sometimes, you know in advance that performance will be a major problem - designing a database for Facebook (or Stack Exchange), designing a database with huge amounts of data (terabytes and up), or huge numbers of users. Most systems don't fall into that camp - so I recommend regular performance tests, with representative data, to find if you have a problem, and only tune when you can prove you have to. Many performance optimizations are at the expense of maintainability - denormalization, for instance.

Oh, and in general, avoid triggers and stored procedures if you can. That's just my opinion, though...


问:
How can I turn off auto-complete for .txt files in VS Code?
I have a .txt file in VS Code. I use it for typing in plain text.

It suggests auto-completion. I want to keep auto-completion on for other files, such as Python file.

I want to turn of auto-completion suggestions for only .txt files in VS Code. Is that possible?

答:
Make a language-specific setting like this (in your settings.json):

```<code>"[plaintext]": {
  "editor.quickSuggestions": {
    "other": false,
    "comments": false,
    "strings": false
  }
}
</code>```

So you shouldn't get the suggestions automaticallyin a .txt file, you can still trigger them manually if you want with Ctrl+Space.

Body:
Make a language-specific setting like this (in your settings.json):

"[plaintext]": {
  "editor.quickSuggestions": {
    "other": false,
    "comments": false,
    "strings": false
  }
}

So you shouldn't get the suggestions automaticallyin a .txt file, you can still trigger them manually if you want with Ctrl+Space.


问:
Partial type family application
This recursive definition of T fails to type-check.

class C a where
  type T a :: Type

newtype Compose (f :: Type -> Type) (g :: Type -> Type) (a :: Type) = Compose {getCompose :: f (g a)}

instance C (Maybe a) where
  type T (Maybe a) = NP (Compose T Identity) '[a]
```
<p>Specific error:</p>
```    • The associated type family ‘T’ should have 1 argument, but has been given none
    • In the type instance declaration for ‘T’
      In the instance declaration for ‘C (Maybe a)’
   |
32 |   type T (Maybe a) = NP (Compose T Identity) '[a]
   |        ^
```
<ol>
<li>Why is GHC unable to do this?</li>
<li>Is there a workaround?</li>
</ol>
<p>The real class/instance looks like this:</p>
<pre class="lang-hs prettyprint-override"><code>instance Ema (MultiSite models) where
  type RouteFor (MultiSite models) = NP (Compose RouteFor Site) models
</code>```

This says that "the route for a multisite is an n-ary product of the routes for the individual sites", hence RouteFor has to be defined recursively.

答:
Type families are unmatchable and must be fully saturated. This means they can not be passed partially applied as an argument. This is basically what the error message says

• The associated type family ‘T’ should have 1 argument, but has been given none

At the present time this is not distinguished at the kind level (see Unsaturated type families proposal) but there is a very clear distinction within GHC.

According to :kind both T and Identity have the same kind while in reality Identity is Matchable and T is Unmatchable:

Identity :: Type -> @M Type
T        :: Type -> @U Type
```
<p>Because the arguments of <code>Compose</code> are <code>Type -> @M Type</code> you cannot pass an unmatchable type family. The type language is first order! (Higher-Order Type-Level Programming in Haskell) and there is no way to define <code>Compose</code> that accepts an unmatchable function at the moment.</p>
<p>If you compare the kind of the slightly modified <code>T1</code> and <code>T2</code>, the first one is unmatchable in both arguments while the second is matchable in its second argument</p>
```type  C1 :: Type -> @M Constraint
class C1 a where
  --   T1 :: Type -> @U Type -> @U Type
  type T1 a (b :: Type) :: Type

type  C2 :: Type -> @M Contraint
class C2 a where
  --   T2 :: Type -> @U Type -> @M Type
  type T2 a :: Type -> Type
```
<p>A possibility is to wrap it in a (matchable) newtype</p>
<pre class="lang-hs prettyprint-override"><code>type    Wrapp'T :: Type -> @M Type
newtype Wrapp'T a = Wrapp'd (T a)

instance C (Maybe a) where
  type T (Maybe a) = NP (Compose Wrapp'T Identity) '[a]
</code>```

Title: Partial type family application

Body:
This recursive definition of T fails to type-check.

class C a where
  type T a :: Type

newtype Compose (f :: Type -> Type) (g :: Type -> Type) (a :: Type) = Compose {getCompose :: f (g a)}

instance C (Maybe a) where
  type T (Maybe a) = NP (Compose T Identity) '[a]

Specific error:

    • The associated type family ‘T’ should have 1 argument, but has been given none
    • In the type instance declaration for ‘T’
      In the instance declaration for ‘C (Maybe a)’
   |
32 |   type T (Maybe a) = NP (Compose T Identity) '[a]
   |        ^

Why is GHC unable to do this?

Is there a workaround?

The real class/instance looks like this:

instance Ema (MultiSite models) where
  type RouteFor (MultiSite models) = NP (Compose RouteFor Site) models

This says that "the route for a multisite is an n-ary product of the routes for the individual sites", hence RouteFor has to be defined recursively.

Body:
Type families are unmatchable and must be fully saturated. This means they can not be passed partially applied as an argument. This is basically what the error message says

• The associated type family ‘T’ should have 1 argument, but has been given none

At the present time this is not distinguished at the kind level (see Unsaturated type families proposal) but there is a very clear distinction within GHC.

According to :kind both T and Identity have the same kind while in reality Identity is Matchable and T is Unmatchable:

Identity :: Type -> @M Type
T        :: Type -> @U Type

Because the arguments of Compose are Type -> @M Type you cannot pass an unmatchable type family. The type language is first order! (Higher-Order Type-Level Programming in Haskell) and there is no way to define Compose that accepts an unmatchable function at the moment.

If you compare the kind of the slightly modified T1 and T2, the first one is unmatchable in both arguments while the second is matchable in its second argument

type  C1 :: Type -> @M Constraint
class C1 a where
  --   T1 :: Type -> @U Type -> @U Type
  type T1 a (b :: Type) :: Type

type  C2 :: Type -> @M Contraint
class C2 a where
  --   T2 :: Type -> @U Type -> @M Type
  type T2 a :: Type -> Type

A possibility is to wrap it in a (matchable) newtype

type    Wrapp'T :: Type -> @M Type
newtype Wrapp'T a = Wrapp'd (T a)

instance C (Maybe a) where
  type T (Maybe a) = NP (Compose Wrapp'T Identity) '[a]


问:
SQL date conversion to mm/dd/yyyy hh:mm
Can't seem to find answer to what seems like a simple question. I have a date that is returned
2022-02-07 18:53:36.000 I need to convert that date to mm/dd/yyyy hh:mm.
Is that possible?

答:
I got the answer from another site. I've tested it and it works.</p>
```<code>(CONVERT(VARCHAR(20), ea.event_timestamp, 101) + ' ' + LEFT(CONVERT(VARCHAR(20),ea.event_timestamp, 108) ,5)) AS  EventDate
</code>```

Title: SQL date conversion to mm/dd/yyyy hh:mm

Body:
I got the answer from another site. I've tested it and it works.

(CONVERT(VARCHAR(20), ea.event_timestamp, 101) + ' ' + LEFT(CONVERT(VARCHAR(20),ea.event_timestamp, 108) ,5)) AS  EventDate


问:
How do I create an auto timeout for users that redirect to login page?
I want to add a section to my site which will logout the user and redirect them to the log in page. I want to do this so no user is idle or keep one login secession open for more than 24 hours. How would I create an auto timeout in c#?</p>

答:
Are you using Identity framework? If yes, you will find IdentityConfig.cs class in
App_Start folder. In ApplicationUserManager add the following line of code or set the value as per your requirements.

```<code>manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(15);
</code>```

Body:
Are you using Identity framework? If yes, you will find IdentityConfig.cs class in
App_Start folder. In ApplicationUserManager add the following line of code or set the value as per your requirements.

manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(15);


问:
Problem with RecyclerView OnClick (kotlin)
sorry for the inconvenience, but this is my first time trying this. I've been trying on doing this app which it has a recyclerView which I intent it to open a chrome page. The thing is, I'm not able to implement the itemOnClickListener despite having tried a lot of videos. Could you point out where is my mistake?

My Adapter:

```<code>package com.example.practica1.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.example.practica1.R
import com.example.practica1.data.Video

class MainAdapter(private val context: Context, private val videos: List<Video>): RecyclerView.Adapter<MainAdapter.ViewHolder>(){

    private lateinit var mListener: onItemClickListener

    interface onItemClickListener{
        fun onItemClick(position: Int)
    }

    fun setOnClickListener(listener: onItemClickListener){
        mListener = listener
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainAdapter.ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_cartoon, parent, false)
        return ViewHolder(view, mListener)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val video = videos[position]
        holder.title.text = video.data.short_title
        holder.serieTitle.text = video.data.show.title
        holder.durationTitle.text = video.data.video.duration + " seg"
        Glide.with(context)
            .load(video.data.imagepath)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .override(400, 400)
            .centerCrop()
            .into(holder.imagePrev)

    }

    override fun getItemCount() = videos.size

    inner class ViewHolder(itemView: View, listener: onItemClickListener) : RecyclerView.ViewHolder(itemView){
        val title: TextView = itemView.findViewById(R.id.videoTitle)
        val serieTitle: TextView = itemView.findViewById(R.id.serieTitle)
        val durationTitle: TextView = itemView.findViewById(R.id.durationTitle)
        val imagePrev: ImageView = itemView.findViewById(R.id.photoPreview)

        init{
            itemView.setOnClickListener{
                listener.onItemClick(adapterPosition)
            }
        }
    }

}
</code>```

The fragment in which I tried to implement the method:

```<code>package com.example.practica1.fragments

import android.os.Bundle
import android.util.Log
import android.util.Log.d
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.Navigation
import androidx.recyclerview.widget.RecyclerView
import com.example.practica1.R
import com.example.practica1.adapter.MainAdapter
import com.example.practica1.data.ApiInterface
import com.example.practica1.data.Video
import com.example.practica1.databinding.FragmentMenuBinding
import com.haerul.bottomfluxdialog.BottomFluxDialog
import com.haerul.bottomfluxdialog.BottomFluxDialog.OnInputListener
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class MenuFragment : Fragment() {
    private var _binding: FragmentMenuBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        _binding = FragmentMenuBinding.inflate(inflater, container, false)

        val view = inflater.inflate(R.layout.fragment_menu, container, false)

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val retrofit = Retrofit.Builder()
            .baseUrl("https://www.cartoonnetwork.com.co")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        val api = retrofit.create(ApiInterface::class.java)
        showProgress()
        api.fetchAllVideos().enqueue(object : Callback<List<Video>> {
            override fun onResponse(call: Call<List<Video>>, response: Response<List<Video>>) {
                if (response.isSuccessful()) {
                    d("daniel", "onResponse ${response.body()!![0].id}")
                    if (response.body()!!.size > 0) {
                        showData(response.body()!!)
                        getResult(true, "Sucess")
                    } else
                        getResult(false, response.message())

                    hideProgress()
                }

            }

            override fun onFailure(call: Call<List<Video>>, t: Throwable) {
                d("daniel", "onFailure")
                getResult(false, "Request Timeout. Please Try Again!")
                hideProgress()
            }

        })

        binding.search.setOnClickListener { v -> showDialog(v) }
    }

    fun showData(videos: List<Video>){
        val test: RecyclerView = requireActivity().findViewById(R.id.recycler_viewMenu)
        var adap = MainAdapter(requireContext(), videos)
        test.apply{
            adapter = adap
        }

        adap.setOnClickListener(object: MainAdapter.onItemClickListener{
            override fun onItemClick(position: Int){
                d("test", "test")
            }
        })
    }

    fun showProgress(){
        binding.swipeRefresh.setRefreshing(true)
        binding.emptyView.setVisibility(View.GONE)
        binding.shimmer.startShimmer()
        binding.shimmer.setVisibility(View.VISIBLE)
        binding.recyclerViewMenu.setVisibility(View.GONE)
    }

     fun hideProgress(){
        binding.swipeRefresh.setRefreshing(false)
        binding.shimmer.stopShimmer()
        binding.shimmer.setVisibility(View.GONE)
        binding.recyclerViewMenu.setVisibility(View.VISIBLE)
    }

    fun getResult(status: Boolean, message: String){
        if(!status) {
            binding.emptyView.setVisibility(View.VISIBLE)
            binding.textEmptyErr.setText(message)
        }
        else
            binding.emptyView.setVisibility((View.GONE))
    }

    private fun showDialog(view: View){
        BottomFluxDialog.inputDialog(requireActivity())
            .setTextTitle("Input Title")
            .setTextMessage("This is an input message")
            .setRightButtonText("SUBMIT")
            .setInputListener(object : OnInputListener {
                override fun onSubmitInput(text: String?) {
                    val bundle = Bundle()
                    bundle.putString("search", text)
                    Navigation.findNavController(view)
                        .navigate(R.id.action_menuFragment_to_listFragment, bundle)
                }

                override fun onCancelInput() {}

            })

            .show()
    }

}
</code>```

Thanks!

答:
There is no such common thin like OnItemClickListener for RecyclerView, so you have to design your own. It shouldn't be hard to implement by hand, though. What you can do, is that you can Just set OnClickListener to the whole item view and delegate it clicks to upper lambda.

```<code>class YourAdapter(
    private val listener: (Video) -> Unit,
    private val videos: List<Video>,
): ... {
     ...
     override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        ...
        holder.itemView.setOnClickListener { v ->
            if (position != RecyclerView.NO_POSITION) {
                listener(videos[position])
            }
        }
     }
}
</code>```

There are no noticeable side-effects of swapping View.OnClickListener in onBindViewHolder() method.

Also, few suggestions:

Read about ListAdapterhere. Looks like it perfect fit for your usecase.

Use getAbsoluteAdapterPosition() instead of adapterPosition() method within ViewHolder,  as adapters are designed to be combined. Read more about ConcatAdapter here.

You don't need to pass Context to adapter constructor. View already has context, so you can query context by calling viewHolder.itemView.context.

Make sure to use your binding. It looks like you creating your binding in MenuFragment, but later you are getting RecyclerView by id in an old-fashioned way.

Don't create adapters, that require data for creation. Instead, pass and update data as you requested from the backend. RecyclerView.Adapter is designed to be reused.

Body:
sorry for the inconvenience, but this is my first time trying this. I've been trying on doing this app which it has a recyclerView which I intent it to open a chrome page. The thing is, I'm not able to implement the itemOnClickListener despite having tried a lot of videos. Could you point out where is my mistake?

My Adapter:

package com.example.practica1.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.example.practica1.R
import com.example.practica1.data.Video

class MainAdapter(private val context: Context, private val videos: List<Video>): RecyclerView.Adapter<MainAdapter.ViewHolder>(){

    private lateinit var mListener: onItemClickListener

    interface onItemClickListener{
        fun onItemClick(position: Int)
    }

    fun setOnClickListener(listener: onItemClickListener){
        mListener = listener
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainAdapter.ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_cartoon, parent, false)
        return ViewHolder(view, mListener)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val video = videos[position]
        holder.title.text = video.data.short_title
        holder.serieTitle.text = video.data.show.title
        holder.durationTitle.text = video.data.video.duration + " seg"
        Glide.with(context)
            .load(video.data.imagepath)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .override(400, 400)
            .centerCrop()
            .into(holder.imagePrev)

    }

    override fun getItemCount() = videos.size

    inner class ViewHolder(itemView: View, listener: onItemClickListener) : RecyclerView.ViewHolder(itemView){
        val title: TextView = itemView.findViewById(R.id.videoTitle)
        val serieTitle: TextView = itemView.findViewById(R.id.serieTitle)
        val durationTitle: TextView = itemView.findViewById(R.id.durationTitle)
        val imagePrev: ImageView = itemView.findViewById(R.id.photoPreview)

        init{
            itemView.setOnClickListener{
                listener.onItemClick(adapterPosition)
            }
        }
    }

}

The fragment in which I tried to implement the method:

package com.example.practica1.fragments

import android.os.Bundle
import android.util.Log
import android.util.Log.d
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.Navigation
import androidx.recyclerview.widget.RecyclerView
import com.example.practica1.R
import com.example.practica1.adapter.MainAdapter
import com.example.practica1.data.ApiInterface
import com.example.practica1.data.Video
import com.example.practica1.databinding.FragmentMenuBinding
import com.haerul.bottomfluxdialog.BottomFluxDialog
import com.haerul.bottomfluxdialog.BottomFluxDialog.OnInputListener
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class MenuFragment : Fragment() {
    private var _binding: FragmentMenuBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        _binding = FragmentMenuBinding.inflate(inflater, container, false)

        val view = inflater.inflate(R.layout.fragment_menu, container, false)

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val retrofit = Retrofit.Builder()
            .baseUrl("https://www.cartoonnetwork.com.co")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        val api = retrofit.create(ApiInterface::class.java)
        showProgress()
        api.fetchAllVideos().enqueue(object : Callback<List<Video>> {
            override fun onResponse(call: Call<List<Video>>, response: Response<List<Video>>) {
                if (response.isSuccessful()) {
                    d("daniel", "onResponse ${response.body()!![0].id}")
                    if (response.body()!!.size > 0) {
                        showData(response.body()!!)
                        getResult(true, "Sucess")
                    } else
                        getResult(false, response.message())

                    hideProgress()
                }

            }

            override fun onFailure(call: Call<List<Video>>, t: Throwable) {
                d("daniel", "onFailure")
                getResult(false, "Request Timeout. Please Try Again!")
                hideProgress()
            }

        })

        binding.search.setOnClickListener { v -> showDialog(v) }
    }

    fun showData(videos: List<Video>){
        val test: RecyclerView = requireActivity().findViewById(R.id.recycler_viewMenu)
        var adap = MainAdapter(requireContext(), videos)
        test.apply{
            adapter = adap
        }

        adap.setOnClickListener(object: MainAdapter.onItemClickListener{
            override fun onItemClick(position: Int){
                d("test", "test")
            }
        })
    }

    fun showProgress(){
        binding.swipeRefresh.setRefreshing(true)
        binding.emptyView.setVisibility(View.GONE)
        binding.shimmer.startShimmer()
        binding.shimmer.setVisibility(View.VISIBLE)
        binding.recyclerViewMenu.setVisibility(View.GONE)
    }

     fun hideProgress(){
        binding.swipeRefresh.setRefreshing(false)
        binding.shimmer.stopShimmer()
        binding.shimmer.setVisibility(View.GONE)
        binding.recyclerViewMenu.setVisibility(View.VISIBLE)
    }

    fun getResult(status: Boolean, message: String){
        if(!status) {
            binding.emptyView.setVisibility(View.VISIBLE)
            binding.textEmptyErr.setText(message)
        }
        else
            binding.emptyView.setVisibility((View.GONE))
    }

    private fun showDialog(view: View){
        BottomFluxDialog.inputDialog(requireActivity())
            .setTextTitle("Input Title")
            .setTextMessage("This is an input message")
            .setRightButtonText("SUBMIT")
            .setInputListener(object : OnInputListener {
                override fun onSubmitInput(text: String?) {
                    val bundle = Bundle()
                    bundle.putString("search", text)
                    Navigation.findNavController(view)
                        .navigate(R.id.action_menuFragment_to_listFragment, bundle)
                }

                override fun onCancelInput() {}

            })

            .show()
    }

}

Thanks!

Body:
There is no such common thin like OnItemClickListener for RecyclerView, so you have to design your own. It shouldn't be hard to implement by hand, though. What you can do, is that you can Just set OnClickListener to the whole item view and delegate it clicks to upper lambda.

class YourAdapter(
    private val listener: (Video) -> Unit,
    private val videos: List<Video>,
): ... {
     ...
     override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        ...
        holder.itemView.setOnClickListener { v ->
            if (position != RecyclerView.NO_POSITION) {
                listener(videos[position])
            }
        }
     }
}

There are no noticeable side-effects of swapping View.OnClickListener in onBindViewHolder() method.

Also, few suggestions:

Read about ListAdapterhere. Looks like it perfect fit for your usecase.

Use getAbsoluteAdapterPosition() instead of adapterPosition() method within ViewHolder,  as adapters are designed to be combined. Read more about ConcatAdapter here.

You don't need to pass Context to adapter constructor. View already has context, so you can query context by calling viewHolder.itemView.context.

Make sure to use your binding. It looks like you creating your binding in MenuFragment, but later you are getting RecyclerView by id in an old-fashioned way.

Don't create adapters, that require data for creation. Instead, pass and update data as you requested from the backend. RecyclerView.Adapter is designed to be reused.


问:
Why does the sprite costume not change?
I'm just starting to play about in Scratch...

I seem to have a sprite of a cat with two 'costumes', which I guess are like frames.

I made this sequence:

...but when I click the green flag the cat moves to the right but the costumes don't switch.

If I make a simpler sequence:

...and manually change the costume in the drop-down then the costume does change.

What is the limitation here?

答: Try using a [wait] block: the change between costumes may be so fast that it seems like it is walking without changing costumes...</p>

Title: Why does the sprite costume not change?