问:
flyway locations to control dbms changes for multiple DBs
My flyway config - using mvn package to run flyway

```<code><plugin>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-maven-plugin</artifactId>
            <version>4.2.0</version>
            <configuration>
                <locations>
                    <location>db.migration.h2</location>
                </locations>
            </configuration>
        </plugin>
</code>```

I have a maven app that works just fine for one DB  (using h2 database engine) I need to support flyway to other DB systems (db2, oracle ee, postgres.   On another project we are doing something similar flyway config file on flyway version 3.2.1 to manage table cration between H2 and timesten.

(new findings) When I use flyway location  or configuration file entry in hte pom file.  "mvn clean package" works just fine using.  However "mvn verify" gives me the error that it has multiple V#_# files.

I had H2 flyway files in the following directory structure

```<code>atdd/src/main/java/db/migration/V1_2__comment.java
atdd/src/main/resources/db/migration/V1_1__create_tables.sql
</code>```

I created a subdirectory "h2" under migration and moved the flyway files into that subdirectory.

I made copies db and oracle ee versions of those files in "db/migration/db2" and "db/migration/oracle_ee

RUNNING maven package only gives me:

```<code>Caused by: org.flywaydb.core.api.FlywayException: Found more than one migration with version 1.1
Offenders:
->/Users/XXXXX/Documents/fun/atdd/target/classes/db/migration/h2/V1_1__create_tables.sql (SQL)
->/Users/xxxxxx/Documents/fun/atdd/target/classes/db/migration/db2/V1_1__create_tables.sql (SQL)
</code>```

I have tried using a property file and that does not work either

```<code>   <plugin>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-maven-plugin</artifactId>
            <version>4.2.0</version>

            <configuration>
                   <configFile>./flyway.properties</configFile>
            </configuration>
        </plugin>
</code>```

atdd/flyway.properties has

```<code> flyway.locations=db.migration.h2
</code>```

Seems to be a problem with what ever runs regression tests (surefire plugin - i am fairly new to maven)
Is there anything special about surefire plugin?

答:
I was able to get working by adding config arguments to failsafe plugin

```<code> <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
            <version>2.19.1</version><!--$NO-MVN-MAN-VER$ -->
            <configuration><argLine>-Dflyway.locations=db.migrtion.h2</argLine></configuration>
            <executions>
</code>```

with

```<code>mvn clean package  verify site -Dflyway.locations=db.migration.h2
</code>```

oddly does not work if I don't have "-Dflyway.locations=db.migration.h2 "

Body:
My flyway config - using mvn package to run flyway

<plugin>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-maven-plugin</artifactId>
            <version>4.2.0</version>
            <configuration>
                <locations>
                    <location>db.migration.h2</location>
                </locations>
            </configuration>
        </plugin>

I have a maven app that works just fine for one DB  (using h2 database engine) I need to support flyway to other DB systems (db2, oracle ee, postgres.   On another project we are doing something similar flyway config file on flyway version 3.2.1 to manage table cration between H2 and timesten.

(new findings) When I use flyway location  or configuration file entry in hte pom file.  "mvn clean package" works just fine using.  However "mvn verify" gives me the error that it has multiple V#_# files.

I had H2 flyway files in the following directory structure

atdd/src/main/java/db/migration/V1_2__comment.java
atdd/src/main/resources/db/migration/V1_1__create_tables.sql

I created a subdirectory "h2" under migration and moved the flyway files into that subdirectory.

I made copies db and oracle ee versions of those files in "db/migration/db2" and "db/migration/oracle_ee

RUNNING maven package only gives me:

Caused by: org.flywaydb.core.api.FlywayException: Found more than one migration with version 1.1
Offenders:
->/Users/XXXXX/Documents/fun/atdd/target/classes/db/migration/h2/V1_1__create_tables.sql (SQL)
->/Users/xxxxxx/Documents/fun/atdd/target/classes/db/migration/db2/V1_1__create_tables.sql (SQL)

I have tried using a property file and that does not work either

   <plugin>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-maven-plugin</artifactId>
            <version>4.2.0</version>

            <configuration>
                   <configFile>./flyway.properties</configFile>
            </configuration>
        </plugin>

atdd/flyway.properties has

 flyway.locations=db.migration.h2

Seems to be a problem with what ever runs regression tests (surefire plugin - i am fairly new to maven)
Is there anything special about surefire plugin?

Body:
I was able to get working by adding config arguments to failsafe plugin

 <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
            <version>2.19.1</version><!--$NO-MVN-MAN-VER$ -->
            <configuration><argLine>-Dflyway.locations=db.migrtion.h2</argLine></configuration>
            <executions>

with

mvn clean package  verify site -Dflyway.locations=db.migration.h2

oddly does not work if I don't have "-Dflyway.locations=db.migration.h2 "


来源: stackexchange

问:
Oracle Apex 5: Using Multiple Columns in a Bar Charts Axix
I'm trying to create a bar chart that shows the values of multiple columns from a table. It's a very simple bar chart, that I can't figure out how to design in APEX 5/SQL.

Chart describing what I mean

Basically, I want the X axis of the bar chart to have bar for each column of my table (that I choose), and the bar will represent the sum of that column, grouped by a column called appname.

I know I will need a:

SELECT SUM(columns)
FROM myTable
GROUP BY appname

But I can't seem to get the bar chart to represent each column I choose.

Hopefully I've explained this well, my colleagues who don't know how to help say I don't explain things well.

答:
This can be done, but as far as I'm aware only for a fixed number of sets of data.  This is what I was able to do with some dummy data:

What you have to do is first create a chart for one of the sets something like:

```<code>select code, sum(value) as total
  from data
 where app_id = 1
 group by code
 order by code
</code>```

That produces this (with my sample data):

Now when you look at the region definition you will see that the region contains a single "series":

(By default it is named "Series 1" - but I already renamed mine to "App 1").

Now you can right-click on Series 1 and select "Duplicate" and a new, duplicate series will be created.  You can then edit the name and SQL of this new series to refer to application 2.  Then when you run that you will see the result I showed at the beginning.

ContentLicense: CC BY-SA 3.0

Body:
This can be done, but as far as I'm aware only for a fixed number of sets of data.  This is what I was able to do with some dummy data:

What you have to do is first create a chart for one of the sets something like:

select code, sum(value) as total
  from data
 where app_id = 1
 group by code
 order by code

That produces this (with my sample data):

Now when you look at the region definition you will see that the region contains a single "series":

(By default it is named "Series 1" - but I already renamed mine to "App 1").

Now you can right-click on Series 1 and select "Duplicate" and a new, duplicate series will be created.  You can then edit the name and SQL of this new series to refer to application 2.  Then when you run that you will see the result I showed at the beginning.


问:
Does the available EC2 instances types vary over availablity zones (in the same region)?
Amazon launched a third availability zone in Frankfurt: eu-central-1c

From what I see, the third availability zone does not support all instance types that are available in the existing zones (eu-central-1a and eu-central-1b).

I always assumed that the available instance types may differ over regions but are identical over availability zones within the same region. From what I see that is not the case.

Is it true that you if an EC2 instance type is available in one region, you cannot make the assumption that it will be available in all availability zones?

The script that used for testing is:

```<code>aws ec2 describe-reserved-instances-offerings \
  --query "ReservedInstancesOfferings[?AvailabilityZone=='eu-central-1c'] [InstanceType]" \
  --output text --region eu-central-1 | grep c3.large

# c3.large not available on eu-central-1c
</code>```

but

```<code>aws ec2 describe-reserved-instances-offerings \
  --query "ReservedInstancesOfferings[?AvailabilityZone=='eu-central-1a'] [InstanceType]" \
  --output text --region eu-central-1 | grep c3.large

# ... it is available on eu-central-1a
</code>```

答:
The availability of instance types can differ between availability zones in a region based on the documentation.

From the EC2 docs:

Some AWS resources might not be available in all regions and
  Availability Zones. Ensure that you can create the resources you need
  in the desired regions or Availability Zone before launching an
  instance in a specific Availability Zone.

Although resource is a vague term, an instance type should be considered a resource. So, it's possible that a certain instance type is not available in a certain zone but available in other availability zones. There are also cases where an instance of a certain type cannot be launched because AWS does not have enough capacity in that zone at the time of request.

Another important thing to note here is that the availability zones are not fixed for all accounts as described here.

To ensure that resources are distributed across the Availability Zones
  for a region, we independently map Availability Zones to identifiers
  for each account. For example, your Availability Zone us-east-1a might
  not be the same location as us-east-1a for another account. There's no
  way for you to coordinate Availability Zones between accounts.

Body:
Amazon launched a third availability zone in Frankfurt: eu-central-1c

From what I see, the third availability zone does not support all instance types that are available in the existing zones (eu-central-1a and eu-central-1b).

I always assumed that the available instance types may differ over regions but are identical over availability zones within the same region. From what I see that is not the case.

Is it true that you if an EC2 instance type is available in one region, you cannot make the assumption that it will be available in all availability zones?

The script that used for testing is:

aws ec2 describe-reserved-instances-offerings \
  --query "ReservedInstancesOfferings[?AvailabilityZone=='eu-central-1c'] [InstanceType]" \
  --output text --region eu-central-1 | grep c3.large

# c3.large not available on eu-central-1c

but

aws ec2 describe-reserved-instances-offerings \
  --query "ReservedInstancesOfferings[?AvailabilityZone=='eu-central-1a'] [InstanceType]" \
  --output text --region eu-central-1 | grep c3.large

# ... it is available on eu-central-1a


问:
how to Delete Record From join table
I want to Delete Record from Two different Table but i join those table using Left join

```<code>DELETE tab_issue.tab_issueID, tab_return.tab_issueID
FROM tab_issue
INNER JOIN tab_return
WHERE tab_issue.tab_issueID = tab_return.tab_issueID
</code>```

I have no strong concept on sQL
if someone have simple query which solve my issue.
I am using mySQL database

答:
This should do the trick.</p>

```<code>DELETE tab_issue, tab_return
FROM tab_issue INNER JOIN tab_return
ON tab_issue.tab_issueID = tab_return.tab_issueID;
</code>```

Title: how to Delete Record From join table

Body:
I want to Delete Record from Two different Table but i join those table using Left join

DELETE tab_issue.tab_issueID, tab_return.tab_issueID
FROM tab_issue
INNER JOIN tab_return
WHERE tab_issue.tab_issueID = tab_return.tab_issueID

I have no strong concept on sQL
if someone have simple query which solve my issue.
I am using mySQL database

Body:
This should do the trick.

DELETE tab_issue, tab_return
FROM tab_issue INNER JOIN tab_return
ON tab_issue.tab_issueID = tab_return.tab_issueID;


问:
Redirect a link from a URL with a certain string to another URL with Javascript
I have this link on my page:

```<code><a href="https://community.mydomain.com/t5/custom/page/page-id/developer-zone">
</code>```

and I need to redirect folks who click on that link to this URL:

```<code>https://community.mydomain.com/s/topic/0TO44000000FliLGAS/sdk
</code>```

I'd love to be able to add some Javascript/jQuery in the head that says "if a link URL contains 'community.mydomain.com' then redirect to the new URL if the user clicks on the link." Something tells me that it's not that easy.

I've checked similar questions and I don't think specifically address what I'm trying to do.

答:
Its actually quite easy, you can await a link click with jquery and redirect then:

$(function(){

$(document).on("click","a",function(e){
    e.preventDefault();//prevent google from opening
    location.href="http://stackoverflow.com";//open SO instead
});

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hi</code>```

Body:
I have this link on my page:

and I need to redirect folks who click on that link to this URL:

https://community.mydomain.com/s/topic/0TO44000000FliLGAS/sdk

I'd love to be able to add some Javascript/jQuery in the head that says "if a link URL contains 'community.mydomain.com' then redirect to the new URL if the user clicks on the link." Something tells me that it's not that easy.

I've checked similar questions and I don't think specifically address what I'm trying to do.

Body:
Its actually quite easy, you can await a link click with jquery and redirect then:

$(function(){

$(document).on("click","a",function(e){
    e.preventDefault();//prevent google from opening
    location.href="http://stackoverflow.com";//open SO instead
});

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="https://google.com">Hi</a>


问:
Amazon Python Web Scraping: All Variations of Product is Returning Same HTML Code as First Variation
I am using Python2 & using urlopen from urllib2 and BeautifulSoup from bs4 to scrap the HTML code of a few variations of the same product listing.

Namely: https://www.amazon.com/Mouse-Pad-Star-Wars-V4/dp/B00TGGVHOW

So when I scrap all the different variations of this same product listing, I am receiving the same exact HTML code back from Var1.

There are 9 total variations and the code returned is the same as the first variation.

It is very weird because if I visit the direct links and inspecting the source, I get different HTML but if its is being scraped using Python, it is getting identical HTML.

Can someone please take a look at this and guide me in the right direction? Much appreciated!

Just to add some information, Mr.sytech brought up a very good point. However, this issue is not occurring for every product but rather only happening to some products. If we take a look at this product: https://www.amazon.com/VicTsing-Wireless-Portable-Receiver-Adjustable/dp/B013WC0P2A it is working as intended and every variation is getting their own unique HTML returned.

答:
You can't expect what urllib2 retrieves to be identical to what you see in your browser. Chances are, the display of variations are controlled via JavaScript. Since urllib2 simply retrieves the server's response containing the HTML, it does not execute JavaScript or anything else that your browser would do.

There may be other options for sourcing the data with urllib, but you can also use browser automation, such as with selenium which can get you the DOM as it appears after executing JS and everything else that the browser does for you.


问:
Need to check dates are overlapping or not in sql server
Below is my input code

```<code>ID  EMP_ID       PROJECT_NAME            START_DATE          END_DATE
1   10016351    ABC                       22-12-2016        15-05-2017
2   10016351    ABC                       01-09-2016        22-11-2016
1   10081503    RTBS AMaaS                21-11-2016        15-02-2017
2   10081503    RTBS AMaaS                18-07-2016        25-11-2016
3   10081503    RTBS AMaaS                21-08-2016        13-10-2016
4   10081503    RTBS AMaaS                03-02-2015        22-05-2015
1   10089293    RTBS PDaaS                17-02-2017        31-12-2017
2   10089293    RTBS PDaaS                13-06-2016        14-02-2017
</code>```

I need to check for an employee, dates are overlapping or not. If yes then it will return min Start date and Max end date and flag as 'O'.

For ex, for emp_id = 10081503 dates are overlapping
21-11-2016 is falling between 18-07-2016    and 25-11-2016, also
21-08-2016 is falling between 18-07-2016    and 25-11-2016
so the query should return  start date as 18-07-2016 (min)  and end date as
 15-02-2017 (max) for the dates which are overlapping.
For rest entries, it should return the same entry with flag 'N'.

EMP_ID    |   PROJECT_NAME       |    START_DATE         |    END_DATE |  Flag
10081503  |     RTBS AMaaS       |         21-11-2016    |  15-02-2017 | O
10081503  |     RTBS AMaaS       |          03-02-2015   |  22-05-2015 | N

Like wise my final output should be,

```<code>ID  EMP_ID       PROJECT_NAME            START_DATE          END_DATE   FLAG
1   10016351    ABC                       22-12-2016        15-05-2017   N
2   10016351    ABC                       01-09-2016        22-11-2016   N
1    10081503   RTBS AMaaS                21-11-2016        15-02-2017   O
2    10081503   RTBS AMaaS                03-02-2015        22-05-2015   N
1   10089293    RTBS PDaaS                17-02-2017        31-12-2017   N
2   10089293    RTBS PDaaS                13-06-2016        14-02-2017   N
</code>```

答:
Thanks all for help.!

Need some help in the same context,

Came across below scenario,

In such a scenario, we will get two entries in the ALLOCATION DETAILS. This is because the resource was assigned to two different projectsbut the Allocation end date of the first allocation project (in the above example) overlappedwith Allocation Start date of the second allocation project.
Thus, for the computation of tenure of Allocation 1:
Tenure (Alloc 1)=Alloc Start Date (Alloc 2) – Alloc Start Date (Alloc 1)
    i.e., (17-11-2016) – (01-09-2016) = 77
The tenure calculation for allocation 2 has no changes.
Here, final entry would appear as below:

Body:
Below is my input code

ID  EMP_ID       PROJECT_NAME            START_DATE          END_DATE
1   10016351    ABC                       22-12-2016        15-05-2017
2   10016351    ABC                       01-09-2016        22-11-2016
1   10081503    RTBS AMaaS                21-11-2016        15-02-2017
2   10081503    RTBS AMaaS                18-07-2016        25-11-2016
3   10081503    RTBS AMaaS                21-08-2016        13-10-2016
4   10081503    RTBS AMaaS                03-02-2015        22-05-2015
1   10089293    RTBS PDaaS                17-02-2017        31-12-2017
2   10089293    RTBS PDaaS                13-06-2016        14-02-2017

I need to check for an employee, dates are overlapping or not. If yes then it will return min Start date and Max end date and flag as 'O'.

For ex, for emp_id = 10081503 dates are overlapping
21-11-2016 is falling between 18-07-2016    and 25-11-2016, also
21-08-2016 is falling between 18-07-2016    and 25-11-2016
so the query should return  start date as 18-07-2016 (min)  and end date as
 15-02-2017 (max) for the dates which are overlapping.
For rest entries, it should return the same entry with flag 'N'.

EMP_ID    |   PROJECT_NAME       |    START_DATE         |    END_DATE |  Flag
10081503  |     RTBS AMaaS       |         21-11-2016    |  15-02-2017 | O
10081503  |     RTBS AMaaS       |          03-02-2015   |  22-05-2015 | N

Like wise my final output should be,

ID  EMP_ID       PROJECT_NAME            START_DATE          END_DATE   FLAG
1   10016351    ABC                       22-12-2016        15-05-2017   N
2   10016351    ABC                       01-09-2016        22-11-2016   N
1    10081503   RTBS AMaaS                21-11-2016        15-02-2017   O
2    10081503   RTBS AMaaS                03-02-2015        22-05-2015   N
1   10089293    RTBS PDaaS                17-02-2017        31-12-2017   N
2   10089293    RTBS PDaaS                13-06-2016        14-02-2017   N


问:
Is it possible to run a Spring Cloud AWS application on Elastic Beanstalk?
I'm trying to run a web application of "hello world" complexity on Elastic Beanstalk.  I have no problem doing this with Spring Boot on Elastic Beanstalk.

But when I try to use Spring Cloud AWS, I encounter a myriad of problems.  The reference guide never mentions that running on Beanstalk is possible, so perhaps I am barking up the wrong tree?

The root problem I seem to encounter is the stackResourceRegistryFactoryBean blowing up when trying to identify the "stack" being used - i.e. the CloudFormation stack.  But I'm using Elastic Beanstalk, not CloudFormation.  The root exception is:

```<code>Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cloud.aws.core.env.stack.config.StackResourceRegistryFactoryBean]: Factory method 'stackResourceRegistryFactoryBean' threw exception; nested exception is java.lang.IllegalAccessError: tried to access class org.springframework.cloud.aws.core.env.stack.config.AutoDetectingStackNameProvider from class org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration$StackAutoDetectConfiguration
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 89 more
Caused by: java.lang.IllegalAccessError: tried to access class org.springframework.cloud.aws.core.env.stack.config.AutoDetectingStackNameProvider from class org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration$StackAutoDetectConfiguration
    at org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration$StackAutoDetectConfiguration.stackResourceRegistryFactoryBean(ContextStackAutoConfiguration.java:71)
    at org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration$StackAutoDetectConfiguration$$EnhancerBySpringCGLIB$$432c7658.CGLIB$stackResourceRegistryFactoryBean$0(<generated>)
    at org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration$StackAutoDetectConfiguration$$EnhancerBySpringCGLIB$$432c7658$$FastClassBySpringCGLIB$$47c6e7d2.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    ...
</code>```

There are tags present on the generated EC2 instance for "aws:cloudformation:stack-id" and "aws:cloudformation:stack-name" if it is relevant, and my understanding is that Beanstalk uses CloudFormation stacks behind the scenes.  I've tried manually specifying the name of the stack via @EnableStackConfiguration, but since the name is generated I'd rather not do this, even if it did work.

So my questions are:
1) Is it possible to run a Spring Cloud AWS-based application on Elastic Beanstalk?
2) If so, are there any special steps required?  For example, I already discovered the one about CloudFormation read access being required on the role.
3) Is there a way to disable the part of Spring Cloud AWS that attempts to obtain resource names from the stack?  At this point my app doesn't need this.

thanks in advance,
k

答:
Ok, so over time I've answered my own questions on this topic.

First, Elastic Beanstalk uses CloudFormation behind the scenes, so this is why there is a "stack".

Next, Spring Cloud AWS tries to make connections to DBs and such easier by binding to other resources that may have been created in the same stack.  This is reasonable - if you are expecting it.  If not, as @barthand says, it is probably better to turn this feature off with cloud.aws.stack.auto=false than have the app fail to start up.

Third, When using Elastic Beanstalk, you have the opportunity to associate an execution role with your instance - otherwise the code in your instance isn't able to do much of anything with the AWS SDK.  To explore the resources in a CloudFormation stack, Spring Cloud AWS tries to make some API calls, and by default these are not allowed.  To make them allowed, I added these permissions to the role:

```<code>"Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "cloudformation:DescribeStacks",
            "cloudformation:DescribeStackEvents",
            "cloudformation:DescribeStackResource",
            "cloudformation:DescribeStackResources",
            "cloudformation:GetTemplate",
            "cloudformation:List*"
        ],
        "Resource": "*"
    }
]
</code>```

So to answer my original questions:

Yes it is definitely possible (and easy!) to run a Spring Cloud AWS
program in Elastic Beanstalk.

Special requirements - Need to open the permissions on the associated role to include CloudFormation read operations, or...

Disable these using cloud.aws.stack.auto=false

Hope this info helps someone in the future

Body:
I'm trying to run a web application of "hello world" complexity on Elastic Beanstalk.  I have no problem doing this with Spring Boot on Elastic Beanstalk.

But when I try to use Spring Cloud AWS, I encounter a myriad of problems.  The reference guide never mentions that running on Beanstalk is possible, so perhaps I am barking up the wrong tree?

The root problem I seem to encounter is the stackResourceRegistryFactoryBean blowing up when trying to identify the "stack" being used - i.e. the CloudFormation stack.  But I'm using Elastic Beanstalk, not CloudFormation.  The root exception is:

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cloud.aws.core.env.stack.config.StackResourceRegistryFactoryBean]: Factory method 'stackResourceRegistryFactoryBean' threw exception; nested exception is java.lang.IllegalAccessError: tried to access class org.springframework.cloud.aws.core.env.stack.config.AutoDetectingStackNameProvider from class org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration$StackAutoDetectConfiguration
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 89 more
Caused by: java.lang.IllegalAccessError: tried to access class org.springframework.cloud.aws.core.env.stack.config.AutoDetectingStackNameProvider from class org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration$StackAutoDetectConfiguration
    at org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration$StackAutoDetectConfiguration.stackResourceRegistryFactoryBean(ContextStackAutoConfiguration.java:71)
    at org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration$StackAutoDetectConfiguration$$EnhancerBySpringCGLIB$$432c7658.CGLIB$stackResourceRegistryFactoryBean$0(<generated>)
    at org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration$StackAutoDetectConfiguration$$EnhancerBySpringCGLIB$$432c7658$$FastClassBySpringCGLIB$$47c6e7d2.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    ...

There are tags present on the generated EC2 instance for "aws:cloudformation:stack-id" and "aws:cloudformation:stack-name" if it is relevant, and my understanding is that Beanstalk uses CloudFormation stacks behind the scenes.  I've tried manually specifying the name of the stack via @EnableStackConfiguration, but since the name is generated I'd rather not do this, even if it did work.

So my questions are:
1) Is it possible to run a Spring Cloud AWS-based application on Elastic Beanstalk?
2) If so, are there any special steps required?  For example, I already discovered the one about CloudFormation read access being required on the role.
3) Is there a way to disable the part of Spring Cloud AWS that attempts to obtain resource names from the stack?  At this point my app doesn't need this.

thanks in advance,
k

Body:
Ok, so over time I've answered my own questions on this topic.

First, Elastic Beanstalk uses CloudFormation behind the scenes, so this is why there is a "stack".

Next, Spring Cloud AWS tries to make connections to DBs and such easier by binding to other resources that may have been created in the same stack.  This is reasonable - if you are expecting it.  If not, as @barthand says, it is probably better to turn this feature off with cloud.aws.stack.auto=false than have the app fail to start up.

Third, When using Elastic Beanstalk, you have the opportunity to associate an execution role with your instance - otherwise the code in your instance isn't able to do much of anything with the AWS SDK.  To explore the resources in a CloudFormation stack, Spring Cloud AWS tries to make some API calls, and by default these are not allowed.  To make them allowed, I added these permissions to the role:

"Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "cloudformation:DescribeStacks",
            "cloudformation:DescribeStackEvents",
            "cloudformation:DescribeStackResource",
            "cloudformation:DescribeStackResources",
            "cloudformation:GetTemplate",
            "cloudformation:List*"
        ],
        "Resource": "*"
    }
]

So to answer my original questions:

Yes it is definitely possible (and easy!) to run a Spring Cloud AWS
program in Elastic Beanstalk.

Special requirements - Need to open the permissions on the associated role to include CloudFormation read operations, or...

Disable these using cloud.aws.stack.auto=false

Hope this info helps someone in the future


问:
How to improve doctrine performance (plain sql is 4x faster)?
The problem is next - I want to execute simple query (e.g. 10 rows from one table)

In Doctrine this operation takes 0.013752s

Here is DQL:

```<code>$q = Doctrine_Query::create()
    ->update('TABLE')
    ->set('FIELD', 1)
    ->where('ID = ?', $id);
$rows = $q->execute();
</code>```

But when i use plain sql and mysql_query() it takes only 0.003298s

What's wrong? Is Doctrine realy 4x slower?

答:
John,

Nothing is wrong. Doctrine introduces considerable overhead compared to a straight SQL query. But you gain the convenience of a nice object oriented interface to the database as well as many other benefits. If raw performance is really important then you might not want to use Doctrine.
For queries where I need performance over convenience (hundreds of thousands of inserts for example) I use PDO to avoid the overhead that gets introduced by the ORM.

ContentLicense: CC BY-SA 2.5

Body:
The problem is next - I want to execute simple query (e.g. 10 rows from one table)

In Doctrine this operation takes 0.013752s

Here is DQL:

$q = Doctrine_Query::create()
    ->update('TABLE')
    ->set('FIELD', 1)
    ->where('ID = ?', $id);
$rows = $q->execute();

But when i use plain sql and mysql_query() it takes only 0.003298s

What's wrong? Is Doctrine realy 4x slower?


问:
rvm installation not working: "RVM is not a function"
I just installed RVM, but can't make it work. I have such line at the end of my .profile file:

```<code>[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm"
</code>```

I tried to run source .profile and restarting terminal, but still, when I run rvm use 1.9.2 I'm getting:

```<code>RVM is not a function, selecting rubies with 'rvm use ...' will not work.
</code>```

My system is Ubuntu 11.10.

答:
I fixed it by adding this line to .bash_profile:</p>

```<code>[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
</code>```

Body:
I just installed RVM, but can't make it work. I have such line at the end of my .profile file:

[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm"

I tried to run source .profile and restarting terminal, but still, when I run rvm use 1.9.2 I'm getting:

RVM is not a function, selecting rubies with 'rvm use ...' will not work.

My system is Ubuntu 11.10.

Body:
I fixed it by adding this line to .bash_profile:

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*


问:
How to set OneNote API´s permissions
I Need to use OneNote API in order to get pages by searching specific words in their content with search attribute.

I have made a successful connection to Microsoft Graph, but it doesn´t have support to search words in pages´s content.

In order to get the access token I am using https://login.microsoftonline.com as endpoint url.

As I said I already did a successful connection to Microsoft Graph with the following request : https://login.microsoftonline.com/common/oauth2/v2.0/authorize?scope=Notes.ReadWrite.All+openid+email+profile+offline_access&client_id=4e3c319

with that I got the accesstoken and I was able to get pages using https://graph.microsoft.com/v1.0/me/onenote/pages, but I need to get pages by searching words in their content, so I am trying with onenote api that has search attribute.

If I try with https://www.onenote.com/api/v1.0/me/notes/pages I get Unauthorized error.

I have added onenote api´s scopes : office.onenote_update, office.onenote, etchttps://login.microsoftonline.com/common/oauth2/v2.0/authorize?scope=office.onenote_update+openid+email+profile

But : I got this issue

How can I set the correct scopes for onenote api but using https://login.microsoftonline.com as I did with Microsoft Graph because I need to use that oauth endpoint

答:
https://github.com/microsoftgraph/microsoft-graph-docs/blob/master/api-reference/beta/api/page_get.md

You're using the SCOPES for OneNote API - Graph API has a different set of scopes.

You should use something like Notes.ReadWrite.All.

Title: How to set OneNote API´s permissions


问:
Better way to structure/new keyword
Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently.  I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation.  Essentially it uses a for loop to provide a kind of structured goto.  My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.

ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.

Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses

```<code>boolean valid = false;

// this loop never loops
for (;;)
{
    if (!condition1)
        break;

    condition2.setup();

    if (!condition2)
        break;

    condition3.setup();

    if (!condition3)
        break;

    valid = true;
    break;
}

if (valid) dosomething();
</code>```

EDIT:

I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.

The restructured code looks like this.

```<code>boolean valid = false;

breakout:
{
    if (!condition1)
        break breakout;

    condition2.setup();

    if (!condition2)
        break breakout;

    condition3.setup();

    if (!condition3)
        break breakout;

    valid = true;
}

if (valid) dosomething();
</code>```

Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?

答:
You may have heard of these things modern programming languages have, called functions ;)
One of the key reasons goto is no longer used is that we can now factor code out into separate functions, and call them instead.

One way to solve your problem would be to put the code in a separate function instead, and return instead of breaking from your pseudo-loop:

```<code>void safedosomething() {
    if (!condition1)
        return;

    condition2.setup();

    if (!condition2)
        return;

    condition3.setup();

    if (!condition3)
        return;

    dosomething();
}
</code>```

or write helper functions (such as bool checkcondition1() { condition1.setup(); return condition1; }) which set up and then test the conditions, and use a boolean flag:

```<code>bool valid = true;

if (!checkcondition1())
    valid = false;

if (!checkcondition2())
    valid = false;

if (!checkcondition3())
    valid = false;

if (!checkcondition4())
    valid = false;

if (valid) dosomething();
</code>```

or a bit more concisely:

```<code>bool valid = true;

valid &&= checkcondition1();
valid &&= checkcondition2();
valid &&= checkcondition3();
valid &&= checkcondition4();

if (valid) dosomething();
</code>```

or just

```<code>if (checkcondition1()
  && checkcondition2()
  && checkcondition3()
  && checkcondition4())
    dosomething();
</code>```

There are plenty of ways to express this, without counterintuitive loops-that-don't-loop.

Title: Better way to structure/new keyword

Body:
Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently.  I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation.  Essentially it uses a for loop to provide a kind of structured goto.  My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.

ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.

Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses

boolean valid = false;

// this loop never loops
for (;;)
{
    if (!condition1)
        break;

    condition2.setup();

    if (!condition2)
        break;

    condition3.setup();

    if (!condition3)
        break;

    valid = true;
    break;
}

if (valid) dosomething();

EDIT:

I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.

The restructured code looks like this.

boolean valid = false;

breakout:
{
    if (!condition1)
        break breakout;

    condition2.setup();

    if (!condition2)
        break breakout;

    condition3.setup();

    if (!condition3)
        break breakout;

    valid = true;
}

if (valid) dosomething();

Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?

Body:
You may have heard of these things modern programming languages have, called functions ;)
One of the key reasons goto is no longer used is that we can now factor code out into separate functions, and call them instead.

One way to solve your problem would be to put the code in a separate function instead, and return instead of breaking from your pseudo-loop:

void safedosomething() {
    if (!condition1)
        return;

    condition2.setup();

    if (!condition2)
        return;

    condition3.setup();

    if (!condition3)
        return;

    dosomething();
}

or write helper functions (such as bool checkcondition1() { condition1.setup(); return condition1; }) which set up and then test the conditions, and use a boolean flag:

bool valid = true;

if (!checkcondition1())
    valid = false;

if (!checkcondition2())
    valid = false;

if (!checkcondition3())
    valid = false;

if (!checkcondition4())
    valid = false;

if (valid) dosomething();

or a bit more concisely:

bool valid = true;

valid &&= checkcondition1();
valid &&= checkcondition2();
valid &&= checkcondition3();
valid &&= checkcondition4();

if (valid) dosomething();

or just

if (checkcondition1()
  && checkcondition2()
  && checkcondition3()
  && checkcondition4())
    dosomething();

There are plenty of ways to express this, without counterintuitive loops-that-don't-loop.


问:
Get Device Properties using Xamarin Forms?
i'm designing a cross platform app using xamarin forms.
every page/view/Form designed from code behind. now i want to read Height and Width of the device used by user. based on those values, i want to place some header and footers.</p>

答:
I do this in my viewmodel and it works great.  You could do the same in your code-behind.

```<code>public SomeViewModel
{
    private double width;
    private double Width
    {
        get { return width; }
        set
        {
            width = value;
            if (value != 0 && value != -1)
            {
                // device width found, set other properties
                SetProperties();
            }
        }
    }

    void SetProperties()
    {
        // use value of Width however you need
    }

    public SomeViewModel()
    {
         Width = Application.Current.MainPage.Width;
         var fireAndForget = Task.Run(GetWidthAsync);
    }

    public async Task GetWidthAsync()
    {
        while (Width == -1 || Width == 0)
        {
            await Task.Delay(TimeSpan.FromMilliseconds(1)).ConfigureAwait(false);
            // MainPage is the page that is using this ViewModel
            Width = Application.Current.MainPage.Width;
        }
    }
}
</code>```

If you want to display Width in a label in your form for testing purposes using binding, don't forget to change the property from private to public.

Body:
I do this in my viewmodel and it works great.  You could do the same in your code-behind.

public SomeViewModel
{
    private double width;
    private double Width
    {
        get { return width; }
        set
        {
            width = value;
            if (value != 0 && value != -1)
            {
                // device width found, set other properties
                SetProperties();
            }
        }
    }

    void SetProperties()
    {
        // use value of Width however you need
    }

    public SomeViewModel()
    {
         Width = Application.Current.MainPage.Width;
         var fireAndForget = Task.Run(GetWidthAsync);
    }

    public async Task GetWidthAsync()
    {
        while (Width == -1 || Width == 0)
        {
            await Task.Delay(TimeSpan.FromMilliseconds(1)).ConfigureAwait(false);
            // MainPage is the page that is using this ViewModel
            Width = Application.Current.MainPage.Width;
        }
    }
}

If you want to display Width in a label in your form for testing purposes using binding, don't forget to change the property from private to public.


问:
unix - how to sort on a specific key
How do I sort this output?

```<code>10.1.3.39:{ "range_start" : 96, "range_end" : 96 }
10.1.3.27:{ "range_start" : 33, "range_end" : 33 }
10.1.3.100:{ range_start" : 30, "range_end" : 30 }
10.1.2.233:{ "range_start" : 78, "range_end" : 78 }
10.1.4.239:{ "range_start" : 53, "range_end" : 53 }
10.1.2.161:{ "range_start" : 44, "range_end" : 44 }
</code>```

I want to sort this output by the range_start key

So, expected would be:

```<code>10.1.3.100:{ "range_start" : 30, "range_end" : 30 }
10.1.3.27:{ "range_start" : 33, "range_end" : 33 }
10.1.2.161:{ "range_start" : 44, "range_end" : 44 }
10.1.4.239:{ "range_start" : 53, "range_end" : 53 }
10.1.2.233:{ "range_start" : 78, "range_end" : 78 }
10.1.3.39:{ "range_start" : 96, "range_end" : 96 }
</code>```

答:
Here we have a JSON-like format, not a column-formatted text, yet we can get by sorting just by a field value separated by spaces:

```<code>sort -n -k 4,4
</code>```

Would produce the desired output.

However using a parser that is aware of the format would help in many cases.
For instance, the solution with sort would fail if the keys and values were not consistently separated by spaces, e.g.

```<code>0.1.3.100:{ range_start":30, "range_end" : 30 }
</code>```

or if the order of the entries was not consistent, e.g.

```<code>0.1.2.233:{ "range_end" : 108, "range_start" : 78 }
10.1.3.39:{ "range_start" : 96, "range_end" : 96 }
</code>```

Title: unix - how to sort on a specific key

Body:
How do I sort this output?

10.1.3.39:{ "range_start" : 96, "range_end" : 96 }
10.1.3.27:{ "range_start" : 33, "range_end" : 33 }
10.1.3.100:{ range_start" : 30, "range_end" : 30 }
10.1.2.233:{ "range_start" : 78, "range_end" : 78 }
10.1.4.239:{ "range_start" : 53, "range_end" : 53 }
10.1.2.161:{ "range_start" : 44, "range_end" : 44 }

I want to sort this output by the range_start key

So, expected would be:

10.1.3.100:{ "range_start" : 30, "range_end" : 30 }
10.1.3.27:{ "range_start" : 33, "range_end" : 33 }
10.1.2.161:{ "range_start" : 44, "range_end" : 44 }
10.1.4.239:{ "range_start" : 53, "range_end" : 53 }
10.1.2.233:{ "range_start" : 78, "range_end" : 78 }
10.1.3.39:{ "range_start" : 96, "range_end" : 96 }

Body:
Here we have a JSON-like format, not a column-formatted text, yet we can get by sorting just by a field value separated by spaces:

sort -n -k 4,4

Would produce the desired output.

However using a parser that is aware of the format would help in many cases.
For instance, the solution with sort would fail if the keys and values were not consistently separated by spaces, e.g.

0.1.3.100:{ range_start":30, "range_end" : 30 }

or if the order of the entries was not consistent, e.g.

0.1.2.233:{ "range_end" : 108, "range_start" : 78 }
10.1.3.39:{ "range_start" : 96, "range_end" : 96 }


问:
Issues with changing text in access 2013 report
I have made changes to text in a sentence in a report.
The changes display correctly in Design View and also in Layout View, but when I display it in print preview the previous text is displayed, not the new amended text. If I then go back to Layout view, it now displays the original text just like print preview did. The display in Design shows the new amended text.

I am using access 2013 on a *.accdb database which I was given by the previous user.  Any ideas why this is happening?
I would imagine that it something to do with my print preview?

答:
Most probably there is VBA code behind the report that changes the text, e.g. in an OnFormat event that only runs in Print preview.

Open Design view, open the report's code module, and search for the text you see in Print preview.


问:
Calling functions from .dll class and connecting it with my custom class C#
I have a library (not mine) that I use for meshes in C# and this library is compiled in .dll. So I do not have access to code inside.

However I wrote my custom static class, that is full of helper functions to that library.

I just noticed that every single function is written like this:

```<code>public static class MeshUtilities{

 public static functionA (Mesh mesh, some other variable)
 { ... }

 public static functionB (Mesh mesh, some other variable)
 { ... }

 public static functionC (Mesh mesh, some other variable)
 { ... }

}
</code>```

In my application I call those functions as MeshUtilities.function(mesh, some other variable)

But as you see every single function starts from type Mesh mesh.

Is there any way that I could write this helper class in such a way that I would only need to write mesh.FunctionFromMyCustomHelperClass(some other variables) ?

答:
Unless I very much misunderstand your last paragraph, that's an extension method. Add this before the first parameter's type:

```<code>public static class MeshUtilities{

     public static void functionA (this Mesh mesh, object someOtherVariable)
     {
         mesh.SomeOtherMethod(baz.foobar());
         //  etc.
     }
</code>```

And use like so:

```<code>var mesh = new Mesh();

mesh.functionA(3);
</code>```

Body:
I have a library (not mine) that I use for meshes in C# and this library is compiled in .dll. So I do not have access to code inside.

However I wrote my custom static class, that is full of helper functions to that library.

I just noticed that every single function is written like this:

public static class MeshUtilities{

 public static functionA (Mesh mesh, some other variable)
 { ... }

 public static functionB (Mesh mesh, some other variable)
 { ... }

 public static functionC (Mesh mesh, some other variable)
 { ... }

}

In my application I call those functions as MeshUtilities.function(mesh, some other variable)

But as you see every single function starts from type Mesh mesh.

Is there any way that I could write this helper class in such a way that I would only need to write mesh.FunctionFromMyCustomHelperClass(some other variables) ?

Body:
Unless I very much misunderstand your last paragraph, that's an extension method. Add this before the first parameter's type:

public static class MeshUtilities{

     public static void functionA (this Mesh mesh, object someOtherVariable)
     {
         mesh.SomeOtherMethod(baz.foobar());
         //  etc.
     }

And use like so:

var mesh = new Mesh();

mesh.functionA(3);


问:
Setting user rights assignment of local security policy using powershell/cmd
I want to edit security settings of user rights assignment of local security policy using powershell or cmd.

```<code>Eg: policy =  "change the system time"
default_security_settings = "local service,Administrators"
i want to remove everything except Administrators
</code>```

i have tried ntrights command, but seems like not working
Any command will be appreciated

答:
Here is something i just wrote. You can make it more dynamic </p>

```<code>function Replace-SecurityTest([string[]]$Usernames,[string]$SecuritySetting, $SaveFile = "C:\Configuration.cfg"){
    function Get-SID($USER){
        $objUser = New-Object System.Security.Principal.NTAccount("$USER")
        $strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
        $strSID.Value
    }
    secedit /export /cfg $SaveFile
    $reader = [System.IO.File]::OpenText($SaveFile)
    while($null -ne ($line = $reader.ReadLine())) {
        if ($Line -like "*$SecuritySetting*"){
            $reader.Close()
            $line2 = $line.Remove($line.IndexOf("="))
            $line2 += "= "
            foreach($user in $Usernames){
                $line2 += "*$(Get-SID -USER "$user"), "
            }
            $line2 = $line2.Remove($line2.LastIndexOf(", "))
            (gc $SaveFile).replace("$Line", "$Line2") | Out-File $SaveFile
            secedit /configure /db c:\windows\security\local.sdb /cfg $SaveFile /areas SECURITYPOLICY
            rm -force $SaveFile -confirm:$false
            break
        }
    }

}

Replace-SecurityTest -Usernames "Administrators" -SecuritySetting "SeSystemtimePrivilege" -SaveFile "C:\Config22.cfg"
</code>```

Body:
I want to edit security settings of user rights assignment of local security policy using powershell or cmd.

Eg: policy =  "change the system time"
default_security_settings = "local service,Administrators"
i want to remove everything except Administrators

i have tried ntrights command, but seems like not working
Any command will be appreciated

Body:
Here is something i just wrote. You can make it more dynamic

function Replace-SecurityTest([string[]]$Usernames,[string]$SecuritySetting, $SaveFile = "C:\Configuration.cfg"){
    function Get-SID($USER){
        $objUser = New-Object System.Security.Principal.NTAccount("$USER")
        $strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
        $strSID.Value
    }
    secedit /export /cfg $SaveFile
    $reader = [System.IO.File]::OpenText($SaveFile)
    while($null -ne ($line = $reader.ReadLine())) {
        if ($Line -like "*$SecuritySetting*"){
            $reader.Close()
            $line2 = $line.Remove($line.IndexOf("="))
            $line2 += "= "
            foreach($user in $Usernames){
                $line2 += "*$(Get-SID -USER "$user"), "
            }
            $line2 = $line2.Remove($line2.LastIndexOf(", "))
            (gc $SaveFile).replace("$Line", "$Line2") | Out-File $SaveFile
            secedit /configure /db c:\windows\security\local.sdb /cfg $SaveFile /areas SECURITYPOLICY
            rm -force $SaveFile -confirm:$false
            break
        }
    }

}

Replace-SecurityTest -Usernames "Administrators" -SecuritySetting "SeSystemtimePrivilege" -SaveFile "C:\Config22.cfg"


问:
PhoneGap Build App Expiring Provisioning Profile
I have an "in house" hybrid app built with PhoneGap that is distributed via direct link so it does not use the App Store.  The iOS provisioning profile is expiring soon but the certificate is good until next year.  I already went into my Apple Developer account, edited the expiring provisioning profile and then clicked "Generate" to update expiration date to a year from now - so the provisioning profile itself is now updated.  I have also tested on an iPad by changing the system date past the previous expiration date but before the new expiration date and the app still works; however, when I change the date past the new expiration date it no longer works as expected with the message: "App Name" is No Longer Available.

My question is: Do I need to rebuild the PhoneGap app with the provisioning profile that now has an updated date and the then redistribute to all (hundreds) users or will it continue working without an update now that the provisioning profile date is updated?

In my testing, it seems the app does not need to be rebuilt with the updated provisioning profile date but I am having a hard time getting a clear answer on this.

Additional Information:

Adjusting the iPad system time more than 70 days past the previous expiration date no longer allows the app to be installed.

答:
Running an app on an iOS device simply requires that there is a valid provisioning profile on the device when you launch the app. If your app is the only one ever installed on the device (meaning the old provisioning profile is the only one that's been installed on the device), when you hit the expiration date, the app will not lunch again.

You have a few options. All of them will require the new provisioning profile to be installed on the device.

First, you can rebuild the app with the new provisioning profile and install the new build of the app on your devices.

Second, if you have access to the devices, you can manually install the new provisioning profile on the devices through Xcode. This can be done through the devices window in Xcode. This will not require you to rebuild and reinstall the app.

Third, if these devices are managed with an MDM system, you can push the new provisioning profile to the devices using your MDM provider.

A fourth option, which would only work if you're using a wildcard identifier in the provisioning profile, would be to install another app with the new provision profile on it. This will allow the profile to be installed on the device, without having to rebuild the original app.


问:
Setting NSScrollView Contents to Top Left Instead of Bottom Left When Document Swapping
I had one of my colleagues come to me today with a problem of how can he load or view-swap a documentView of an NSScrollView so that the loaded view appears to fix to the top-left corner instead of the bottom-let corner.

He had spent a while searching the web and floundering and didn't have a solution despite reading the documentation at Apple, on StackOverflow and various other places.

Here's the issue piece-by-piece:

In Interface Builder drag an NSScrollView into the project.
Also in Interface Builder drag two custom views into the project and add some textfields, buttons etc.

Create a controller class (e.g. myController) with the following IBOutlets:

IBOutlet NSScrollView * myScrollView

IBOutlet NSView * myCustomView1

IBOutlet NSView * myCustomView2

Connect the outlets to the controls in Interface Builder.

Create an NSView subclass to flip the documentView:

```<code>@implementation myFlippedView

-(id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
    }
    return self;
}

-(void)drawRect:(NSRect)dirtyRect {
    // Drawing code here.
}

-(BOOL)isFlipped {
    return YES;
}
</code>```

Select the documentViewof the NSScrollView in Interface Builder and make it a subclass of myFlippedView. In Interface Builder you would select the NSScrollView and then click in it again to get to the documentView, or change the IB Library to show a tree view and select the child custom view of the NSScrollView.

In the myController class swap the views with the following methods:

```<code>-(void)awakeFromNib {

    [myScrollView setDocumentView:myCustomView1];
}

-(IBAction)swapViews:(id)sender {

    if ([myScrollView documentView] == myCustomView1) {

        [myScrollView setDocumentView:myCustomView2];

    } else {

        [myScrollView setDocumentView:myCustomView1];

    }
}
</code>```

Finally hook up a button in your project to the action swapViews, build and run.

The problem is that the coordinates were not being resolved as was expected with the isFlipped.

答:
To correctly make the documentView initially align to the top of the scrollview AND to also pin it to the top when the documentView is smaller than it's clipview, this is what works for me:

1 – In Interface Builder enclose all controls in your documentView in a custom NSView instance. (NOT a flipped view)

2 – Create an NSView subclass to be used for the documentView, and override these methods:

```<code>- (BOOL)isFlipped {
    return YES;
}
- (void)resizeWithOldSuperviewSize:(NSSize)oldSize {
CGFloat superViewHeight = self.superview.frame.size.height, height = self.frame.size.height;
    if(superViewHeight>height) {
        [self setFrameOrigin:NSMakePoint(self.frame.origin.x, superViewHeight-height)];
    }
}
</code>```

The subclassed view should be the scrollViews' documentView which contains second (normal) NSView that contains all controls.

Body:
I had one of my colleagues come to me today with a problem of how can he load or view-swap a documentView of an NSScrollView so that the loaded view appears to fix to the top-left corner instead of the bottom-let corner.

He had spent a while searching the web and floundering and didn't have a solution despite reading the documentation at Apple, on StackOverflow and various other places.

Here's the issue piece-by-piece:

In Interface Builder drag an NSScrollView into the project.
Also in Interface Builder drag two custom views into the project and add some textfields, buttons etc.

Create a controller class (e.g. myController) with the following IBOutlets:

IBOutlet NSScrollView * myScrollView

IBOutlet NSView * myCustomView1

IBOutlet NSView * myCustomView2

Connect the outlets to the controls in Interface Builder.

Create an NSView subclass to flip the documentView:

@implementation myFlippedView

-(id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
    }
    return self;
}

-(void)drawRect:(NSRect)dirtyRect {
    // Drawing code here.
}

-(BOOL)isFlipped {
    return YES;
}

Select the documentViewof the NSScrollView in Interface Builder and make it a subclass of myFlippedView. In Interface Builder you would select the NSScrollView and then click in it again to get to the documentView, or change the IB Library to show a tree view and select the child custom view of the NSScrollView.

In the myController class swap the views with the following methods:

-(void)awakeFromNib {

    [myScrollView setDocumentView:myCustomView1];
}

-(IBAction)swapViews:(id)sender {

    if ([myScrollView documentView] == myCustomView1) {

        [myScrollView setDocumentView:myCustomView2];

    } else {

        [myScrollView setDocumentView:myCustomView1];

    }
}

Finally hook up a button in your project to the action swapViews, build and run.

The problem is that the coordinates were not being resolved as was expected with the isFlipped.

Body:
To correctly make the documentView initially align to the top of the scrollview AND to also pin it to the top when the documentView is smaller than it's clipview, this is what works for me:

1 – In Interface Builder enclose all controls in your documentView in a custom NSView instance. (NOT a flipped view)

2 – Create an NSView subclass to be used for the documentView, and override these methods:

- (BOOL)isFlipped {
    return YES;
}
- (void)resizeWithOldSuperviewSize:(NSSize)oldSize {
CGFloat superViewHeight = self.superview.frame.size.height, height = self.frame.size.height;
    if(superViewHeight>height) {
        [self setFrameOrigin:NSMakePoint(self.frame.origin.x, superViewHeight-height)];
    }
}

The subclassed view should be the scrollViews' documentView which contains second (normal) NSView that contains all controls.


问:
React - render() not called with setState with axios
I am trying to fetch an array of movies and after it fetches the list it updates the state and the list should render, but the problem is the render method never calls from inside the axios callback, here is my code below

```<code>export default class Movies extends Component {
    constructor(props){
      super(props);

      this.state={movies:[]};
    }

    componentDidMount(){

      axios.get('URL')
            .then(response => {
              this.setState({movies:response.data});
              console.log("Movies",this.state);// I get the values here see screenshot..

      });
  }

  render(){
    return(
      <div className="row">
        <div className="col-md-3">
          <MovieList movies={this.state.movies}/>
        </div>
        <div className="col-md-6">Movie Details</div>
      </div>
    );
  }
}
</code>```

As you can see the code above, in function componentDidMount in the axios callback I am setting the response values to the state, but it doesn't call the render after doing it, the block does execute well as I get the log properly see screenshot below

I am not understanding why it doesn't call render() ? I have tried couple of solutions available but none works for me, if I hardcode the videos array in default state it works fine, please help if anyone know the solution.

Update(Adding MovieList Code)

```<code>class ListItem extends Component {
  render(){
    return(
      <li className="list-group-item">{this.props.moviename}</li>
    );
  }
}

export default class MoviesList extends Component {
  constructor(props) {
    super(props);
    console.log("Props",props);
    this.state={movies:props.movies};
  }

  renderList(){

    const items=this.state.movies.map((movie) => <ListItem moviename={movie.name} key={movie.name}/>);

    return items;
  }

  render(){
    return(
      <ul className="list-group">
        <li className="list-group-item"><h3>Movies</h3></li>
        {this.renderList()}
      </ul>
    );
  }
}
</code>```

Thanks.

答:
You should consider making your MoviesList stateless:

```<code>export default class MoviesList extends Component {

  constructor(props) {
    super(props);
    console.log("Props",props);
    //If your component won't alter movies list by itself - there's no point to manage its "state"
    //this.state={movies:props.movies};
  }

  renderList(){
    //Use props here instead
    const items=this.props.movies.map((movie) => <ListItem moviename={movie.name} key={movie.name}/>);
    return items;
  }

  render(){
    return(
      <ul className="list-group">
        <li className="list-group-item"><h3>Movies</h3></li>
        {this.renderList()}
      </ul>
    );
  }
}
</code>```

Generally, you should strive to dumbing-down your components whenever possible.

Body:
I am trying to fetch an array of movies and after it fetches the list it updates the state and the list should render, but the problem is the render method never calls from inside the axios callback, here is my code below

export default class Movies extends Component {
    constructor(props){
      super(props);

      this.state={movies:[]};
    }

    componentDidMount(){

      axios.get('URL')
            .then(response => {
              this.setState({movies:response.data});
              console.log("Movies",this.state);// I get the values here see screenshot..

      });
  }

  render(){
    return(

          <MovieList movies={this.state.movies}/>

Movie Details

    );
  }
}

As you can see the code above, in function componentDidMount in the axios callback I am setting the response values to the state, but it doesn't call the render after doing it, the block does execute well as I get the log properly see screenshot below

I am not understanding why it doesn't call render() ? I have tried couple of solutions available but none works for me, if I hardcode the videos array in default state it works fine, please help if anyone know the solution.

Update(Adding MovieList Code)

class ListItem extends Component {
  render(){
    return(

{this.props.moviename}

    );
  }
}

export default class MoviesList extends Component {
  constructor(props) {
    super(props);
    console.log("Props",props);
    this.state={movies:props.movies};
  }

  renderList(){

    const items=this.state.movies.map((movie) => <ListItem moviename={movie.name} key={movie.name}/>);

    return items;
  }

  render(){
    return(

Movies

        {this.renderList()}

    );
  }
}

Thanks.

Body:
You should consider making your MoviesList stateless:

export default class MoviesList extends Component {

  constructor(props) {
    super(props);
    console.log("Props",props);
    //If your component won't alter movies list by itself - there's no point to manage its "state"
    //this.state={movies:props.movies};
  }

  renderList(){
    //Use props here instead
    const items=this.props.movies.map((movie) => <ListItem moviename={movie.name} key={movie.name}/>);
    return items;
  }

  render(){
    return(
      <ul className="list-group">
        <li className="list-group-item"><h3>Movies</h3></li>
        {this.renderList()}
      </ul>
    );
  }
}

Generally, you should strive to dumbing-down your components whenever possible.


问:
How to make a chatbot in Golang with dynamic plugins and adapters?
I'm new to Golang and writing a chat bot as an exercise.

Basically I'm using net/http and gorilla/mux to handle requests.

For now it can only talk to one specific chat platform (I call it an adapter) and has only one plugin (find a picture on google).

How can I make both adapters and plugins be dynamic - so other developers can write their own stuff and just use my bot as a base platform? Are there any good examples?

Also should I have all the plugins and adapters in one repo/static binary or should they be separate? I know I can do both ways but what would you recommend as a better way to have easier collaboration and extensibility?

答: Medium post, "Standard Package Layout", by Ben Johnson, helped me think about this.</p>


答:
Why don't you make it an extension class?

```<code>public static class MeshUtilities{

 public static functionA (this Mesh mesh, some other variable)
 { ... }

 public static functionB (this Mesh mesh, some other variable)
 { ... }

 public static functionC (this Mesh mesh, some other variable)
 { ... }

}
</code>```

And call it like this:

```<code>Mesh ourMesh = new Mesh();
ourMesh.functionC(someVariable);
</code>```

Title: Calling functions from .dll class and connecting it with my custom class C#

Body:
Why don't you make it an extension class?

public static class MeshUtilities{

 public static functionA (this Mesh mesh, some other variable)
 { ... }

 public static functionB (this Mesh mesh, some other variable)
 { ... }

 public static functionC (this Mesh mesh, some other variable)
 { ... }

}

And call it like this:

Mesh ourMesh = new Mesh();
ourMesh.functionC(someVariable);


问:
When Android Textview Draw Multi-Line strings, The Layout Redrawn?

This is the code.

```<code>RelativeLayout layout = new RelativeLayout(this);
TextView title = new TextView(this);
title.setGravity(Gravity.CENTER);
title.setWidth(320);
title.setHeight(160)
title.setText("hello");
layout.addView(title);
layout.setOnTouchListener(this);
</code>```

On the Screen, when I move the view location from (x:0, y:0) -> to (x: 200, y:300)

And then set the TextView's value

```<code>title.setText("aaaaabbbbbbccccccdddddddeeeeeeeddddd");
</code>```

the string length > textview's width, so multi-line display

Then occurred error is "the TextView's location is back to (x:0, y:0)"

if the TextView is display SingleLine,  eg: title.setText("aaa"); the TextView's location is (x:200, y:300)

Is the android textView display multi-line strings, the layout is Redrawn? anyone can help me? I've been worried all night!!!

ps: the same error is also happened when call the TextView.bringToFront();

// In Android，if you changed the view location，must be setting layoutparams；otherwise，when the view reDraw，the view will back to location(0,0)。

// the solution is like this：

```<code>                RelativeLayout.LayoutParams lpFeedback = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                lpFeedback.leftMargin = v.getLeft();
                lpFeedback.topMargin = v.getTop();
                lpFeedback.setMargins(v.getLeft(), v.getTop(), 0, 0);
                v.setLayoutParams(lpFeedback);
</code>```

答:
No it doesn't happen like that here is a sample code try this:

```<code>RelativeLayout layout = new RelativeLayout(this);
        RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
        );
        TextView title = new TextView(this);
        RelativeLayout.LayoutParams tvlp = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT
        );
        tvlp.setMargins(200,300,0,0);
        title.setLayoutParams(tvlp);

        title.setGravity(Gravity.CENTER);
        title.setTextColor(Color.WHITE);
        title.setBackgroundColor(Color.GREEN);
        title.setWidth(320);
        title.setHeight(160);
        title.setText("helloaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
        title.setTextSize(22);
        layout.addView(title);
        setContentView(layout, rlp);
</code>```

Hope it helps!!!

Body:
This is the code.

RelativeLayout layout = new RelativeLayout(this);
TextView title = new TextView(this);
title.setGravity(Gravity.CENTER);
title.setWidth(320);
title.setHeight(160)
title.setText("hello");
layout.addView(title);
layout.setOnTouchListener(this);

On the Screen, when I move the view location from (x:0, y:0) -> to (x: 200, y:300)

And then set the TextView's value

title.setText("aaaaabbbbbbccccccdddddddeeeeeeeddddd");

the string length > textview's width, so multi-line display

Then occurred error is "the TextView's location is back to (x:0, y:0)"

if the TextView is display SingleLine,  eg: title.setText("aaa"); the TextView's location is (x:200, y:300)

Is the android textView display multi-line strings, the layout is Redrawn? anyone can help me? I've been worried all night!!!

ps: the same error is also happened when call the TextView.bringToFront();

// In Android，if you changed the view location，must be setting layoutparams；otherwise，when the view reDraw，the view will back to location(0,0)。

// the solution is like this：

                RelativeLayout.LayoutParams lpFeedback = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                lpFeedback.leftMargin = v.getLeft();
                lpFeedback.topMargin = v.getTop();
                lpFeedback.setMargins(v.getLeft(), v.getTop(), 0, 0);
                v.setLayoutParams(lpFeedback);

Body:
No it doesn't happen like that here is a sample code try this:

RelativeLayout layout = new RelativeLayout(this);
        RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
        );
        TextView title = new TextView(this);
        RelativeLayout.LayoutParams tvlp = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT
        );
        tvlp.setMargins(200,300,0,0);
        title.setLayoutParams(tvlp);

        title.setGravity(Gravity.CENTER);
        title.setTextColor(Color.WHITE);
        title.setBackgroundColor(Color.GREEN);
        title.setWidth(320);
        title.setHeight(160);
        title.setText("helloaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
        title.setTextSize(22);
        layout.addView(title);
        setContentView(layout, rlp);

Hope it helps!!!


问:
How to add_filter to the_content after a plugin does it
I have a function that adds a block of html to the top of the_content() wordpress function, however, a wordpress plugin I have also does the same, and it inserts its code ABOVE the block of html I already inserted. But I want my block of html to always be at the top of the_content output.

Is there a way to specify this?

This is my function at the minute (the plugin does it in a similar way, so I assume it's done in order of loading

```<code>function my_function($content){
    global $post;

    $content = $content . my_function($post) ;
    return $content;
}
add_filter( 'the_content', 'my_function', 9 );
</code>```

the plugin uses:

```<code>add_filter( 'the_content', array( &$this, 'the_content' ) );
</code>```

I set mine to priority 9, so surely it would be loaded before the plugin's 10 (default)?

Thanks guys.

答:
I'm not sure if you still need help with this but it might be helpful to other people who find your question.

I set mine to priority 9, so surely it would be loaded before the
  plugin's 10 (default)?

That is correct, but you want your filter to take effect AFTER the plugin's filter. Currently, your filter inserts a block of HTML into the top of the content section. Then, the plugin filter inserts a block of HTML into the top of the content section, above your previously inserted block. So, you should set the $priority filter to a higher value like 20 so that it will occur later and insert the HTML block above all HTML blocks inserted by other filters.

Body:
I have a function that adds a block of html to the top of the_content() wordpress function, however, a wordpress plugin I have also does the same, and it inserts its code ABOVE the block of html I already inserted. But I want my block of html to always be at the top of the_content output.

Is there a way to specify this?

This is my function at the minute (the plugin does it in a similar way, so I assume it's done in order of loading

function my_function($content){
    global $post;

    $content = $content . my_function($post) ;
    return $content;
}
add_filter( 'the_content', 'my_function', 9 );

the plugin uses:

add_filter( 'the_content', array( &$this, 'the_content' ) );

I set mine to priority 9, so surely it would be loaded before the plugin's 10 (default)?

Thanks guys.


问:
Using sum function with when case
```<code>SELECT  '2017-05-30' AS `short_date`,
        'Stats' AS `group`,
        'Active ' AS `subgroup`,
         '' AS `row`,
         CASE
WHEN COUNT(DISTINCT(guild_name)) >= 1 AND  COUNT(DISTINCT(guild_name)) <= 5   THEN '1 - 5 '
WHEN COUNT(DISTINCT(guild_name)) >= 6 AND COUNT(DISTINCT(guild_name)) <= 10  THEN '6 - 10 '
WHEN COUNT(DISTINCT(guild_name)) >= 11 AND COUNT(DISTINCT(guild_name)) <= 15 THEN '11 - 15 '
WHEN COUNT(DISTINCT(guild_name)) >= 16 AND COUNT(DISTINCT(guild_name)) <= 20 THEN '16 - 20 '
WHEN COUNT(DISTINCT(guild_name)) >= 21 AND COUNT(DISTINCT(guild_name)) <= 25 THEN '21 - 25 '
WHEN COUNT(DISTINCT(guild_name)) >= 30 THEN '> 30' END AS `value`
FROM  table
WHERE guild_name !=0
GROUP BY
                `short_date`,
                `group`,
                `subgroup`
</code>```

<p>How not to count a value in each case, how to count it once and use in each case? </p>

答:
How about you move the count to a subquery and move the case outside like this:

```<code>select `short_date`, `group`, `subgroup`, `row`,
CASE
    WHEN nb_guild >= 1 AND nb_guild <= 5   THEN '1 - 5 '
    WHEN nb_guild >= 6 AND nb_guild <= 10  THEN '6 - 10 '
    WHEN nb_guild >= 11 AND nb_guild <= 15 THEN '11 - 15 '
    WHEN nb_guild >= 16 AND nb_guild <= 20 THEN '16 - 20 '
    WHEN nb_guild >= 21 AND nb_guild <= 25 THEN '21 - 25 '
    WHEN nb_guild >= 30 THEN '> 30'
END AS `value`
from
(
    SELECT  '2017-05-30' AS `short_date`,
            'Stats' AS `group`,
            'Active ' AS `subgroup`,
            '' AS `row`,
            COUNT(DISTINCT(guild_name)) as nb_guild
    FROM  table
    WHERE guild_name !=0
    GROUP BY
                    `short_date`,
                    `group`,
                    `subgroup`
) as subquery
</code>```

This way your count only gets executed once in the subquery and your outer query does its treatment on the resulting resultset.

Title: Using sum function with when case

Body:
SELECT  '2017-05-30' AS `short_date`,
        'Stats' AS `group`,
        'Active ' AS `subgroup`,
         '' AS `row`,
         CASE
WHEN COUNT(DISTINCT(guild_name)) >= 1 AND  COUNT(DISTINCT(guild_name)) <= 5   THEN '1 - 5 '
WHEN COUNT(DISTINCT(guild_name)) >= 6 AND COUNT(DISTINCT(guild_name)) <= 10  THEN '6 - 10 '
WHEN COUNT(DISTINCT(guild_name)) >= 11 AND COUNT(DISTINCT(guild_name)) <= 15 THEN '11 - 15 '
WHEN COUNT(DISTINCT(guild_name)) >= 16 AND COUNT(DISTINCT(guild_name)) <= 20 THEN '16 - 20 '
WHEN COUNT(DISTINCT(guild_name)) >= 21 AND COUNT(DISTINCT(guild_name)) <= 25 THEN '21 - 25 '
WHEN COUNT(DISTINCT(guild_name)) >= 30 THEN '> 30' END AS `value`
FROM  table
WHERE guild_name !=0
GROUP BY
                `short_date`,
                `group`,
                `subgroup`

How not to count a value in each case, how to count it once and use in each case?

Body:
How about you move the count to a subquery and move the case outside like this:

select `short_date`, `group`, `subgroup`, `row`,
CASE
    WHEN nb_guild >= 1 AND nb_guild <= 5   THEN '1 - 5 '
    WHEN nb_guild >= 6 AND nb_guild <= 10  THEN '6 - 10 '
    WHEN nb_guild >= 11 AND nb_guild <= 15 THEN '11 - 15 '
    WHEN nb_guild >= 16 AND nb_guild <= 20 THEN '16 - 20 '
    WHEN nb_guild >= 21 AND nb_guild <= 25 THEN '21 - 25 '
    WHEN nb_guild >= 30 THEN '> 30'
END AS `value`
from
(
    SELECT  '2017-05-30' AS `short_date`,
            'Stats' AS `group`,
            'Active ' AS `subgroup`,
            '' AS `row`,
            COUNT(DISTINCT(guild_name)) as nb_guild
    FROM  table
    WHERE guild_name !=0
    GROUP BY
                    `short_date`,
                    `group`,
                    `subgroup`
) as subquery

This way your count only gets executed once in the subquery and your outer query does its treatment on the resulting resultset.


问:
Constructors with variable number of arguments
Using a few extensions, I can do something like this:

```<code>{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}

type family TF (a :: Bool) where
  TF 'True = Int
  TF 'False = Double

data D a where
  D :: TF a -> D a
</code>```

Notice the constructor D can work in two ways. Either:

```<code>D :: Int -> D 'True
</code>```

or

```<code>D :: Double -> D 'False
</code>```

Using this pattern, I can completely change the arguments to the constructor depending on it's type, whilst reusing it's name.

However, I'd also like the number of arguments to depend on it's name.

I know I could just replace some arguments with () or Void but I'd rather remove them entirely.

Is there anyway to do this?

答:
I'm not sure if this is exactly what @luqui had in mind in the comment above, but you can create a smart constructor in a type class that dispatches on the type of its first argument (or any fixed number of initial arguments) to determine the count and types of remaining arguments via a type family:

```<code>{-# LANGUAGE TypeFamilies #-}

data D = Int2 Int Int
       | Double1 Double
       deriving (Show)

class D1 a where
  d :: a -> T2 a
type family T2 a where
  T2 Int = Int -> D
  T2 Double = D

instance D1 Int where
  d x = \y -> Int2 x y     -- or just `d = Int2`
instance D1 Double where
  d x = Double1 x          -- or just `d = Double1`
</code>```

After which:

```<code>> d (2 :: Int) 3
Int2 2 3
> d (2 :: Double)
Double1 2.0
>
</code>```

It's not clear to me how to generalize this to a situation that requires conditional dispatch:

```<code>data D = IntStringDouble Int String Double
       | Int2 Int Int
       | Double1 Double
       deriving (Show)
</code>```

since you'd need something like:

```<code>T2 Int = a -> T3 a
</code>```

with T3 an additional type family for the next step in the dispatch, and I don't think there's any way to have the RHS of a type family be polymorphic.  Maybe someone else can see a way.

Anyway, it's all probably more trouble than it's worth.

Body:
Using a few extensions, I can do something like this:

{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}

type family TF (a :: Bool) where
  TF 'True = Int
  TF 'False = Double

data D a where
  D :: TF a -> D a

Notice the constructor D can work in two ways. Either:

D :: Int -> D 'True

or

D :: Double -> D 'False

Using this pattern, I can completely change the arguments to the constructor depending on it's type, whilst reusing it's name.

However, I'd also like the number of arguments to depend on it's name.

I know I could just replace some arguments with () or Void but I'd rather remove them entirely.

Is there anyway to do this?

Body:
I'm not sure if this is exactly what @luqui had in mind in the comment above, but you can create a smart constructor in a type class that dispatches on the type of its first argument (or any fixed number of initial arguments) to determine the count and types of remaining arguments via a type family:

{-# LANGUAGE TypeFamilies #-}

data D = Int2 Int Int
       | Double1 Double
       deriving (Show)

class D1 a where
  d :: a -> T2 a
type family T2 a where
  T2 Int = Int -> D
  T2 Double = D

instance D1 Int where
  d x = \y -> Int2 x y     -- or just `d = Int2`
instance D1 Double where
  d x = Double1 x          -- or just `d = Double1`

After which:

> d (2 :: Int) 3
Int2 2 3
> d (2 :: Double)
Double1 2.0
>

It's not clear to me how to generalize this to a situation that requires conditional dispatch:

data D = IntStringDouble Int String Double
       | Int2 Int Int
       | Double1 Double
       deriving (Show)

since you'd need something like:

T2 Int = a -> T3 a

with T3 an additional type family for the next step in the dispatch, and I don't think there's any way to have the RHS of a type family be polymorphic.  Maybe someone else can see a way.

Anyway, it's all probably more trouble than it's worth.


问:
Cannot read property '_listenId' of undefined when using listenTo in a view
I am creating a view but it isn't rendering in my page.
I am building a SPA with backbone, and I need that my template can open inside of div in my body, but I don't know what is my problem here.
What can be?

Show this error:

```<code>Uncaught TypeError: Cannot read property '_listenId' of undefined
at child.Events.(anonymous function) [as listenTo] (http://localhost:9000/bower_components/backbone/backbone.js:222:19)
at child.initialize (http://localhost:9000/scripts/views/RepositoriesView.js:21:12)
at child.Backbone.View (http://localhost:9000/bower_components/backbone/backbone.js:1001:21)
at new child (http://localhost:9000/bower_components/backbone/backbone.js:1566:41)
at child.repositories (http://localhost:9000/scripts/routes/AppRouter.js:46:7)
at child.execute (http://localhost:9000/bower_components/backbone/backbone.js:1265:30)
at Object.callback (http://localhost:9000/bower_components/backbone/backbone.js:1254:16)
at http://localhost:9000/bower_components/backbone/backbone.js:1481:19
at Function.some (http://localhost:9000/bower_components/lodash/dist/lodash.compat.js:4304:25)
at Backbone.History.loadUrl (http://localhost:9000/bower_components/backbone/backbone.js:1479:16)
</code>```

My AppRouter is:

```<code>/*global Sice, Backbone*/

Sice.Routers = Sice.Routers || {};
Sice.Views = Sice.Views || {};

(function() {
    'use strict';

    Sice.Routers.AppRouter = Backbone.Router.extend({

        //map url routes to contained methods
        routes: {
            "": "repositories",
            "repositories": "repositories",
            "search": "search",
            "starreds": "starreds"
        },

        deselectPills: function() {
            //deselect all navigation pills
            $('ul.pills li').removeClass('active');
        },

        selectPill: function(pill) {
            //deselect all navigation pills
            this.deselectPills();
            //select passed navigation pill by selector
            $(pill).addClass('active');
        },

        hidePages: function() {
            //hide all pages with 'pages' class
            $('div#content').hide();
        },

        showPage: function(page) {
            //hide all pages
            this.hidePages();
            //show passed page by selector
            $(page).show();
        },

        repositories: function() {
            this.showPage('div#content');
            this.selectPill('li.repositories-pill');
            new Sice.Views.RepositoriesView();
        },

        search: function() {
            this.showPage('div#content');
            this.selectPill('li.search-pill');
        },

        starreds: function() {
            this.showPage('div#content');
            this.selectPill('li.starreds-pill');
        }
    });

    Sice.Views.AppView = Backbone.View.extend({

        //bind view to body element (all views should be bound to DOM elements)
        el: $('body'),

        //observe navigation click events and map to contained methods
        events: {
            'click ul.pills li.repositories-pill a': 'displayRepositories',
            'click ul.pills li.search-pill a': 'displaySearch',
            'click ul.pills li.starreds-pill a': 'displayStarreds'
        },

        //called on instantiation
        initialize: function() {
            //set dependency on Sice.Routers.AppRouter
            this.router = new Sice.Routers.AppRouter();

            //call to begin monitoring uri and route changes
            Backbone.history.start();
        },

        displayRepositories: function() {
            //update url and pass true to execute route method
            this.router.navigate("repositories", true);
        },

        displaySearch: function() {
            //update url and pass true to execute route method
            this.router.navigate("search", true);
        },

        displayStarreds: function() {
            //update url and pass true to execute route method
            this.router.navigate("starreds", true);
        }
    });

    //load application
    new Sice.Views.AppView();
})();
</code>```

My View is:

```<code> /*global Sice, Backbone, JST*/

Sice.Views = Sice.Views || {};

(function() {
    'use strict';

    Sice.Views.RepositoriesView = Backbone.View.extend({
        template: JST['app/scripts/templates/RepositoriesView.ejs'],
        tagName: 'div',
        id: 'repositoriesView',
        className: 'page-repositories',
        events: {},

        initialize: function() {
            this.listenTo(this.model, 'change', this.render);
        },

        render: function() {
            this.$el.html(this.template());
        }
    });
})();
</code>```

答:
What's happening?

In the following router function, you're instantiating a new View instance.

```<code>repositories: function() {
    this.showPage('div#content');
    this.selectPill('li.repositories-pill');
    new Sice.Views.RepositoriesView(); // <-- here
},
</code>```

But you're not passing a model object which the view listens to.

```<code>initialize: function() {
    this.listenTo(this.model, 'change', this.render);
},
</code>```

So it's calling this.listenTo with this.model as undefined.

What's the solution?

Pass a model instance

```<code>new Sice.Views.RepositoriesView({ model: new MyModel() });
</code>```

Create a model instance in the view

```<code>initialize: function() {
    this.model = new MyModel();
    this.listenTo(this.model, 'change', this.render);
},
</code>```

Body:
I am creating a view but it isn't rendering in my page.
I am building a SPA with backbone, and I need that my template can open inside of div in my body, but I don't know what is my problem here.
What can be?

Show this error:

Uncaught TypeError: Cannot read property '_listenId' of undefined
at child.Events.(anonymous function) [as listenTo] (http://localhost:9000/bower_components/backbone/backbone.js:222:19)
at child.initialize (http://localhost:9000/scripts/views/RepositoriesView.js:21:12)
at child.Backbone.View (http://localhost:9000/bower_components/backbone/backbone.js:1001:21)
at new child (http://localhost:9000/bower_components/backbone/backbone.js:1566:41)
at child.repositories (http://localhost:9000/scripts/routes/AppRouter.js:46:7)
at child.execute (http://localhost:9000/bower_components/backbone/backbone.js:1265:30)
at Object.callback (http://localhost:9000/bower_components/backbone/backbone.js:1254:16)
at http://localhost:9000/bower_components/backbone/backbone.js:1481:19
at Function.some (http://localhost:9000/bower_components/lodash/dist/lodash.compat.js:4304:25)
at Backbone.History.loadUrl (http://localhost:9000/bower_components/backbone/backbone.js:1479:16)

My AppRouter is:

/*global Sice, Backbone*/

Sice.Routers = Sice.Routers || {};
Sice.Views = Sice.Views || {};

(function() {
    'use strict';

    Sice.Routers.AppRouter = Backbone.Router.extend({

        //map url routes to contained methods
        routes: {
            "": "repositories",
            "repositories": "repositories",
            "search": "search",
            "starreds": "starreds"
        },

        deselectPills: function() {
            //deselect all navigation pills
            $('ul.pills li').removeClass('active');
        },

        selectPill: function(pill) {
            //deselect all navigation pills
            this.deselectPills();
            //select passed navigation pill by selector
            $(pill).addClass('active');
        },

        hidePages: function() {
            //hide all pages with 'pages' class
            $('div#content').hide();
        },

        showPage: function(page) {
            //hide all pages
            this.hidePages();
            //show passed page by selector
            $(page).show();
        },

        repositories: function() {
            this.showPage('div#content');
            this.selectPill('li.repositories-pill');
            new Sice.Views.RepositoriesView();
        },

        search: function() {
            this.showPage('div#content');
            this.selectPill('li.search-pill');
        },

        starreds: function() {
            this.showPage('div#content');
            this.selectPill('li.starreds-pill');
        }
    });

    Sice.Views.AppView = Backbone.View.extend({

        //bind view to body element (all views should be bound to DOM elements)
        el: $('body'),

        //observe navigation click events and map to contained methods
        events: {
            'click ul.pills li.repositories-pill a': 'displayRepositories',
            'click ul.pills li.search-pill a': 'displaySearch',
            'click ul.pills li.starreds-pill a': 'displayStarreds'
        },

        //called on instantiation
        initialize: function() {
            //set dependency on Sice.Routers.AppRouter
            this.router = new Sice.Routers.AppRouter();

            //call to begin monitoring uri and route changes
            Backbone.history.start();
        },

        displayRepositories: function() {
            //update url and pass true to execute route method
            this.router.navigate("repositories", true);
        },

        displaySearch: function() {
            //update url and pass true to execute route method
            this.router.navigate("search", true);
        },

        displayStarreds: function() {
            //update url and pass true to execute route method
            this.router.navigate("starreds", true);
        }
    });

    //load application
    new Sice.Views.AppView();
})();

My View is:

 /*global Sice, Backbone, JST*/

Sice.Views = Sice.Views || {};

(function() {
    'use strict';

    Sice.Views.RepositoriesView = Backbone.View.extend({
        template: JST['app/scripts/templates/RepositoriesView.ejs'],
        tagName: 'div',
        id: 'repositoriesView',
        className: 'page-repositories',
        events: {},

        initialize: function() {
            this.listenTo(this.model, 'change', this.render);
        },

        render: function() {
            this.$el.html(this.template());
        }
    });
})();

Body:
What's happening?

In the following router function, you're instantiating a new View instance.

repositories: function() {
    this.showPage('div#content');
    this.selectPill('li.repositories-pill');
    new Sice.Views.RepositoriesView(); // <-- here
},

But you're not passing a model object which the view listens to.

initialize: function() {
    this.listenTo(this.model, 'change', this.render);
},

So it's calling this.listenTo with this.model as undefined.

What's the solution?

Pass a model instance

new Sice.Views.RepositoriesView({ model: new MyModel() });

Create a model instance in the view

initialize: function() {
    this.model = new MyModel();
    this.listenTo(this.model, 'change', this.render);
},