问:
Maven Invoker Plugin not detecting failed test
As part of a root parent pom project, several integration tests have been added to test it on sample projects.

The structure of the project folder is as following:

```<code>-root-maven-parent-project
    |- src
    |   |-it
    |      |-sample-project-test1
    |      |-sample-project-test2
    |      |-sample-project-test3
    |      |-settings.xml
    |- pom.xml
</code>```

The main issue is: although the build of sample-project-test2 is wrongly failing (it should not), the build is SUCCESSFUL for the Invoker plugin and the overall build does not fail.

Here is the concerned maven-invoker-plugin configuration:

```<code><profile>
    <id>it-tests</id>
    <build>
        <plugins>
            <!-- Integration tests configuration -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-invoker-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <streamLogs>true</streamLogs>
                    <goals>
                        <goal>clean</goal>
                        <goal>generate-sources</goal>
                    </goals>
                    <settingsFile>src/it/settings.xml</settingsFile>
                    <failIfNoProjects>true</failIfNoProjects>
                </configuration>
                <executions>
                    <execution>
                        <id>integration-test-release</id>
                        <goals>
                            <goal>install</goal>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                        <configuration>
                            <cloneProjectsTo>${project.build.directory}/its/sample-project-test1</cloneProjectsTo>
                            <pom>src/it/sample-project-test1/pom.xml</pom>
                            <properties>
                                <scmBranch>release-something</scmBranch>
                            </properties>
                        </configuration>
                    </execution>
                    <execution>
                        <id>integration-test-hotfix</id>
                        <goals>
                            <goal>install</goal>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                        <configuration>
                            <cloneProjectsTo>${project.build.directory}/its/sample-project-test2</cloneProjectsTo>
                            <pom>src/it/sample-project-test2/pom.xml</pom>
                            <properties>
                                <scmBranch>hotfix-something</scmBranch>
                            </properties>
                        </configuration>
                    </execution>
                    <execution>
                        <id>integration-test-master</id>
                        <goals>
                            <goal>install</goal>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                        <configuration>
                            <cloneProjectsTo>${project.build.directory}/its/sample-project-test3</cloneProjectsTo>
                            <pom>src/it/sample-project-test3/pom.xml</pom>
                            <properties>
                                <scmBranch>master</scmBranch>
                            </properties>
                        </configuration>
                    </execution>
            </plugin>
        </plugins>
    </build>
</profile>
</code>```

As you can see, multiple executions are configured because each execution would need its own properties. Each execution is also pointing at its own integration test project and pom.

The build is clearly failing for a specific execution:

```<code>[INFO] [INFO] ------------------------------------------------------------------------
[INFO] [INFO] BUILD FAILURE
[INFO] [INFO] ------------------------------------------------------------------------
[INFO] [INFO] Total time: 2.337 s
[INFO] [INFO] Finished at: 2017-07-04T17:35:49+02:00
[INFO] [INFO] Final Memory: 12M/220M
[INFO] [INFO] ------------------------------------------------------------------------
[INFO] [ERROR] Failed to execute goal org.apache.maven.plugins:maven-enforcer-plugin:1.4.1:enforce (enforce-snapshot-management) on project cmp-sample-project-test2: Some Enforcer rules have failed. Look above for specific messages explaining why the rule failed. -> [Help 1]
[INFO] [ERROR]
[INFO] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[INFO] [ERROR] Re-run Maven using the -X switch to enable full debug logging.
[INFO] [ERROR]
[INFO] [ERROR] For more information about the errors and possible solutions, please read the following articles:
[INFO] [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
[INFO]           pom.xml .......................................... FAILED (4.1 s)
[INFO]   The build exited with code 1. See C:\data\git-repositories\root-maven-parent\target\its\sample-project-test2\build.log for details.
</code>```

However, at the bottom of the build we see that the verify goal of the maven-invoker-plugin aggregated the results, flagged the concerned test as Passed and made the build SUCCESS:

```<code>[INFO]
[INFO] --- maven-invoker-plugin:3.0.0:verify (integration-test-release) @ root-maven-parent ---
[INFO] -------------------------------------------------
[INFO] Build Summary:
[INFO]   Passed: 1, Failed: 0, Errors: 0, Skipped: 0
[INFO] -------------------------------------------------
[INFO]
[INFO] --- maven-invoker-plugin:3.0.0:verify (integration-test-hotfix) @ root-maven-parent ---
[INFO] -------------------------------------------------
[INFO] Build Summary:
[INFO]   Passed: 1, Failed: 0, Errors: 0, Skipped: 0
[INFO] -------------------------------------------------
[INFO]
[INFO] --- maven-invoker-plugin:3.0.0:verify (integration-test-master) @ root-maven-parent ---
[INFO] -------------------------------------------------
[INFO] Build Summary:
[INFO]   Passed: 1, Failed: 0, Errors: 0, Skipped: 0
[INFO] -------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
</code>```

Moreover, by only running the failing test from command line as:

```<code>mvn invoker:integration-test@integration-test-hotfix invoker:verify -Pit-tests
</code>```

The sub-build of the test project fails, the output is correctly marked as Failed in the test summary, and the build is correctly ending with FAILURE.

Question: why when executing multiple integration tests using the maven-invoker-plugin, although a test is failed, it is marked as Passed in the test summary and the build does not fail, while running only the isolated test everything fails correctly?

Note: no invoker property file is used.

答:
use this configuration :-

```<code>    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-enforcer-plugin</artifactId>
        <version>1.0</version>
        <configuration>
            <rules>
                <banDuplicateClasses>
                    <findAllDuplicates>true</findAllDuplicates>
                </banDuplicateClasses>
            </rules>
            <fail>false</fail>
        </configuration>
        <dependencies>
            <dependency>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>extra-enforcer-rules</artifactId>
                <version>1.0-alpha-1</version>
            </dependency>
        </dependencies>
    </plugin>
</code>```

for more refer this link :

http://maven.apache.org/enforcer/maven-enforcer-plugin/

Body:
As part of a root parent pom project, several integration tests have been added to test it on sample projects.

The structure of the project folder is as following:

-root-maven-parent-project
    |- src
    |   |-it
    |      |-sample-project-test1
    |      |-sample-project-test2
    |      |-sample-project-test3
    |      |-settings.xml
    |- pom.xml

The main issue is: although the build of sample-project-test2 is wrongly failing (it should not), the build is SUCCESSFUL for the Invoker plugin and the overall build does not fail.

Here is the concerned maven-invoker-plugin configuration:

<profile>
    <id>it-tests</id>
    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-invoker-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <streamLogs>true</streamLogs>
                    <goals>
                        <goal>clean</goal>
                        <goal>generate-sources</goal>
                    </goals>
                    <settingsFile>src/it/settings.xml</settingsFile>
                    <failIfNoProjects>true</failIfNoProjects>
                </configuration>
                <executions>
                    <execution>
                        <id>integration-test-release</id>
                        <goals>
                            <goal>install</goal>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                        <configuration>
                            <cloneProjectsTo>${project.build.directory}/its/sample-project-test1</cloneProjectsTo>
                            <pom>src/it/sample-project-test1/pom.xml</pom>
                            <properties>
                                <scmBranch>release-something</scmBranch>
                            </properties>
                        </configuration>
                    </execution>
                    <execution>
                        <id>integration-test-hotfix</id>
                        <goals>
                            <goal>install</goal>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                        <configuration>
                            <cloneProjectsTo>${project.build.directory}/its/sample-project-test2</cloneProjectsTo>
                            <pom>src/it/sample-project-test2/pom.xml</pom>
                            <properties>
                                <scmBranch>hotfix-something</scmBranch>
                            </properties>
                        </configuration>
                    </execution>
                    <execution>
                        <id>integration-test-master</id>
                        <goals>
                            <goal>install</goal>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                        <configuration>
                            <cloneProjectsTo>${project.build.directory}/its/sample-project-test3</cloneProjectsTo>
                            <pom>src/it/sample-project-test3/pom.xml</pom>
                            <properties>
                                <scmBranch>master</scmBranch>
                            </properties>
                        </configuration>
                    </execution>
            </plugin>
        </plugins>
    </build>
</profile>

As you can see, multiple executions are configured because each execution would need its own properties. Each execution is also pointing at its own integration test project and pom.

The build is clearly failing for a specific execution:

[INFO] [INFO] ------------------------------------------------------------------------
[INFO] [INFO] BUILD FAILURE
[INFO] [INFO] ------------------------------------------------------------------------
[INFO] [INFO] Total time: 2.337 s
[INFO] [INFO] Finished at: 2017-07-04T17:35:49+02:00
[INFO] [INFO] Final Memory: 12M/220M
[INFO] [INFO] ------------------------------------------------------------------------
[INFO] [ERROR] Failed to execute goal org.apache.maven.plugins:maven-enforcer-plugin:1.4.1:enforce (enforce-snapshot-management) on project cmp-sample-project-test2: Some Enforcer rules have failed. Look above for specific messages explaining why the rule failed. -> [Help 1]
[INFO] [ERROR]
[INFO] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[INFO] [ERROR] Re-run Maven using the -X switch to enable full debug logging.
[INFO] [ERROR]
[INFO] [ERROR] For more information about the errors and possible solutions, please read the following articles:
[INFO] [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
[INFO]           pom.xml .......................................... FAILED (4.1 s)
[INFO]   The build exited with code 1. See C:\data\git-repositories\root-maven-parent\target\its\sample-project-test2\build.log for details.

However, at the bottom of the build we see that the verify goal of the maven-invoker-plugin aggregated the results, flagged the concerned test as Passed and made the build SUCCESS:

[INFO]
[INFO] --- maven-invoker-plugin:3.0.0:verify (integration-test-release) @ root-maven-parent ---
[INFO] -------------------------------------------------
[INFO] Build Summary:
[INFO]   Passed: 1, Failed: 0, Errors: 0, Skipped: 0
[INFO] -------------------------------------------------
[INFO]
[INFO] --- maven-invoker-plugin:3.0.0:verify (integration-test-hotfix) @ root-maven-parent ---
[INFO] -------------------------------------------------
[INFO] Build Summary:
[INFO]   Passed: 1, Failed: 0, Errors: 0, Skipped: 0
[INFO] -------------------------------------------------
[INFO]
[INFO] --- maven-invoker-plugin:3.0.0:verify (integration-test-master) @ root-maven-parent ---
[INFO] -------------------------------------------------
[INFO] Build Summary:
[INFO]   Passed: 1, Failed: 0, Errors: 0, Skipped: 0
[INFO] -------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

Moreover, by only running the failing test from command line as:

mvn invoker:integration-test@integration-test-hotfix invoker:verify -Pit-tests

The sub-build of the test project fails, the output is correctly marked as Failed in the test summary, and the build is correctly ending with FAILURE.

Question: why when executing multiple integration tests using the maven-invoker-plugin, although a test is failed, it is marked as Passed in the test summary and the build does not fail, while running only the isolated test everything fails correctly?

Note: no invoker property file is used.

Body:
use this configuration :-

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-enforcer-plugin</artifactId>
        <version>1.0</version>
        <configuration>
            <rules>
                <banDuplicateClasses>
                    <findAllDuplicates>true</findAllDuplicates>
                </banDuplicateClasses>
            </rules>
            <fail>false</fail>
        </configuration>
        <dependencies>
            <dependency>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>extra-enforcer-rules</artifactId>
                <version>1.0-alpha-1</version>
            </dependency>
        </dependencies>
    </plugin>

for more refer this link :

http://maven.apache.org/enforcer/maven-enforcer-plugin/


来源: stackexchange

问:
How to draw samples from lmfit model?
I have a skewed Gaussian model in lmfit that fits my data. Now I would like to draw a sample from it, but I could nowhere in the documentation find how? Is the correct approach to simply implement the model function yourself in my case the skewed normal distribution or is there a function in lmfit for this?

My code:

```<code>model = SkewedGaussianModel()

params = model.make_params(amplitude=60, center=30, sigma=10, gamma=0)

result = model.fit(y, params, x=x)
print(result.fit_report())
plt.plot(x, result.best_fit)
plt.show()
# something like this
print(result.model.eval(random.random())
</code>```

答:
The definition for skewed Gaussian used in lmfit is given at
http://lmfit.github.io/lmfit-py/builtin_models.html#skewedgaussianmodel
with code at
https://github.com/lmfit/lmfit-py/blob/master/lmfit/lineshapes.py#L213.  </p>

<p>I believe that what you are looking for is the "inverse transform sampling". See http://www.nehalemlabs.net/prototype/blog/2013/12/16/how-to-do-inverse-transformation-sampling-in-scipy-and-numpy/ for hints on how to do that. There is not a built-in method for this in lmfit, as lmfit does not necessarily assert that the model being fitted is a probability distribution function.  It might be worth considering adding such a capability. </p>

ContentLicense: CC BY-SA 3.0

Title: How to draw samples from lmfit model?

Body:
I have a skewed Gaussian model in lmfit that fits my data. Now I would like to draw a sample from it, but I could nowhere in the documentation find how? Is the correct approach to simply implement the model function yourself in my case the skewed normal distribution or is there a function in lmfit for this?

My code:

model = SkewedGaussianModel()

params = model.make_params(amplitude=60, center=30, sigma=10, gamma=0)

result = model.fit(y, params, x=x)
print(result.fit_report())
plt.plot(x, result.best_fit)
plt.show()
# something like this
print(result.model.eval(random.random())

Body:
The definition for skewed Gaussian used in lmfit is given at
http://lmfit.github.io/lmfit-py/builtin_models.html#skewedgaussianmodel
with code at
https://github.com/lmfit/lmfit-py/blob/master/lmfit/lineshapes.py#L213.

I believe that what you are looking for is the "inverse transform sampling". See http://www.nehalemlabs.net/prototype/blog/2013/12/16/how-to-do-inverse-transformation-sampling-in-scipy-and-numpy/ for hints on how to do that. There is not a built-in method for this in lmfit, as lmfit does not necessarily assert that the model being fitted is a probability distribution function.  It might be worth considering adding such a capability.


问:
Declaring service name in providers when we are passing the same as a parameter to constructor
Why should we declare a service name in providers when we are passing it as a parameter to component constructor

```<code>import {xComponent} from './x'
@Component({
providers : [xComponent]
})
export class xyz{
constructor(public x : xComponent){}
}
</code>```

From the above, why should we declare the xComponent in providers if we are passing the same in constructor. Isn't that redundency.

答:
Because providing and injecting are two different things.

Providing specifies where and how an instance of a service is created and what it's scope is.

Injecting is to specify a constructor parameter, where a service (or other injectable) instance needs to be passed in.

Body:
Why should we declare a service name in providers when we are passing it as a parameter to component constructor

import {xComponent} from './x'
@Component({
providers : [xComponent]
})
export class xyz{
constructor(public x : xComponent){}
}

From the above, why should we declare the xComponent in providers if we are passing the same in constructor. Isn't that redundency.


问:
Funnel Legacy SQL Filter problems - BigQuery
we're trying to use script for a funnel for google BigQuery that Doug Mackenzie created linked here:http://online-behavior.com/analytics/funnel-analysis

We have run into some problems with our SQL call.

We're trying to use a filter from a hits.customDimensions.index = 20 where the value is 1. These values are always present so a simple filter such as the ones used as examples in his introduction is unfortunately not adequate.
A filter such as:

    WHERE hits.customDimensions.index = '20' Does not filter what we need to have filtered.

Rather we need (we imagine) something like this:

WHERE MAX(IF(hits.customDimensions.index=20,hits.customDimensions.value,NULL)) WITHIN hits as locked= '1'

This is how we've tried doing it:

```<code>FROM (
    SELECT
      fullVisitorId,
      visitId,
      MIN(hits.hitNumber) AS firstHit,
      MAX(IF(hits.isExit, 1, 0)) AS exit
    FROM(
      SELECT
      *,
      MAX(IF(hits.customDimensions.index=20,hits.customDimensions.value,NULL)) WITHIN hits as locked,
      FROM
      TABLE_DATE_RANGE([[dataset.ga_sessions_], TIMESTAMP('2017-06-01'), TIMESTAMP('2017-06-04'))
      )
    WHERE
      REGEXP_MATCH(hits.page.pagePath, '^/plus/.*/[0-9]')
      AND totals.visits = 1
      AND locked= '1'
    GROUP BY
      fullVisitorId,
      visitId) s0
</code>```

This returns the error:

Error: Cannot query the cross product of repeated fields customDimensions.index and hits.kunde. ; Cannot query the cross product of repeated fields customDimensions.value and hits.kunde.

We have seen that there are some suggestions to use FLATTEN on problems with the above mentioned error. However this did seem to give syntax errors:

```<code>  FROM (
    SELECT
      fullVisitorId,
      visitId,
      MIN(hits.hitNumber) AS firstHit,
      MAX(IF(hits.isExit, 1, 0)) AS exit,
      MAX(IF(hits.customDimensions.index=20,hits.customDimensions.value,NULL)) WITHIN hits AS locked
    FROM
      FLATTEN(TABLE_DATE_RANGE([[dataset.ga_sessions_], TIMESTAMP('2017-06-01'), TIMESTAMP('2017-06-04')),hits.customDimension)
    WHERE
      REGEXP_MATCH(hits.page.pagePath, '^/plus/.*/[0-9]')
      AND totals.visits = 1
      AND locked = '1'
    GROUP BY
      fullVisitorId,
      visitId) s0
</code>```

Just gives the error: Error: Not found: Table eb-bigquery:3917183.ga_sessions_

So any suggestions to how we can get the filter to work would be much appreciated.

答:
BigQuery has evolved a lot since this blog was written and now we have more advanced techniques to process data.

That's the main reason why I asked if you could use the Standard Version of BigQuery as solving this would be easier there. For instance:

```<code>SELECT
  fullvisitorid,
  visitid,
  (select min(hitNumber) from unnest(hits) where regexp_contains(page.pagePath, r'^/plus/.*/[0-9]')) firstHit,
  (select max(isExit) from UNNEST(hits) where regexp_contains(page.pagePath, r'^/plus/.*/[0-9]')) exitFlag
FROM `table`
WHERE 1 = 1
  AND EXISTS(select 1 from unnest(hits) where regexp_contains(page.pagePath, r'^/plus/.*/[0-9]'))
AND EXISTS(select 1 from unnest(hits) hits where (select count(value) from unnest(hits.customDimensions) custd where index=20) > 0)
AND totals.visits = 1
</code>```

This query does the same thing and runs faster than the Legacy ones as it avoids first unnesting all repeated fields and then processing the data.

Body:
we're trying to use script for a funnel for google BigQuery that Doug Mackenzie created linked here:http://online-behavior.com/analytics/funnel-analysis

We have run into some problems with our SQL call.

We're trying to use a filter from a hits.customDimensions.index = 20 where the value is 1. These values are always present so a simple filter such as the ones used as examples in his introduction is unfortunately not adequate.
A filter such as:

    WHERE hits.customDimensions.index = '20' Does not filter what we need to have filtered.

Rather we need (we imagine) something like this:

WHERE MAX(IF(hits.customDimensions.index=20,hits.customDimensions.value,NULL)) WITHIN hits as locked= '1'

This is how we've tried doing it:

FROM (
    SELECT
      fullVisitorId,
      visitId,
      MIN(hits.hitNumber) AS firstHit,
      MAX(IF(hits.isExit, 1, 0)) AS exit
    FROM(
      SELECT
      *,
      MAX(IF(hits.customDimensions.index=20,hits.customDimensions.value,NULL)) WITHIN hits as locked,
      FROM
      TABLE_DATE_RANGE([[dataset.ga_sessions_], TIMESTAMP('2017-06-01'), TIMESTAMP('2017-06-04'))
      )
    WHERE
      REGEXP_MATCH(hits.page.pagePath, '^/plus/.*/[0-9]')
      AND totals.visits = 1
      AND locked= '1'
    GROUP BY
      fullVisitorId,
      visitId) s0

This returns the error:

Error: Cannot query the cross product of repeated fields customDimensions.index and hits.kunde. ; Cannot query the cross product of repeated fields customDimensions.value and hits.kunde.

We have seen that there are some suggestions to use FLATTEN on problems with the above mentioned error. However this did seem to give syntax errors:

  FROM (
    SELECT
      fullVisitorId,
      visitId,
      MIN(hits.hitNumber) AS firstHit,
      MAX(IF(hits.isExit, 1, 0)) AS exit,
      MAX(IF(hits.customDimensions.index=20,hits.customDimensions.value,NULL)) WITHIN hits AS locked
    FROM
      FLATTEN(TABLE_DATE_RANGE([[dataset.ga_sessions_], TIMESTAMP('2017-06-01'), TIMESTAMP('2017-06-04')),hits.customDimension)
    WHERE
      REGEXP_MATCH(hits.page.pagePath, '^/plus/.*/[0-9]')
      AND totals.visits = 1
      AND locked = '1'
    GROUP BY
      fullVisitorId,
      visitId) s0

Just gives the error: Error: Not found: Table eb-bigquery:3917183.ga_sessions_

So any suggestions to how we can get the filter to work would be much appreciated.

Body:
BigQuery has evolved a lot since this blog was written and now we have more advanced techniques to process data.

That's the main reason why I asked if you could use the Standard Version of BigQuery as solving this would be easier there. For instance:

SELECT
  fullvisitorid,
  visitid,
  (select min(hitNumber) from unnest(hits) where regexp_contains(page.pagePath, r'^/plus/.*/[0-9]')) firstHit,
  (select max(isExit) from UNNEST(hits) where regexp_contains(page.pagePath, r'^/plus/.*/[0-9]')) exitFlag
FROM `table`
WHERE 1 = 1
  AND EXISTS(select 1 from unnest(hits) where regexp_contains(page.pagePath, r'^/plus/.*/[0-9]'))
AND EXISTS(select 1 from unnest(hits) hits where (select count(value) from unnest(hits.customDimensions) custd where index=20) > 0)
AND totals.visits = 1

This query does the same thing and runs faster than the Legacy ones as it avoids first unnesting all repeated fields and then processing the data.


问:
DependencyProperty in my UserControl fails to update bound property in ViewModel
I have made an usercontrol that contains a TextBox with some custom behaviours and I want to bind the Text property to a property in my ViewModel.

I have isolated the problem into a sample solution and manage to update the Text property with the ViewModel property value, but when I write into the textbox and leaves the textbox my Person.Name property is not updated.

My usercontrol xaml:

```<code><UserControl x:Class="WpfCustomUserControlBinding.TextBoxReadOnlyLooksDisabled"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<Control.Resources>
    <Style x:Key="readOnlyTextbox">
        <Style.Triggers>
            <Trigger Property="TextBoxBase.IsReadOnly" Value="True">
                <Setter Property="TextBoxBase.Background" Value="WhiteSmoke" />
                <Setter Property="TextBoxBase.Foreground" Value="#FF6D6D6D" />
                <Setter Property="TextBox.BorderBrush" Value="DarkGray" />
                <Setter Property="TextBoxBase.BorderThickness" Value="1,1,1,1" />
            </Trigger>
            <Trigger Property="TextBoxBase.IsReadOnly" Value="False">
                <Setter Property="TextBoxBase.Background" Value="White" />
                <Setter Property="TextBoxBase.Foreground" Value="Black" />
            </Trigger>
        </Style.Triggers>
    </Style>
</Control.Resources>

<TextBox Style="{StaticResource readOnlyTextbox}" x:Name="txtTextBoxBase" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</code>```

The codebehind code:

```<code>public partial class TextBoxReadOnlyLooksDisabled
{
    public TextBoxReadOnlyLooksDisabled()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof (string)
                                                                                , typeof (TextBoxReadOnlyLooksDisabled)
                                                                                ,new PropertyMetadata(OnTextChange));

    private static void OnTextChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var textBoxReadOnlyLooksDisabled = (TextBoxReadOnlyLooksDisabled) d;
        textBoxReadOnlyLooksDisabled.txtTextBoxBase.Text = (string) e.NewValue;
    }

    public string Text
    {
        get { return (string) GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }
}
</code>```

Window where I try to get the sample to work:

```<code><Window x:Class="WpfCustomUserControlBinding.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:src="clr-namespace:WpfCustomUserControlBinding" Title="MainWindow" Height="153" Width="525">
<Window.Resources>
    <src:Person x:Key="myDataSource"/>
</Window.Resources>
<Grid >
    <Label Content="Plain vanilla" Height="26" HorizontalAlignment="Left" Margin="12,12,0,0" Name="label1" VerticalAlignment="Top" Width="143" />
    <Label Content="Messed up version" Height="26" HorizontalAlignment="Left" Margin="12,61,0,0" Name="label2" VerticalAlignment="Top" Width="143" />
    <TextBox Height="23" HorizontalAlignment="Left" Margin="152,15,0,0" x:Name="txtVanlig" VerticalAlignment="Top" Width="251" Text="{Binding Source={StaticResource myDataSource}, Path=Name, Mode=TwoWay}"/>

    <src:TextBoxReadOnlyLooksDisabled Height="23" HorizontalAlignment="Left" Margin="152,61,0,0" x:Name="txtVrien" VerticalAlignment="Top" Width="251" Text="{Binding Source={StaticResource myDataSource}, Path=Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</code>```

The sample value class:

```<code> public class Person
{
    private string _name = "King Chaos";

    public string Name{get{return _name;}set{_name = value;}}
}
</code>```

Thanks in advance. ;)

Edit: Adding INotifyPropertyChanged does not do the trick since the set method of the Name is not accessed when updating my custom TextBox.

答:
Well the problem you are experiencing is caused because the Text dependency property of the TextBox inside of your custom TextBoxReadOnlyLooksDisabled is actually not bound to your "ViewModel" (the Person class) and so when you write something in that txtTextBoxBase its Text dp is changed, but the change is not propagated back to the ViewModel.
What you can do is wire the Text dp of the nested TextBox to the Text dp of your custom control with:

```<code><TextBox x:Name="txtTextBoxBase"
         Text={Binding Path=Text, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TextBoxReadOnlyLooksDisabled}}} />
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have made an usercontrol that contains a TextBox with some custom behaviours and I want to bind the Text property to a property in my ViewModel.

I have isolated the problem into a sample solution and manage to update the Text property with the ViewModel property value, but when I write into the textbox and leaves the textbox my Person.Name property is not updated.

My usercontrol xaml:

<UserControl x:Class="WpfCustomUserControlBinding.TextBoxReadOnlyLooksDisabled"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<Control.Resources>

    </Style>
</Control.Resources>

<TextBox Style="{StaticResource readOnlyTextbox}" x:Name="txtTextBoxBase" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />

The codebehind code:

public partial class TextBoxReadOnlyLooksDisabled
{
    public TextBoxReadOnlyLooksDisabled()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof (string)
                                                                                , typeof (TextBoxReadOnlyLooksDisabled)
                                                                                ,new PropertyMetadata(OnTextChange));

    private static void OnTextChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var textBoxReadOnlyLooksDisabled = (TextBoxReadOnlyLooksDisabled) d;
        textBoxReadOnlyLooksDisabled.txtTextBoxBase.Text = (string) e.NewValue;
    }

    public string Text
    {
        get { return (string) GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }
}

Window where I try to get the sample to work:

<Window x:Class="WpfCustomUserControlBinding.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:src="clr-namespace:WpfCustomUserControlBinding" Title="MainWindow" Height="153" Width="525">
<Window.Resources>
    <src:Person x:Key="myDataSource"/>
</Window.Resources>
<Grid >

    <TextBox Height="23" HorizontalAlignment="Left" Margin="152,15,0,0" x:Name="txtVanlig" VerticalAlignment="Top" Width="251" Text="{Binding Source={StaticResource myDataSource}, Path=Name, Mode=TwoWay}"/>

    <src:TextBoxReadOnlyLooksDisabled Height="23" HorizontalAlignment="Left" Margin="152,61,0,0" x:Name="txtVrien" VerticalAlignment="Top" Width="251" Text="{Binding Source={StaticResource myDataSource}, Path=Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>

The sample value class:

 public class Person
{
    private string _name = "King Chaos";

    public string Name{get{return _name;}set{_name = value;}}
}

Thanks in advance. ;)

Edit: Adding INotifyPropertyChanged does not do the trick since the set method of the Name is not accessed when updating my custom TextBox.

Body:
Well the problem you are experiencing is caused because the Text dependency property of the TextBox inside of your custom TextBoxReadOnlyLooksDisabled is actually not bound to your "ViewModel" (the Person class) and so when you write something in that txtTextBoxBase its Text dp is changed, but the change is not propagated back to the ViewModel.
What you can do is wire the Text dp of the nested TextBox to the Text dp of your custom control with:

<TextBox x:Name="txtTextBoxBase"
         Text={Binding Path=Text, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TextBoxReadOnlyLooksDisabled}}} />


答:
What do you mean by providers? Is it @Component providers or is it @NgModule providers?

If @Component, then it is not required anymore, if you use @Inject annotation on constructor parameters (I'm pretty sure it was required in beta, but soonish after release it was removed). However, it is still possible to use that approach for few special cases (e.g. if you need dynamic dependency, so you can get local instance of Injector, that contains services/classes listed in providers, but that is definitely not your case. Or you can list all Services that needs to be provided and remove @Inject annotation). But you still can find tons of outdated examples across internet.

If @NgModule - it is still required - that is entry point for Injector to get list of Classes available for DI. If you do not provide your service here, DI cannot be resolved in constructor via @Inject

Title: Declaring service name in providers when we are passing the same as a parameter to constructor


问:
AngularJS routeParam not working
I have url like this:

```<code>http://localhost:3000/details/59567bc1de7ddb2d5feff262
</code>```

and I want to get the parameter id

```<code>59567bc1de7ddb2d5feff262
</code>```

But for some reasons routeParam always returns undefined

My controller is:

```<code>task.controller('ctrla',  function($rootScope, $scope, $http, $timeout, $routeParams){
    $scope.first = 1;
    console.log($routeParams);
});
</code>```

routes :

```<code>task.config(function ($routeProvider, $locationProvider){
$routeProvider.when('/details/:id', {
      templateUrl: "details.html",
      controller: "ctrla"
    })

});
</code>```

any help will be a life save.

答:
If yu have route deinition defined as </p>

```<code>$routeProvider.when('/details/:id', {
      templateUrl: "partial.html",
      controller: "ctrla"
    })
</code>```

<p>Then in controller you should get its value as </p>

```<code>task.controller('ctrla',  function($rootScope, $scope, $http, $timeout, $routeParams){
    $scope.first = 1;
    console.log($routeParams.id);

});
</code>```

Title: AngularJS routeParam not working

Body:
I have url like this:

http://localhost:3000/details/59567bc1de7ddb2d5feff262

and I want to get the parameter id

59567bc1de7ddb2d5feff262

But for some reasons routeParam always returns undefined

My controller is:

task.controller('ctrla',  function($rootScope, $scope, $http, $timeout, $routeParams){
    $scope.first = 1;
    console.log($routeParams);
});

routes :

task.config(function ($routeProvider, $locationProvider){
$routeProvider.when('/details/:id', {
      templateUrl: "details.html",
      controller: "ctrla"
    })

});

any help will be a life save.

Body:
If yu have route deinition defined as

$routeProvider.when('/details/:id', {
      templateUrl: "partial.html",
      controller: "ctrla"
    })

Then in controller you should get its value as

task.controller('ctrla',  function($rootScope, $scope, $http, $timeout, $routeParams){
    $scope.first = 1;
    console.log($routeParams.id);

});


问:
Initialize slices of memoryview in cython from numpy.ndarray
I am trying to initialize a slice (not not whole) of a memoryview. Suppose that I have memoryview A as an attribute of a class (Extension Type)

```<code>from cython.view cimport array as cvarray

N = 1000
cdef double[:,:,::1] A = cvarray(shape=(2,N,N),itemsize=sizeof(double),format='d')
</code>```

Now, I am trying to initialize it in a cdef function. I have no problem initializing the whole memoryview like this

```<code># From elsewhere we have loaded a numpy.ndarray B of size (2,N,N)
A[:,:,:] = B
</code>```

This is fine when the initializer B is 3D array (2,N,N) so that we do not have to slice A. But now, the problem is here: suppose that I have 2D arrays B1 and B2 of size (N,N), and trying to initialize as

```<code>A[0,:,:] = B1
A[1,:,:] = B2
</code>```

This gives me the following error:

```<code>TypeError: only length-1 arrays can be converted to Python scalars
</code>```

Of course I can copy all data one-by-one from B1 and B2 to A, but this would not be efficient. This process is in a loop and the size N is large. B1 and B2 come form loading netcdf files as numpy.ndarray type.

Also, I am defining A to be as a memoryview so that somewhere else in the code I can use nogil functions over accessing A.

I am wondering if there is an efficient way to initialize the memoryview as above, or at least, somehow play with pointers of B1 and B2 and put them together into an iterable array. Thanks.

答:
I can find two options:

It works if you type B1 and B2 as a memoryview.

You can access the base attribute of the memoryview to get the cvarray and index that:

```<code>A.base[0,:,:] = B1
A.base[1,:,:] = B2
</code>```

I don't think this will necessarily work for all memoryview compatible objects (they are required to define the buffer interface rather than a useful __getitem__) but it should work for most of them, including cvarray.

Body:
I am trying to initialize a slice (not not whole) of a memoryview. Suppose that I have memoryview A as an attribute of a class (Extension Type)

from cython.view cimport array as cvarray

N = 1000
cdef double[:,:,::1] A = cvarray(shape=(2,N,N),itemsize=sizeof(double),format='d')

Now, I am trying to initialize it in a cdef function. I have no problem initializing the whole memoryview like this

# From elsewhere we have loaded a numpy.ndarray B of size (2,N,N)
A[:,:,:] = B

This is fine when the initializer B is 3D array (2,N,N) so that we do not have to slice A. But now, the problem is here: suppose that I have 2D arrays B1 and B2 of size (N,N), and trying to initialize as

A[0,:,:] = B1
A[1,:,:] = B2

This gives me the following error:

TypeError: only length-1 arrays can be converted to Python scalars

Of course I can copy all data one-by-one from B1 and B2 to A, but this would not be efficient. This process is in a loop and the size N is large. B1 and B2 come form loading netcdf files as numpy.ndarray type.

Also, I am defining A to be as a memoryview so that somewhere else in the code I can use nogil functions over accessing A.

I am wondering if there is an efficient way to initialize the memoryview as above, or at least, somehow play with pointers of B1 and B2 and put them together into an iterable array. Thanks.

Body:
I can find two options:

It works if you type B1 and B2 as a memoryview.

You can access the base attribute of the memoryview to get the cvarray and index that:

A.base[0,:,:] = B1
A.base[1,:,:] = B2

I don't think this will necessarily work for all memoryview compatible objects (they are required to define the buffer interface rather than a useful __getitem__) but it should work for most of them, including cvarray.


问:
How do I combine two map locations into a more accurate one?
I am creating an app that is interested in having a highly accurate estimate of an Android device's location. I am also required to send this data to a proxy server.

My current implementation fetches a GPS location on the device itself and sends that to the proxy. In addition, it sends data required by Google's GeoLocation API such as wifi access points to the server, and the server then makes a call to the API and acquires another Location. Both the GPS Location and Geolocation are on the form

{
  center: {
    lat: ...,
    lng: ...,
   },
   accuracy: ...
}```

This means that I end up with two different estimators for a single location, each with their own center and accuracy. My question is as follows:

Is there a way to combine these two Locations into a single, more accurate location? Ideally I'd like to use some API that takes several objects on the form above and returns a single object with a new center and a lower accuracy value than the provided locations. If there is no such API, it's also fine if someone could help me develop an algorithm that has the desired effect.

Since these location estimate the same true location, combining them somehow should be able to yield a better result. I was not able to find an answer as to how either by googling or by reading several pages of all questions tagged with google-geolocation.

This is a slightly difficult question to categorize, it might turn out to be better suited for the statisticians over at https://stats.stackexchange.com/. If so, let me know and I'll take my question there.

答:
Basically, your problem breaks down to finding the circle containing the intersection of the two circles given by the Geolocation and the GPS location.

For the sake of simplicity, let's call the latitude of the Geolocation x1, the longitude y1 and the accuracy r1, whereas we denote the latitude of the GPS location x2, the longitude y2 and the accuracy r2. Please note that I'm using Cartesian Coordinates. You'll have to convert your given Polar Coordinates before doing the beneath outlined calculations.

These two circles can

be completely seperate and have no common points. We drop this case by making the assumption that the reported locations are correct, i.e. the device isn't located outside of the calculated locations. If you don't want to make this assumption - choose the more accurate location.

be contained within another. In this case you simply choose the smaller (i.e more accurate) circle as the optimized location.

intersect in exactly one point (Jackpot! - you've got the exact location)

intersect in an asymmetric lens which looks like this

What you need to calculate is the midpoint (x3,y3) of the asymmetric lens on the line between [(x1,y1)(x2,y2)] and the radius r3 of the spanning circle.

As a good ressource I recommend you Paul Bourke's page on this topic which also offers some implementations, e.g. in Python or C. Please don't mix up the points x3 and y3 from the article since I've choosen an alternative naming which fits better to your problem.

Your optimized location is then given by
x3 = x1 + a*(x2-x1)/d, y3 = y1 + a*(y2-y1)/d and
r3 = sqrt((r1)^2-a^2) where a = ((r1)^2-(r2)^2+d^2)/2*d and
d = (sqrt((x2-x1)^2+(y2-y1)^2).

The rest is up to you since I don't know which language you're using. Feel free to comment on this answer if something isn't clear.

EDIT: If you search for circle circle intersection, you will find even more examples, e.g. this question involving Google Maps API

Body:
I am creating an app that is interested in having a highly accurate estimate of an Android device's location. I am also required to send this data to a proxy server.

My current implementation fetches a GPS location on the device itself and sends that to the proxy. In addition, it sends data required by Google's GeoLocation API such as wifi access points to the server, and the server then makes a call to the API and acquires another Location. Both the GPS Location and Geolocation are on the form

{
  center: {
    lat: ...,
    lng: ...,
   },
   accuracy: ...
}

This means that I end up with two different estimators for a single location, each with their own center and accuracy. My question is as follows:

Is there a way to combine these two Locations into a single, more accurate location? Ideally I'd like to use some API that takes several objects on the form above and returns a single object with a new center and a lower accuracy value than the provided locations. If there is no such API, it's also fine if someone could help me develop an algorithm that has the desired effect.

Since these location estimate the same true location, combining them somehow should be able to yield a better result. I was not able to find an answer as to how either by googling or by reading several pages of all questions tagged with google-geolocation.

This is a slightly difficult question to categorize, it might turn out to be better suited for the statisticians over at https://stats.stackexchange.com/. If so, let me know and I'll take my question there.


问:
GitHub: how to manually deploy all code to production server
I have a Ruby on Rails server with Development and Production environments running on it.  I have recently created a remote GitHub repository based on the Development code, and now I want to deploy this code to Production.

I thought that using git clone would be the way to do this, but this gives:

```<code>fatal: destination path already exists and is not an empty directory.
</code>```

The target directory is indeed present and non-empty, because my (currently ummanaged) Production code lives there.  I thought that using git clone would allow me to write my master code into my Production environment.  What am I not understanding?

答:
Additional information based on comments:

Some comments have clarified that the production directory cannot be deleted as I originally suggested. Furthermore, the code in the production directory is identical to the code in the development directory. This suggests creating a git repo directly in the production directory and then cloning it as the development folder.

On the production machine:

```<code>$ cd <production directory>
$ git init
$ git add .
$ git commit
</code>```

On the development machine:

```<code>$ cd <parent of development directory>
$ rm -rf <development directory>
$ git clone <URL to the production directory>
</code>```

Note I am assuming that the current development repo does not contain any history which you want to keep. If it does, you can instead add the new production repo as a remote and merge the histories.

On the development machine:

```<code>$ cd <development directory>
$ git remote add prod <URL to production directory>
$ git checkout master
$ git pull prod master
</code>```

Original answer:

You should delete the production directory and recreate it as a git repo. Then connect your development repo the production repo.

One way to do this is simply clone as you have done:

```<code>$ cd <parent of production directory>
$ rm -rf <production directory>
$ git clone <development directory or URL> <production directory>
</code>```

This might be difficult if the development directory and production directory are on different machines, depending on the network configuration. Even if you do this, you will need to connect the development directory to the production one in order to push updates:

```<code>$ git remote add prod <production directory or URL>
</code>```

Since you need to do this anyway, you can do it from the beginning. On the production server. First create an empty production repo:

```<code>$ cd <parent of production directory>
$ rm -rf <production directory>
$ mkdir <production directory>
$ cd <production directory>
$ git init
</code>```

Now push the development code to production:

```<code>$ cd <development directory>
$ git remote add prod <production directory or URL>
$ git push prod master
</code>```

Note that the location of the production code is mostly irrelevant. You configure a so-called "remote" with this location. This means that the directories do not need to have the same name.

Body:
I have a Ruby on Rails server with Development and Production environments running on it.  I have recently created a remote GitHub repository based on the Development code, and now I want to deploy this code to Production.

I thought that using git clone would be the way to do this, but this gives:

fatal: destination path already exists and is not an empty directory.

The target directory is indeed present and non-empty, because my (currently ummanaged) Production code lives there.  I thought that using git clone would allow me to write my master code into my Production environment.  What am I not understanding?

Body:
Additional information based on comments:

Some comments have clarified that the production directory cannot be deleted as I originally suggested. Furthermore, the code in the production directory is identical to the code in the development directory. This suggests creating a git repo directly in the production directory and then cloning it as the development folder.

On the production machine:

$ cd <production directory>
$ git init
$ git add .
$ git commit

On the development machine:

$ cd <parent of development directory>
$ rm -rf <development directory>
$ git clone <URL to the production directory>

Note I am assuming that the current development repo does not contain any history which you want to keep. If it does, you can instead add the new production repo as a remote and merge the histories.

On the development machine:

$ cd <development directory>
$ git remote add prod <URL to production directory>
$ git checkout master
$ git pull prod master

Original answer:

You should delete the production directory and recreate it as a git repo. Then connect your development repo the production repo.

One way to do this is simply clone as you have done:

$ cd <parent of production directory>
$ rm -rf <production directory>
$ git clone <development directory or URL> <production directory>

This might be difficult if the development directory and production directory are on different machines, depending on the network configuration. Even if you do this, you will need to connect the development directory to the production one in order to push updates:

$ git remote add prod <production directory or URL>

Since you need to do this anyway, you can do it from the beginning. On the production server. First create an empty production repo:

$ cd <parent of production directory>
$ rm -rf <production directory>
$ mkdir <production directory>
$ cd <production directory>
$ git init

Now push the development code to production:

$ cd <development directory>
$ git remote add prod <production directory or URL>
$ git push prod master

Note that the location of the production code is mostly irrelevant. You configure a so-called "remote" with this location. This means that the directories do not need to have the same name.


问:
Installed Nose but cannot use on command line
I installed Nose on a Mac OSX 10.10.5 with Python2.7.9 using easy_install. The installation appeared to be successful:

```<code>Collecting nose
  Downloading nose-1.3.7-py2-none-any.whl (154kB)
    100% |████████████████████████████████| 155kB 2.3MB/s
Installing collected packages: nose
Successfully installed nose-1.3.7
</code>```

But now, when I try even basic stuff with nosetests on the command line, like nosetests -h or which nosetests I just get:

```<code>bash: nosetests: command not found
</code>```

I have tried uninstalling, reinstalling using pip, tried installing with sudo and then running sudo nostests in the directories with tests scripts as other posts have suggested, but nothing seems to work.

The original purpose for installing was to use nose to run some basic tests with tests scripts I had written for these simple web.py apps. But nothing works, just keep getting the command not found response.

What's strange is that, when I open up the Python interpreter in Terminal, and do something like:

```<code>import nose
nose.main()
</code>```

I get the expected result of:

```<code>.
----------------------------------------------------------------------
Ran 1 test in 0.135s

OK
</code>```

So clearly it's installed....somewhere. Any suggestions for what the hell is going on here?

答:
I had this exact issue on OS X EI Captain with Python 2.7.10.

First I installed nose using pip:

```<code>$sudo pip install nose
</code>```

which failed on the first attempt. Went through on the second attempt. But the  nosetests command didn't work.

In order to fix this:

Step 1: Don't uninstall nose if it was installed already using pip as in my case.

Step 2:

```<code>$cd /usr/bin

$sudo easy_install nose
</code>```

Above command finds the nosetests script (which was installed by pip earlier) & sets it under /usr/local/bin

```<code>Step 3: Try nosetests

$nosetests

----------------------------------------------------------------------
Ran 0 tests in 0.047s

OK
</code>```

Body:
I installed Nose on a Mac OSX 10.10.5 with Python2.7.9 using easy_install. The installation appeared to be successful:

Collecting nose
  Downloading nose-1.3.7-py2-none-any.whl (154kB)
    100% |████████████████████████████████| 155kB 2.3MB/s
Installing collected packages: nose
Successfully installed nose-1.3.7

But now, when I try even basic stuff with nosetests on the command line, like nosetests -h or which nosetests I just get:

bash: nosetests: command not found

I have tried uninstalling, reinstalling using pip, tried installing with sudo and then running sudo nostests in the directories with tests scripts as other posts have suggested, but nothing seems to work.

The original purpose for installing was to use nose to run some basic tests with tests scripts I had written for these simple web.py apps. But nothing works, just keep getting the command not found response.

What's strange is that, when I open up the Python interpreter in Terminal, and do something like:

import nose
nose.main()

I get the expected result of:

.
----------------------------------------------------------------------
Ran 1 test in 0.135s

OK

So clearly it's installed....somewhere. Any suggestions for what the hell is going on here?

Body:
I had this exact issue on OS X EI Captain with Python 2.7.10.

First I installed nose using pip:

$sudo pip install nose

which failed on the first attempt. Went through on the second attempt. But the  nosetests command didn't work.

In order to fix this:

Step 1: Don't uninstall nose if it was installed already using pip as in my case.

Step 2:

$cd /usr/bin

$sudo easy_install nose

Above command finds the nosetests script (which was installed by pip earlier) & sets it under /usr/local/bin

Step 3: Try nosetests

$nosetests

----------------------------------------------------------------------
Ran 0 tests in 0.047s

OK


问:
How to change the JDK for a Jenkins job?
I have imported the jenkins jobs from existing jenkins server from another machine. But the problem is, it has the JDK referenced as per the old machines and I want to change it to use the JDK configured in my new jenkins. But I am unable to find any way of doing this. So, please if you have come across this situation and found a way then please help me too.

Thanks.

答: For those who couldn't find this option. Install JDK Parameter Plugin</p>


问:
Android Share button does not appear and Material Design not working
Share button does not appear on the action bar.. Please help..!!
Here is the code::

MainActivity.java

```<code>import java.util.ArrayList;
import java.util.Currency;
import android.content.Context;
import android.os.Vibrator;
import android.speech.RecognizerIntent;
import android.app.Activity;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.support.v7.widget.ShareActionProvider;
import android.widget.Toast;
import android.support.v7.app.ActionBar.OnNavigationListener;
import android.support.v7.app.ActionBar;
import android.support.v4.app.ShareCompat;

@SuppressLint("DefaultLocale") public class MainActivity extends ActionBarActivity {
protected static final int REQUEST_OK = 1;
ListView l1;
ArrayList<Array_songs> songlist;
EditText e1;
Song_adapter adp;
private ShareActionProvider MenuSAP;

ImageButton ib;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ActionBar actionBar = getSupportActionBar();
    //actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);
    actionBar.setDisplayShowHomeEnabled(true);
    actionBar.setIcon(R.drawable.iconw);

    l1=(ListView)findViewById(R.id.lv1);
    ib=(ImageButton)findViewById(R.id.ib1);
    songlist=new ArrayList<Array_songs>();
    e1= (EditText)findViewById(R.id.editText1);
    e1.addTextChangedListener(tw);

    ib.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            Intent i=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
            try{
                startActivityForResult(i,REQUEST_OK );
            }catch(ActivityNotFoundException r){
                Toast.makeText(getApplicationContext(),"song cant be played", Toast.LENGTH_SHORT).show();

            }

        }
    });

    adp=new Song_adapter(MainActivity.this, songlist, this.getApplication());
    l1.setAdapter(adp);
    getSongList("");

    l1.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {

            int sCB = getVar();
            if(sCB == 0) {
                Array_songs slist = songlist.get(position);
                String Song_Title = slist.get_title();
                String Song_Artist = slist.get_artist();
                long Song_ID = slist.get_id();

                //Toast.makeText(getApplicationContext(), Song_Artist + Song_Title + String.valueOf(Song_ID), Toast.LENGTH_SHORT).show();

                // TODO Auto-generated method stub

                Uri song_path = ContentUris.withAppendedId(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, Song_ID);

                Intent musicplayer = new Intent(Intent.ACTION_VIEW);
                musicplayer.setDataAndType(song_path, "audio/*");

                try {

                    startActivity(musicplayer);

                } catch (ActivityNotFoundException e) {

                    Toast.makeText(getApplicationContext(), "Try Again", Toast.LENGTH_SHORT).show();

                }

            }
            else
            {

            }

        }
    });

    l1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
            changeVar();
            vibrate();
            int select = l1.getSelectedItemPosition();
            l1.setItemChecked(select, true);
            adp.notifyDataSetChanged();
            return false;
        }
    });
}

private void vibrate() {
    Vibrator v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
    v.vibrate(120);
}

private void changeVar() {
    ((SyncClass) this.getApplication()).setShowCheckBox(1);
}

private int getVar()
{
    Integer sCB = Integer.parseInt(((SyncClass) this.getApplication()).getShowCheckBox());
    return sCB;
}

TextWatcher tw=new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub
        songlist.clear();
        adp.notifyDataSetChanged();
        getSongList(s.toString());

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub

    }
};

protected void  onActivityResult(int requestcode,int resultcode,Intent data){

    super.onActivityResult(requestcode, resultcode, data);

    if(requestcode==REQUEST_OK && resultcode==RESULT_OK){
        ArrayList<String> ls=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

        e1.setText(ls.get(0));

    }

}

public void getSongList(String stitle){
    ContentResolver cr= getContentResolver();
    Uri music=android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    Cursor mus=cr.query(music, null, null, null, null);

    if(mus != null && mus.moveToFirst()){

        int titleint=mus.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
        int artistint= mus.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);
        int songid=mus.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
        do{
            String songTitle=mus.getString(titleint);
            String songArtist=mus.getString(artistint);
            long  songId=mus.getLong(songid);

            if(songTitle.toUpperCase().contains(stitle.toUpperCase())){

                songlist.add(new Array_songs(songId, songTitle, songArtist));

            }

        }while(mus.moveToNext());

    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    MenuItem item = menu.findItem(R.id.menu_item_share);
    MenuSAP = new ShareActionProvider(this);
    MenuSAP.setShareIntent(createShareIntent());
    MenuItemCompat.setActionProvider(item, MenuSAP);
    return super.onCreateOptionsMenu(menu);
}

private Intent createShareIntent() {
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("audio/*");
    shareIntent.putExtra(Intent.EXTRA_MIME_TYPES,"audio/*");
    return shareIntent;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onBackPressed() {
    int check;
    check = getVar();
    if(check == 1)
    {
        ((SyncClass) this.getApplication()).setShowCheckBox(0);
        adp.notifyDataSetChanged();
    }
    else
    {
        super.onBackPressed();
    }

}
}
</code>```

SongAdapter.java

```<code>public class Song_adapter extends BaseAdapter {
private ArrayList<Array_songs> song_ob;
private LayoutInflater inflator_ob;
private Application xyz;
//private int sCB = ((SyncClass) this.getApplication()).getSomeVariable();
public Song_adapter(Context c,ArrayList<Array_songs> songlist, Application a)
{
    song_ob=songlist;
    inflator_ob= LayoutInflater.from(c);
    xyz = a;
}

@Override
public int getCount() {

    // TODO Auto-generated method stub
    return song_ob.size();
}

@Override
public Object getItem(int arg0) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public long getItemId(int arg0) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public View getView(int position, View v, ViewGroup parent) {
    // TODO Auto-generated method stub
    LinearLayout lin_ob =(LinearLayout)inflator_ob.inflate(R.layout.song_content, parent,false) ;
    Array_songs ars_ob= song_ob.get(position);
    TextView title= (TextView)lin_ob.findViewById(R.id.song_name);
    TextView artist= (TextView)lin_ob.findViewById(R.id.artist);
    //CheckBox check = (CheckBox) lin_ob.findViewById(R.id.cbselect);
    if(((SyncClass) xyz).getShowCheckBox() == "1")
    {
        lin_ob.findViewById(R.id.cbselect).setVisibility(View.VISIBLE);
    }
    else
    {
        lin_ob.findViewById(R.id.cbselect).setVisibility(View.GONE);
    }

    String stitle= ars_ob.get_title();
    String sartist= ars_ob.get_artist();

    title.setText(stitle);
    artist.setText(sartist);

    return lin_ob;

}

}
</code>```

SyncClass.java

```<code>public class SyncClass extends Application {
private String showCheckBox = "0";

public String getShowCheckBox()
{
    return showCheckBox;
}

public void setShowCheckBox(int showCheckBox)
{
    this.showCheckBox = Integer.toString(showCheckBox);
}
}
</code>```

menu_main.xml

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"      tools:context=".MainActivity"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/action_settings"
    android:title="@string/action_settings"
    android:orderInCategory="100"
    app:showAsAction="never" />
<item
    android:id="@+id/menu_item_share"
    app:showAsAction="ifRoom"
    android:title="Share"
    android:actionProviderClass="android.widget.ShareActionProvider" />
</code>```

Also i want to apply the material design theme to my project.. and i have done the following:-

Android Manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.musicginni" >
<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<application
    android:allowBackup="true"
    android:icon="@drawable/iconw"
    android:theme="@style/Theme.AppCompat"
    android:name=".SyncClass">
    <activity
        android:name=".StartUp"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAINACTIVITY" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
</application>

</manifest>
</code>```

this is the styles.xml(v21) file

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="android:Theme.Material.Light">
    <item name="android:colorPrimary">#ff95609b</item>
    <item name="android:colorPrimaryDark">#ff644469</item>
    <item name="android:textColorPrimary">#fff8f7ec</item>
    <item name="android:windowBackground">@color/custom_theme_color</item>
    <item name="android:navigationBarColor">#ff403a25</item>
</style>
<color name="custom_theme_color">#ffffffff</color>
</resources>
</code>```

Styles.xml file

```<code><resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="android:actionBarStyle">@style/MyActionBar</item>
    <item name="android:absListViewStyle">@style/MyListView</item>
</style>
<style name="MyActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
    <item name="android:background">#ff774d7d</item>
</style>
<style name="MyListView" parent="@android:style/Widget.Holo.Light.ListView">
    <item name="android:background">#ffb3aac6</item>
</style>

</resources>
</code>```

The material design was working fine before i compiled the appcompat v7 library and used ActionBarActivity instead of Activity..

答:
You have to check the following steps

If your activity extends from AppCompatActivity, you have to change on the
menu_main.xml the item that must begin with app:showAsActio...or app:actionProvider etc.

You must import the correct (import:android.support.v7.widget.ShareActionProvider)...

And on the method onCreateOptionsMenu (Menu menuItem) you have to attribute the value MenuItemCompat.getActioProvider(menuItem) instead of just menuItem(getActionProvider).

Body:
Share button does not appear on the action bar.. Please help..!!
Here is the code::

MainActivity.java

import java.util.ArrayList;
import java.util.Currency;
import android.content.Context;
import android.os.Vibrator;
import android.speech.RecognizerIntent;
import android.app.Activity;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.support.v7.widget.ShareActionProvider;
import android.widget.Toast;
import android.support.v7.app.ActionBar.OnNavigationListener;
import android.support.v7.app.ActionBar;
import android.support.v4.app.ShareCompat;

@SuppressLint("DefaultLocale") public class MainActivity extends ActionBarActivity {
protected static final int REQUEST_OK = 1;
ListView l1;
ArrayList<Array_songs> songlist;
EditText e1;
Song_adapter adp;
private ShareActionProvider MenuSAP;

ImageButton ib;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ActionBar actionBar = getSupportActionBar();
    //actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);
    actionBar.setDisplayShowHomeEnabled(true);
    actionBar.setIcon(R.drawable.iconw);

    l1=(ListView)findViewById(R.id.lv1);
    ib=(ImageButton)findViewById(R.id.ib1);
    songlist=new ArrayList<Array_songs>();
    e1= (EditText)findViewById(R.id.editText1);
    e1.addTextChangedListener(tw);

    ib.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            Intent i=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
            try{
                startActivityForResult(i,REQUEST_OK );
            }catch(ActivityNotFoundException r){
                Toast.makeText(getApplicationContext(),"song cant be played", Toast.LENGTH_SHORT).show();

            }

        }
    });

    adp=new Song_adapter(MainActivity.this, songlist, this.getApplication());
    l1.setAdapter(adp);
    getSongList("");

    l1.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {

            int sCB = getVar();
            if(sCB == 0) {
                Array_songs slist = songlist.get(position);
                String Song_Title = slist.get_title();
                String Song_Artist = slist.get_artist();
                long Song_ID = slist.get_id();

                //Toast.makeText(getApplicationContext(), Song_Artist + Song_Title + String.valueOf(Song_ID), Toast.LENGTH_SHORT).show();

                // TODO Auto-generated method stub

                Uri song_path = ContentUris.withAppendedId(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, Song_ID);

                Intent musicplayer = new Intent(Intent.ACTION_VIEW);
                musicplayer.setDataAndType(song_path, "audio/*");

                try {

                    startActivity(musicplayer);

                } catch (ActivityNotFoundException e) {

                    Toast.makeText(getApplicationContext(), "Try Again", Toast.LENGTH_SHORT).show();

                }

            }
            else
            {

            }

        }
    });

    l1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
            changeVar();
            vibrate();
            int select = l1.getSelectedItemPosition();
            l1.setItemChecked(select, true);
            adp.notifyDataSetChanged();
            return false;
        }
    });
}

private void vibrate() {
    Vibrator v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
    v.vibrate(120);
}

private void changeVar() {
    ((SyncClass) this.getApplication()).setShowCheckBox(1);
}

private int getVar()
{
    Integer sCB = Integer.parseInt(((SyncClass) this.getApplication()).getShowCheckBox());
    return sCB;
}

TextWatcher tw=new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub
        songlist.clear();
        adp.notifyDataSetChanged();
        getSongList(s.toString());

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub

    }
};

protected void  onActivityResult(int requestcode,int resultcode,Intent data){

    super.onActivityResult(requestcode, resultcode, data);

    if(requestcode==REQUEST_OK && resultcode==RESULT_OK){
        ArrayList<String> ls=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

        e1.setText(ls.get(0));

    }

}

public void getSongList(String stitle){
    ContentResolver cr= getContentResolver();
    Uri music=android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    Cursor mus=cr.query(music, null, null, null, null);

    if(mus != null && mus.moveToFirst()){

        int titleint=mus.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
        int artistint= mus.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);
        int songid=mus.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
        do{
            String songTitle=mus.getString(titleint);
            String songArtist=mus.getString(artistint);
            long  songId=mus.getLong(songid);

            if(songTitle.toUpperCase().contains(stitle.toUpperCase())){

                songlist.add(new Array_songs(songId, songTitle, songArtist));

            }

        }while(mus.moveToNext());

    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    MenuItem item = menu.findItem(R.id.menu_item_share);
    MenuSAP = new ShareActionProvider(this);
    MenuSAP.setShareIntent(createShareIntent());
    MenuItemCompat.setActionProvider(item, MenuSAP);
    return super.onCreateOptionsMenu(menu);
}

private Intent createShareIntent() {
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("audio/*");
    shareIntent.putExtra(Intent.EXTRA_MIME_TYPES,"audio/*");
    return shareIntent;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onBackPressed() {
    int check;
    check = getVar();
    if(check == 1)
    {
        ((SyncClass) this.getApplication()).setShowCheckBox(0);
        adp.notifyDataSetChanged();
    }
    else
    {
        super.onBackPressed();
    }

}
}

SongAdapter.java

public class Song_adapter extends BaseAdapter {
private ArrayList<Array_songs> song_ob;
private LayoutInflater inflator_ob;
private Application xyz;
//private int sCB = ((SyncClass) this.getApplication()).getSomeVariable();
public Song_adapter(Context c,ArrayList<Array_songs> songlist, Application a)
{
    song_ob=songlist;
    inflator_ob= LayoutInflater.from(c);
    xyz = a;
}

@Override
public int getCount() {

    // TODO Auto-generated method stub
    return song_ob.size();
}

@Override
public Object getItem(int arg0) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public long getItemId(int arg0) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public View getView(int position, View v, ViewGroup parent) {
    // TODO Auto-generated method stub
    LinearLayout lin_ob =(LinearLayout)inflator_ob.inflate(R.layout.song_content, parent,false) ;
    Array_songs ars_ob= song_ob.get(position);
    TextView title= (TextView)lin_ob.findViewById(R.id.song_name);
    TextView artist= (TextView)lin_ob.findViewById(R.id.artist);
    //CheckBox check = (CheckBox) lin_ob.findViewById(R.id.cbselect);
    if(((SyncClass) xyz).getShowCheckBox() == "1")
    {
        lin_ob.findViewById(R.id.cbselect).setVisibility(View.VISIBLE);
    }
    else
    {
        lin_ob.findViewById(R.id.cbselect).setVisibility(View.GONE);
    }

    String stitle= ars_ob.get_title();
    String sartist= ars_ob.get_artist();

    title.setText(stitle);
    artist.setText(sartist);

    return lin_ob;

}

}

SyncClass.java

public class SyncClass extends Application {
private String showCheckBox = "0";

public String getShowCheckBox()
{
    return showCheckBox;
}

public void setShowCheckBox(int showCheckBox)
{
    this.showCheckBox = Integer.toString(showCheckBox);
}
}

menu_main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"      tools:context=".MainActivity"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/action_settings"
    android:title="@string/action_settings"
    android:orderInCategory="100"
    app:showAsAction="never" />
<item
    android:id="@+id/menu_item_share"
    app:showAsAction="ifRoom"
    android:title="Share"
    android:actionProviderClass="android.widget.ShareActionProvider" />

Also i want to apply the material design theme to my project.. and i have done the following:-

Android Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.musicginni" >
<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<application
    android:allowBackup="true"
    android:icon="@drawable/iconw"
    android:theme="@style/Theme.AppCompat"
    android:name=".SyncClass">
    <activity
        android:name=".StartUp"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAINACTIVITY" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
</application>

</manifest>

this is the styles.xml(v21) file

<?xml version="1.0" encoding="utf-8"?>
<resources>

<color name="custom_theme_color">#ffffffff</color>
</resources>

Styles.xml file

<resources>

</resources>

The material design was working fine before i compiled the appcompat v7 library and used ActionBarActivity instead of Activity..


问:
TYPO3 Remove "Select & Upload Files" button
Removing the "Select & Upload Files" button from Page properties works with the following line in PageTSConfig:

```<code>TCEFORM.pages.media.config.appearance.fileUploadAllowed = 0
</code>```

Now I want to remove the "Select & Upload Files" button within content elements (for example with CType "textmedia"), too.

I tried out several things, but with no success. I found no working PageTSConfig "rule" for this case. Does somebody know how the "Select & Upload Files" button can be removed for content elements like textmedia elements?

Using TYPO3 8.7.1

答:
You can set for each field separately, see post from Kevin Appelt. In this case you need to remember for any further field in future to add this setting too.
To adapt file upload for all fields globaly, you can use UserTSConfig edit_docModuleUpload. See https://docs.typo3.org/typo3cms/TSconfigReference/singlehtml/Index.html#document-UserTsconfig/Setup/Index

To avoid file upload for all fields simple add to ext_localconf.php of your customer extension (sitepackage):

```<code>\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addUserTSConfig('setup.override.edit_docModuleUpload = 0');
</code>```

If you want use a separate configuration file for UserTSConfig, which I recommend add to ext_localconf.php

```<code>\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addUserTSConfig('<INCLUDE_TYPOSCRIPT: source="FILE:EXT:sitepackage/Configuration/TypoScript/User/Default.ts">');
</code>```

and in your extension /Configuration/TypoScript/User/Default.ts

```<code>setup.override.edit_docModuleUpload = 0
</code>```

If you also want exclude file upload and folder creation in file element browser (popup window) add following code to your extension /Configuration/TypoScript/User/Default.ts

```<code># Hide 'file upload' and 'create folder' in link- and element browser
options.folderTree.uploadFieldsInLinkBrowser = 0
options.folderTree.hideCreateFolder = 1
options.createFoldersInEB = 1
</code>```

Body:
Removing the "Select & Upload Files" button from Page properties works with the following line in PageTSConfig:

TCEFORM.pages.media.config.appearance.fileUploadAllowed = 0

Now I want to remove the "Select & Upload Files" button within content elements (for example with CType "textmedia"), too.

I tried out several things, but with no success. I found no working PageTSConfig "rule" for this case. Does somebody know how the "Select & Upload Files" button can be removed for content elements like textmedia elements?

Using TYPO3 8.7.1

Body:
You can set for each field separately, see post from Kevin Appelt. In this case you need to remember for any further field in future to add this setting too.
To adapt file upload for all fields globaly, you can use UserTSConfig edit_docModuleUpload. See https://docs.typo3.org/typo3cms/TSconfigReference/singlehtml/Index.html#document-UserTsconfig/Setup/Index

To avoid file upload for all fields simple add to ext_localconf.php of your customer extension (sitepackage):

\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addUserTSConfig('setup.override.edit_docModuleUpload = 0');

If you want use a separate configuration file for UserTSConfig, which I recommend add to ext_localconf.php

\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addUserTSConfig('<INCLUDE_TYPOSCRIPT: source="FILE:EXT:sitepackage/Configuration/TypoScript/User/Default.ts">');

and in your extension /Configuration/TypoScript/User/Default.ts

setup.override.edit_docModuleUpload = 0

If you also want exclude file upload and folder creation in file element browser (popup window) add following code to your extension /Configuration/TypoScript/User/Default.ts

# Hide 'file upload' and 'create folder' in link- and element browser
options.folderTree.uploadFieldsInLinkBrowser = 0
options.folderTree.hideCreateFolder = 1
options.createFoldersInEB = 1


问:
How to "redefine" one char * to another char *?
Something like that: (it is task, how to do this, and not to change body of main function)

I thought that it is too simple... but... I don't know how to do it...

```<code>#include <iostream>

#define "a" "b"

int main( int argc,char ** argv) {
   std::cout << "a";
   return 0;
}
</code>```

// output: b

How to do it?

答:
Changing C++ output without changing the main() function

for example from that topic:

```<code>#include <iostream>
#include <cstdio>
#include <sstream>

#define cout     printf("a"); std::ostringstream os; os

int main()
{
    std::cout << "b";
}
</code>```

a simplier one:

```<code>#include <iostream>
#define cout cout << "a"; return 0; std::cout
int main()
{
    std::cout << "b";
}
</code>```

Body:
Something like that: (it is task, how to do this, and not to change body of main function)

I thought that it is too simple... but... I don't know how to do it...

#include <iostream>

#define "a" "b"

int main( int argc,char ** argv) {
   std::cout << "a";
   return 0;
}

// output: b

How to do it?

Body:
Changing C++ output without changing the main() function

for example from that topic:

#include <iostream>
#include <cstdio>
#include <sstream>

#define cout     printf("a"); std::ostringstream os; os

int main()
{
    std::cout << "b";
}

a simplier one:

#include <iostream>
#define cout cout << "a"; return 0; std::cout
int main()
{
    std::cout << "b";
}


问:
How to kill Java LWP (Light weight process) Linux
Is there any way to kill LWP.

I have a web application and two LWP and running continuously from last 16 hours. And those process consuming lots of core because of that cpu consumption gone 100%. I wonder if i can kill this LWP without affecting running application.

答: Get PID of LWP and use kill -9 command to terminate them. Before terminating them check if they are related with your application </p>


问:
Opening a resizable window in Pygame in Fullscreen
I'm making a firework simulation in pygame, and I want to be able to run the program, and have it open up in full screen. Not the pygame.FULLSCREEN, I still want to be able to use pygame.QUIT.

I don't know if this is possible, but if anyone could help, please share your ideas!

Here's my code for the screen:

```<code>import pygame
screen = pygame.display.set_mode((0, 0), pygame.RESIZABLE)
</code>```

答:
You could use the width and height of the screen to setup the resolution, like in this post, by using the VideoInfo object provided by pygame:</p>

```<code>import pygame

pygame.init()
video_infos = pygame.display.Info()
width, height = video_infos.current_w, video_infos.current_h
screen = pygame.display.set_mode((width, height), pygame.RESIZABLE)
# [...]
</code>```

Body:
I'm making a firework simulation in pygame, and I want to be able to run the program, and have it open up in full screen. Not the pygame.FULLSCREEN, I still want to be able to use pygame.QUIT.

I don't know if this is possible, but if anyone could help, please share your ideas!

Here's my code for the screen:

import pygame
screen = pygame.display.set_mode((0, 0), pygame.RESIZABLE)

Body:
You could use the width and height of the screen to setup the resolution, like in this post, by using the VideoInfo object provided by pygame:

import pygame

pygame.init()
video_infos = pygame.display.Info()
width, height = video_infos.current_w, video_infos.current_h
screen = pygame.display.set_mode((width, height), pygame.RESIZABLE)
# [...]


问:
Can Jquery take the form input straight from the form, or do I have to use a SET button in my script?
I've got a script that is a simple countdown.
You can put in a number press SET and then click START and the number will count down.

I use this in the gym, but I forget to press the SET button a lot after entering the new count.

Is it possible to let jquery take the form input or do I have to use a SET button?

```<code>var CCOUNT;
$(document).ready(function() {
  $('#btnct').click(function() {
    CCOUNT = $('#seconds').val();
    cdreset();
  });
});
var t, count;

function cddisplay() {
  document.getElementById('timespan').innerHTML = count;

}

function countdown() {
  // starts countdown
  cddisplay();
  changeColor(CCOUNT);
  if (count === 0) {
    // time is up

  } else {
    count--;
    t = setTimeout(countdown, 1000);
    $("#onebuttons").attr('disabled', 'disabled');

  }
}

function cdpause() {
  // pauses countdown
  clearTimeout(t);
  $("#onebuttons").removeAttr('disabled');
}

function cdreset() {
  // resets countdown
  cdpause();
  count = CCOUNT;
  cddisplay();
  $("#onebuttons").removeAttr('disabled');
}

function changeColor() {
  if (count <= 1000 && count > 29) {
    document.getElementById('timespan').style.color = "#00CC00";

  } else if (count <= 29 && count > 9) {
    document.getElementById('timespan').style.color = "#F87217";
  } else if (count <= 9 && count > 3) {
    document.getElementById('timespan').style.color = "#ff0000";
  } else if (count === 3) {

    var audio = document.createElement("audio");
    audio.src = "3-2-1-0.m4a";
    audio.play();
  }

  if (count === 0) {
    document.getElementById('timespan').style.color = "#ffffff";

  }
  if (count < 10) {
    $("#timespan").fadeOut('slow', function() {
      $("#timespan").text(count);
      $("#timespan").fadeIn();
    });

  }
}
</code>```

答:
yes, just let the call out of the on click method
like this

```<code>var CCOUNT;
$(document).ready(function() {
    CCOUNT = $('#seconds').val();
    cdreset();
});
</code>```

It will make your method fire at the time the page finnish loads

Body:
I've got a script that is a simple countdown.
You can put in a number press SET and then click START and the number will count down.

I use this in the gym, but I forget to press the SET button a lot after entering the new count.

Is it possible to let jquery take the form input or do I have to use a SET button?

var CCOUNT;
$(document).ready(function() {
  $('#btnct').click(function() {
    CCOUNT = $('#seconds').val();
    cdreset();
  });
});
var t, count;

function cddisplay() {
  document.getElementById('timespan').innerHTML = count;

}

function countdown() {
  // starts countdown
  cddisplay();
  changeColor(CCOUNT);
  if (count === 0) {
    // time is up

  } else {
    count--;
    t = setTimeout(countdown, 1000);
    $("#onebuttons").attr('disabled', 'disabled');

  }
}

function cdpause() {
  // pauses countdown
  clearTimeout(t);
  $("#onebuttons").removeAttr('disabled');
}

function cdreset() {
  // resets countdown
  cdpause();
  count = CCOUNT;
  cddisplay();
  $("#onebuttons").removeAttr('disabled');
}

function changeColor() {
  if (count <= 1000 && count > 29) {
    document.getElementById('timespan').style.color = "#00CC00";

  } else if (count <= 29 && count > 9) {
    document.getElementById('timespan').style.color = "#F87217";
  } else if (count <= 9 && count > 3) {
    document.getElementById('timespan').style.color = "#ff0000";
  } else if (count === 3) {

    var audio = document.createElement("audio");
    audio.src = "3-2-1-0.m4a";
    audio.play();
  }

  if (count === 0) {
    document.getElementById('timespan').style.color = "#ffffff";

  }
  if (count < 10) {
    $("#timespan").fadeOut('slow', function() {
      $("#timespan").text(count);
      $("#timespan").fadeIn();
    });

  }
}

Body:
yes, just let the call out of the on click method
like this

var CCOUNT;
$(document).ready(function() {
    CCOUNT = $('#seconds').val();
    cdreset();
});

It will make your method fire at the time the page finnish loads