问:
In a Swagger YAML definition, is there a way to avoid duplication among HTTP methods?
I am writing an API spec for which I want the PUT and PATCH functionality to be identical. It won't matter whether the API receives a PUT or a PATCH request. It will do the same thing.

Is there a shorthand/reference syntax for this that would prevent me from copying and pasting the parameters and responses, etc. from my PUT method definition to the PATCH method definition?

答:
No.

Although the OpenAPI (fka Swagger) Specification 2.0 supports $ref in some places of an API definition, it's not supported on the operation level. So you need to have separate definitions for PUT and PATCH. You can reduce the code duplication somewhat by $refing parameters and responses within each operation.

```<code>paths:
  /foo:
    # If ALL operations within a path have some common parameters,
    # define these params on the path level instead
    # parameters:
    #  - $ref: '#/parameters/baz'

    put:
      parameters:
        - $ref: '#/parameters/baz'
      responses:
        200:
          $ref: '#/responses/Success'
        default:
          $ref: '#/responses/Error'
    patch:
      parameters:
        - $ref: '#/parameters/baz'
      responses:
        200:
          $ref: '#/responses/Success'
        default:
          $ref: '#/responses/Error'

parameters:
  baz:
    in: query
    name: baz
    type: string

responses:
  Success:
    description: Operation completed successfully
    schema:
      type: object
      ...
  Error:
    description: Error response
    schema:
      type: object
      ...
</code>```

Body:
No.

Although the OpenAPI (fka Swagger) Specification 2.0 supports $ref in some places of an API definition, it's not supported on the operation level. So you need to have separate definitions for PUT and PATCH. You can reduce the code duplication somewhat by $refing parameters and responses within each operation.

paths:
  /foo:
    # If ALL operations within a path have some common parameters,
    # define these params on the path level instead
    # parameters:
    #  - $ref: '#/parameters/baz'

    put:
      parameters:
        - $ref: '#/parameters/baz'
      responses:
        200:
          $ref: '#/responses/Success'
        default:
          $ref: '#/responses/Error'
    patch:
      parameters:
        - $ref: '#/parameters/baz'
      responses:
        200:
          $ref: '#/responses/Success'
        default:
          $ref: '#/responses/Error'

parameters:
  baz:
    in: query
    name: baz
    type: string

responses:
  Success:
    description: Operation completed successfully
    schema:
      type: object
      ...
  Error:
    description: Error response
    schema:
      type: object
      ...


来源: stackexchange

问:
why use<bean:include instead of <jsp:include in struts?
why use<bean:include instead of <jsp:include in struts?

答:
from the documentation for bean:include

Perform an internal dispatch to the specified application component (or external URL) and make the response data from that request available as a bean of type String. This tag has a function similar to that of the standard jsp:include tag, except that the response data is stored in a page scope attribute instead of being written to the output stream. If the current request is part of a session, the generated request for the include will also include the session identifier (and thus be part of the same session).

first hit on google

ContentLicense: CC BY-SA 2.5


问:
Intellij "go to > implementation/declaration" navigation feature not working
I have a maven java project that I would like to use IntelliJ for development on. One of my favorite navigation features of IntelliJ is the 'go to > implementation' feature that appears when you right click on a method or function.

My problem is that this feature is not working for me; when I choose it nothing happens, no error, it just sits right where it is. It also isn't suggesting functions and methods as I type, so it's as if IntelliJ is failing to recognize dependencies and relationships among the various classes in my project.

I know the code is fine because it compiles and runs, has anyone else experienced this? I made sure to open the project as a maven project using the pom.xml file but that made no difference.

答:
Ishnark's comment on my question provided the solution I needed, reposting here so that it can be upvoted and hopefully help others. All I needed to do was right click on the source root of the projecet and select "Mark Directory As > Sources Root". More details here:

solution

ContentLicense: CC BY-SA 3.0


问:
React setState not Updating Immediately
I'm working on a todo application. This is a very simplified version of the offending code. I have a checkbox:

```<code> <p><input type="checkbox"  name="area" checked={this.state.Pencil}   onChange={this.checkPencil}/> Writing Item </p>
</code>```

Here's the function that calls the checkbox:

```<code>checkPencil(){
   this.setState({
      pencil:!this.state.pencil,
  });
  this.props.updateItem(this.state);
}
</code>```

updateItem is a function that's mapped to dispatch to redux

```<code>function mapDispatchToProps(dispatch){
  return bindActionCreators({ updateItem}, dispatch);
}
</code>```

My problem is that when I call the updateItem action and console.log the state, it is always 1 step behind. If the checkbox is unchecked and not true, I still get the state of true being passed to the updateItem function. Do I need to call another function to force the state to update?

答:
When you're updating your state using a property of the current state, React documentation advise you to use the function call version of setState instead of the object.

So setState((state, props) => {...}) instead of setState(object).

The reason is that setState is more of a request for the state to change rather than an immediate change. React batches those setState calls for performance improvement.

Meaning the state property you're checking might not be stable.
This is a potential pitfall to be aware of.

For more info see documentation here: https://facebook.github.io/react/docs/react-component.html#setstate

To answer your question, i'd do this.

```<code>checkPencil(){
    this.setState((prevState) => {
        return {
            pencil: !prevState.pencil
        };
    }, () => {
        this.props.updateItem(this.state)
    });
}
</code>```

Title: React setState not Updating Immediately

Body:
I'm working on a todo application. This is a very simplified version of the offending code. I have a checkbox:

<input type="checkbox"  name="area" checked={this.state.Pencil}   onChange={this.checkPencil}/> Writing Item

Here's the function that calls the checkbox:

checkPencil(){
   this.setState({
      pencil:!this.state.pencil,
  });
  this.props.updateItem(this.state);
}

updateItem is a function that's mapped to dispatch to redux

function mapDispatchToProps(dispatch){
  return bindActionCreators({ updateItem}, dispatch);
}

My problem is that when I call the updateItem action and console.log the state, it is always 1 step behind. If the checkbox is unchecked and not true, I still get the state of true being passed to the updateItem function. Do I need to call another function to force the state to update?

Body:
When you're updating your state using a property of the current state, React documentation advise you to use the function call version of setState instead of the object.

So setState((state, props) => {...}) instead of setState(object).

The reason is that setState is more of a request for the state to change rather than an immediate change. React batches those setState calls for performance improvement.

Meaning the state property you're checking might not be stable.
This is a potential pitfall to be aware of.

For more info see documentation here: https://facebook.github.io/react/docs/react-component.html#setstate

To answer your question, i'd do this.

checkPencil(){
    this.setState((prevState) => {
        return {
            pencil: !prevState.pencil
        };
    }, () => {
        this.props.updateItem(this.state)
    });
}


问:
How can I add a 3d object as a marker on Google Maps like Uber does
I want to add a 3d marker for showing cars on map with rotation like Uber does but I can't find any information on adding 3d objects on Google Maps SDK for iOS.

Would appreciate any help.

Apparently no one is seeing what OP and I are seeing so here's a video of a Uber car turning 90 degrees. Play it frame by frame and you'll notice that it's not a simple image rotation. Either Uber went through the trouble of doing ~360 angles of each vehicles, or it really is a 3D model. Doing 360 images of every car seems foolish to me.

答:
From what I can tell, they are not using 3D objects. They are also not animating between 400 images of a car at a different angle. They're doing a mix of rotating image assets and animating between ~50-70 images of a car at different angles. The illusion is perfect because it really does look like they used 3D car models !

Look at this GIF of a Uber car turning a corner (Dropbox link):

We can clearly see that that the shadow and the car's view angle doesn't update as often as the car's rotation.

Here I overlaid 2 images of the car at different angles, but using the same car image:

We can see that the map is rotated ~5 degrees but the car image is perfectly clear because it hasn't changed, it was simply rotated.


问:
Min-height on class doesn't work
I'm creating a website, but have a little problem, that I don't know how to solve.

```<code> <div id="middle">
        <div id="clock">Here shows JS clock</div><br>
        <div class="element">
            <img  height="80px" src="SOURCE"/><h1 style="float:left" >TITLE TEXT</h1><div class="clearboth"></div>
             TITLE TEXT
        </div>
        <div class="clearboth"></div>
        <div class="element">
            <img  height="80px" src="SOURCE"/><h1 style="float:left">TITLE TEXT</h1><div class="clearboth"></div>
            <p>SOME TEXT</p>
        </div>
</code>```

And CSS

```<code>    .element{
        background-color:#fff;
        min-heigth:100px;
    }
    #middle{
        font-family:'Roboto', monospace;
        padding-left:5px;
        padding-right:5px;
        min-height:1000px;
        width:1000px;
        background-color:#ffffff;
        margin:auto;
    }
    #middle > h1,h2,h3{
        font-family: 'VT323', monospace;
        font-size:34px;
        margin-left:20px;
    }
.clearboth{
    clear:both;
}

    #middle  p{
        text-indent: 40px;
        font-size:18px;
    }
</code>```

But it min-height doesn't work - next element starts right after previous one.

答:
Try this, min-height spelled wrong and your #middle div isn't closed.

    .element{
        background-color:#fff;
        min-height:100px;
    }
    #middle{
        font-family:'Roboto', monospace;
        padding-left:5px;
        padding-right:5px;
        min-height:1000px;
        width:1000px;
        background-color:#ffffff;
        margin:auto;
    }
    #middle > h1,h2,h3{
        font-family: 'VT323', monospace;
        font-size:34px;
        margin-left:20px;
    }
.clearboth{
    clear:both;
}

    #middle  p{
        text-indent: 40px;
        font-size:18px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="middle">
    <div id="clock">Here shows JS clock</div><br>
    <div class="element">
        <img  height="80px" src="SOURCE"/><h1 style="float:left" >TITLE TEXT</h1><div class="clearboth"></div>
         TITLE TEXT
    </div>
    <div class="clearboth"></div>
    <div class="element">
        <img  height="80px" src="SOURCE"/><h1 style="float:left">TITLE TEXT</h1><div class="clearboth"></div>
        <p>SOME TEXT</p>
    </div>
</div></code>```

Title: Min-height on class doesn't work

Body:
I'm creating a website, but have a little problem, that I don't know how to solve.

Here shows JS clock

TITLE TEXT

             TITLE TEXT

TITLE TEXT

SOME TEXT

And CSS

    .element{
        background-color:#fff;
        min-heigth:100px;
    }
    #middle{
        font-family:'Roboto', monospace;
        padding-left:5px;
        padding-right:5px;
        min-height:1000px;
        width:1000px;
        background-color:#ffffff;
        margin:auto;
    }
    #middle > h1,h2,h3{
        font-family: 'VT323', monospace;
        font-size:34px;
        margin-left:20px;
    }
.clearboth{
    clear:both;
}

    #middle  p{
        text-indent: 40px;
        font-size:18px;
    }

But it min-height doesn't work - next element starts right after previous one.

Body:
Try this, min-height spelled wrong and your #middle div isn't closed.

    .element{
        background-color:#fff;
        min-height:100px;
    }
    #middle{
        font-family:'Roboto', monospace;
        padding-left:5px;
        padding-right:5px;
        min-height:1000px;
        width:1000px;
        background-color:#ffffff;
        margin:auto;
    }
    #middle > h1,h2,h3{
        font-family: 'VT323', monospace;
        font-size:34px;
        margin-left:20px;
    }
.clearboth{
    clear:both;
}

    #middle  p{
        text-indent: 40px;
        font-size:18px;
    }

<div id="middle">
    <div id="clock">Here shows JS clock</div><br>
    <div class="element">
        <img  height="80px" src="SOURCE"/><h1 style="float:left" >TITLE TEXT</h1><div class="clearboth"></div>
         TITLE TEXT
    </div>
    <div class="clearboth"></div>
    <div class="element">
        <img  height="80px" src="SOURCE"/><h1 style="float:left">TITLE TEXT</h1><div class="clearboth"></div>
        <p>SOME TEXT</p>
    </div>
</div>


问:
Analyzing non-Visual Studio, Unity C# code with MSBuild/SonarQube via Jenkins
I inherited the responsibility for a SonarQube Linux server which was running version 5.1 and analyzing dozens of Unity C# projects. After upgrading it to SQ 6.1 I discovered that support for analyzing C# projects on non-Windows systems was dropped in version 5.5, so I downgraded it to version 5.4 for the present time.

I have subsequently set up a Windows system as a Jenkins node and SonarQube server. However, the projects I am hoping to evaluate with SonarQube are (mostly) developed on and (always) built on macOS in Unity and therefore lack MSbuild solution files. Is it at all possible for me to use SonarQube within these constraints, short of adding Visual Studio-specific code to the projects? Is there some kind of dummy solution file that I could add to the projects that would allow them to be analyzed without the expectation of a working binary being produced (along the lines of parsing/tokenizing without compiling/linking)? Thanks.

答:
Here is the procedure I have developed for analyzing Unity projects in SonarQube via Jenkins.

A user-facing Jenkins job with the following settings and options, among others specific to my environment.

General—This project is parameterized

String parameter PROJECTKEY

String parameter PROJECTNAME

String parameter PROJECTVERSION

General—Restrict where this project can be run set to the Jenkins build node name you used for your SonarQube server.

Source Code Management

Repository URL set to the repository you want to analyze.

Branches to build set to the main branch, i.e. refs/heads/master.

Additional Behaviors—Recursively update submodules checked as appropriate for your repository.

Build Triggers

Poll SCM checked, but no schedule specified.

Build Environment

Run buildstep before SCM runs—Inject environment variables set to HOME=C:\Users\Jenkins (or as appropriate for your system). This environment variable makes it possible for git to find the correct ssh credentials to use with the Git server. You'll need to put your git private key in %HOME%\.ssh; that is documented elsewhere and left as an exercise to the reader.

Use build environment from another project—Template Project pointing to a second Jenkins job. Mine is called SonarQube_Scanner (see below).

Build

Use builders from another project—Template Project pointing to the same Jenkins job SonarQube_Scanner.

Post-build Actions

Archive the artifacts—Files to archive set to log.zip.

A non-user-facing Jenkins job (SonarQube_Scanner) with the following settings and options.

General—Disable this project checked.

General—Restrict where this project can be run checked and set to your SonarQube server.

Source Code Management set to None.

Build Environment—Inject environment variables to the build process checked.

Properties Content contains

```<code>`LANG=en_US.UTF-8`
</code>```

Build

Execute Windows batch command contains

```<code>set FILENAME=%WORKSPACE%\client\Assets\Editor\SQMenuItems.cs
REM Yes, this syntax works and is sooo much more readable
 > %FILENAME% ECHO using UnityEditor;
>> %FILENAME% ECHO public static class SQMenuItems {
>> %FILENAME% ECHO   static void AssetsOpenCSharpProject() {
>> %FILENAME% ECHO #if UNITY_5
>> %FILENAME% ECHO     EditorApplication.ExecuteMenuItem("Assets/Open C# Project");
>> %FILENAME% ECHO #else
>> %FILENAME% ECHO     EditorApplication.ExecuteMenuItem("Assets/Sync MonoDevelop Project");
>> %FILENAME% ECHO #endif
>> %FILENAME% ECHO     EditorApplication.Exit(0);
>> %FILENAME% ECHO   }
>> %FILENAME% ECHO }
"C:\Program Files\Unity_5.5.2\Editor\Unity.exe" -quit -batchmode -nographics -logFile "%WORKSPACE%\log.txt" -buildTarget android -projectPath %WORKSPACE%\client -executeMethod SQMenuItems.AssetsOpenCSharpProject
"C:\Program Files\7-zip\7z.exe" -tzip a log.zip log.txt
</code>```

SQMenuItems.cs is what triggers Unity to create the .sln and .*proj files that MSBuild needs. The .sln and .*proj files are typically in the .gitignore file and therefore not in the repository.

SonarQube Scanner for MSBuild - Begin Analysis

SonarQube Installation set to the Jenkins build node name you used for your SonarQube server.

Project key set to ${PROJECTKEY}.

Project name set to ${PROJECTNAME}.

Project version set to ${PROJECTVERSION}.

Additional arguments

/d:sonar.exclusions=**\\SQMenuItems.cs

Execute Windows batch command

```<code>"C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe" /maxcpucount /nr:false /nologo /target:rebuild /verbosity:quiet client\client.sln
</code>```

You may need to change client\client.sln above to match your environment. I haven't yet tried replacing that with an environment variable defined in the user-facing Jenkins job.

SonarQube Scanner for MSBuild - End Analysis

DONE

GOTCHAS

If the job fails because Unity fails because it can't find the projectPath, it may have forgotten its license key. Remote desktop to your SonarQube server and launch the Unity GUI. If it pops up asking for your license key, re-enter the key, then quit. Subsequent jobs should succeed.

Things that make it very difficult to pass information to SonarQube in a dynamic way.

Windows environment variables defined in 2.5.1 “Execute Windows batch command” are not preserved through to 2.5.2 “SonarQube Scanner for MSBuild - Begin Analysis”.

The SonarQube.Analysis.xml file specifically prohibits assigning the properties sonar.projectName, sonar.projectKey, and sonar.projectVersion.

I've probably overlooked something; please don't hesitate to inquire.

Body:
Here is the procedure I have developed for analyzing Unity projects in SonarQube via Jenkins.

A user-facing Jenkins job with the following settings and options, among others specific to my environment.

General—This project is parameterized

String parameter PROJECTKEY

String parameter PROJECTNAME

String parameter PROJECTVERSION

General—Restrict where this project can be run set to the Jenkins build node name you used for your SonarQube server.

Source Code Management

Repository URL set to the repository you want to analyze.

Branches to build set to the main branch, i.e. refs/heads/master.

Additional Behaviors—Recursively update submodules checked as appropriate for your repository.

Build Triggers

Poll SCM checked, but no schedule specified.

Build Environment

Run buildstep before SCM runs—Inject environment variables set to HOME=C:\Users\Jenkins (or as appropriate for your system). This environment variable makes it possible for git to find the correct ssh credentials to use with the Git server. You'll need to put your git private key in %HOME%\.ssh; that is documented elsewhere and left as an exercise to the reader.

Use build environment from another project—Template Project pointing to a second Jenkins job. Mine is called SonarQube_Scanner (see below).

Build

Use builders from another project—Template Project pointing to the same Jenkins job SonarQube_Scanner.

Post-build Actions

Archive the artifacts—Files to archive set to log.zip.

A non-user-facing Jenkins job (SonarQube_Scanner) with the following settings and options.

General—Disable this project checked.

General—Restrict where this project can be run checked and set to your SonarQube server.

Source Code Management set to None.

Build Environment—Inject environment variables to the build process checked.

Properties Content contains

`LANG=en_US.UTF-8`

Build

Execute Windows batch command contains

set FILENAME=%WORKSPACE%\client\Assets\Editor\SQMenuItems.cs
REM Yes, this syntax works and is sooo much more readable
 > %FILENAME% ECHO using UnityEditor;
>> %FILENAME% ECHO public static class SQMenuItems {
>> %FILENAME% ECHO   static void AssetsOpenCSharpProject() {
>> %FILENAME% ECHO #if UNITY_5
>> %FILENAME% ECHO     EditorApplication.ExecuteMenuItem("Assets/Open C# Project");
>> %FILENAME% ECHO #else
>> %FILENAME% ECHO     EditorApplication.ExecuteMenuItem("Assets/Sync MonoDevelop Project");
>> %FILENAME% ECHO #endif
>> %FILENAME% ECHO     EditorApplication.Exit(0);
>> %FILENAME% ECHO   }
>> %FILENAME% ECHO }
"C:\Program Files\Unity_5.5.2\Editor\Unity.exe" -quit -batchmode -nographics -logFile "%WORKSPACE%\log.txt" -buildTarget android -projectPath %WORKSPACE%\client -executeMethod SQMenuItems.AssetsOpenCSharpProject
"C:\Program Files\7-zip\7z.exe" -tzip a log.zip log.txt

SQMenuItems.cs is what triggers Unity to create the .sln and .*proj files that MSBuild needs. The .sln and .*proj files are typically in the .gitignore file and therefore not in the repository.

SonarQube Scanner for MSBuild - Begin Analysis

SonarQube Installation set to the Jenkins build node name you used for your SonarQube server.

Project key set to ${PROJECTKEY}.

Project name set to ${PROJECTNAME}.

Project version set to ${PROJECTVERSION}.

Additional arguments

/d:sonar.exclusions=**\\SQMenuItems.cs

Execute Windows batch command

"C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe" /maxcpucount /nr:false /nologo /target:rebuild /verbosity:quiet client\client.sln

You may need to change client\client.sln above to match your environment. I haven't yet tried replacing that with an environment variable defined in the user-facing Jenkins job.

SonarQube Scanner for MSBuild - End Analysis

DONE

GOTCHAS

If the job fails because Unity fails because it can't find the projectPath, it may have forgotten its license key. Remote desktop to your SonarQube server and launch the Unity GUI. If it pops up asking for your license key, re-enter the key, then quit. Subsequent jobs should succeed.

Things that make it very difficult to pass information to SonarQube in a dynamic way.

Windows environment variables defined in 2.5.1 “Execute Windows batch command” are not preserved through to 2.5.2 “SonarQube Scanner for MSBuild - Begin Analysis”.

The SonarQube.Analysis.xml file specifically prohibits assigning the properties sonar.projectName, sonar.projectKey, and sonar.projectVersion.

I've probably overlooked something; please don't hesitate to inquire.


问:
Overriding hashCode() - is this good enough?
For a class whose fields are solely primitive, ex.:

```<code>class Foo
{
    int a;
    String b;
    boolean c;
    long d;

    boolean equals(Object o)
    {
        if (this == o) return true;
        if (!(o instanceof Foo)) return false;
        Foo other = (Foo) o;
        return a == other.a && b.equals(other.b) && c == other.c && d = other.d;
    }
}
</code>```

Is this a reasonably "good enough" way to write hashCode()?

```<code>boolean hashCode()
{
    return (b + a + c + d).hashCode();
}
</code>```

That is, I construct a String out of the same fields that equals() uses, and then just use String#hashCode().

Edit:  I've updated my question to include a long field. How should a long be handled in hashCode()? Just let it overflow int?

答: It totally depends on what your data will look like. Under most circumstances, this would be a good approach. If you'll often have b end with a number, then you'll get some duplicate codes for unequal objects, as JacobM's answer shows. If you know ahead of time that b will pretty much never have a number value at the end, then this is a reasonable hashing algorithm.

Body:
For a class whose fields are solely primitive, ex.:

class Foo
{
    int a;
    String b;
    boolean c;
    long d;

    boolean equals(Object o)
    {
        if (this == o) return true;
        if (!(o instanceof Foo)) return false;
        Foo other = (Foo) o;
        return a == other.a && b.equals(other.b) && c == other.c && d = other.d;
    }
}

Is this a reasonably "good enough" way to write hashCode()?

boolean hashCode()
{
    return (b + a + c + d).hashCode();
}

That is, I construct a String out of the same fields that equals() uses, and then just use String#hashCode().

Edit:  I've updated my question to include a long field. How should a long be handled in hashCode()? Just let it overflow int?


问:
C - Wrong values in printed array
I've looked for but nothing helped me. I've deleted even spaces from my code but when I print my array, values are wrong.

```<code>#include<stdio.h>

main() {
    int n, i = 0, j;
    printf("Set number of elements in array: ");
    scanf("%d", &n);

    int tab[n];
    printf("Number of elements: %d\n", n);
    printf("Set values for each element: \n");

    while (i < n) {
        printf("Tab[%d] = ", i + 1);
        scanf("%d", &tab[n]);
        i++;
    }

    printf("There is your array: \n");
    for (j = 0; j < n; j++) {
        printf("%d\t\t", tab[0]);
    }
    return 0;
}
</code>```

What is happening?

答:
This will print all array values as a string with comma separated values in C#</p>

```<code>string.Join(", ", myArray.Select(v => v.ToString())
</code>```

Title: C - Wrong values in printed array

Body:
I've looked for but nothing helped me. I've deleted even spaces from my code but when I print my array, values are wrong.

#include<stdio.h>

main() {
    int n, i = 0, j;
    printf("Set number of elements in array: ");
    scanf("%d", &n);

    int tab[n];
    printf("Number of elements: %d\n", n);
    printf("Set values for each element: \n");

    while (i < n) {
        printf("Tab[%d] = ", i + 1);
        scanf("%d", &tab[n]);
        i++;
    }

    printf("There is your array: \n");
    for (j = 0; j < n; j++) {
        printf("%d\t\t", tab[0]);
    }
    return 0;
}

What is happening?

Body:
This will print all array values as a string with comma separated values in C#

string.Join(", ", myArray.Select(v => v.ToString())


问:
Oauth2 - JDBC Implementation How to change database table names
I have implemented OAuth2 with Spring security following this link. Now there are several tables with following names - oauth_client_details , oauth_code , oauth_client_token and etc. Now what i need to do is to change these names. with a prefix (like "security_"). How can i do that ?</p>

答:
1) JdbcClientDetailsService implements ClientDetailsService which uses the oauth_client_details table in hard-coded JDBC PreparedStatements.

2) JdbcClientTokenServices implements ClientTokenServices which uses the oauth_client_token table in hard-coded JDBC PreparedStatements.

3) JdbcAuthorizationCodeServices implements AuthorizationCodeServices which uses the oauth_code table in hard-coded JDBC PreparedStatements.

In your Oauth2Config.java or SecurityConfig (whatever you call it), when you wire up your Services, you could use a custom Service that you hand-jammed that implements the same interface as the Service you are trying to override.

So... If you wanted to store your Client tokens in a table called security_oauth_tokens, then you could just implement your own ClientTokenServices and wire it into your configuration instead.

Here is a rough example of how you could start to create a CustomClientTokenServices, that uses spring Repositories:

```<code>@Component
public class RepositoryClientTokenServices implements ClientTokenServices
{

    @Autowired
    TokenRepository repository;

    private ClientKeyGenerator keyGenerator = new DefaultClientKeyGenerator();

    @Override
    public OAuth2AccessToken getAccessToken(final OAuth2ProtectedResourceDetails resource, final Authentication authentication)
    {

        String accessToken = keyGenerator.extractKey(resource, authentication);
        TokenEntity tokenEntity = this.repository.findByAuthenticationId(accessToken);

        if (tokenEntity == null && LOG.isInfoEnabled())
        {
            LOG.debug("Failed to find access token for authentication " + authentication);
            return null;
        }

        return new DefaultOAuth2AccessToken(tokenEntity.getValue());
    }

    @Override
    public void saveAccessToken(final OAuth2ProtectedResourceDetails resource, final Authentication authentication, final OAuth2AccessToken accessToken)
    {
      //use the repository to save the token
    }

    @Override
    public void removeAccessToken(final OAuth2ProtectedResourceDetails resource, final Authentication authentication)
    {
      //use repository to remove the token
    }
}
</code>```

But! Probably the easiest way would be to create a CustomJDBCClientTokenServices, that just does a find/replace on the table name like this:

```<code>@Component
public class CustomJdbcClientTokenServices implements ClientTokenServices {

    private static final Log LOG = LogFactory.getLog(JdbcClientTokenServices.class);

    private static final String DEFAULT_ACCESS_TOKEN_INSERT_STATEMENT = "insert into security_oauth_client_token (token_id, token, authentication_id, user_name, client_id) values (?, ?, ?, ?, ?)";

    private static final String DEFAULT_ACCESS_TOKEN_FROM_AUTHENTICATION_SELECT_STATEMENT = "select token_id, token from security_oauth_client_token where authentication_id = ?";

    private static final String DEFAULT_ACCESS_TOKEN_DELETE_STATEMENT = "delete from security_oauth_client_token where authentication_id = ?";

    private String insertAccessTokenSql = DEFAULT_ACCESS_TOKEN_INSERT_STATEMENT;

    private String selectAccessTokenSql = DEFAULT_ACCESS_TOKEN_FROM_AUTHENTICATION_SELECT_STATEMENT;

    private String deleteAccessTokenSql = DEFAULT_ACCESS_TOKEN_DELETE_STATEMENT;

    private ClientKeyGenerator keyGenerator = new DefaultClientKeyGenerator();

    private final JdbcTemplate jdbcTemplate;

    public CustomJdbcClientTokenServices(DataSource dataSource) {
        Assert.notNull(dataSource, "DataSource required");
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    public void setClientKeyGenerator(ClientKeyGenerator keyGenerator) {
        this.keyGenerator = keyGenerator;
    }

    public OAuth2AccessToken getAccessToken(OAuth2ProtectedResourceDetails resource, Authentication authentication) {

        OAuth2AccessToken accessToken = null;

        try {
            accessToken = jdbcTemplate.queryForObject(selectAccessTokenSql, new RowMapper<OAuth2AccessToken>() {
                public OAuth2AccessToken mapRow(ResultSet rs, int rowNum) throws SQLException {
                    return SerializationUtils.deserialize(rs.getBytes(2));
                }
            }, keyGenerator.extractKey(resource, authentication));
        }
        catch (EmptyResultDataAccessException e) {
            if (LOG.isInfoEnabled()) {
                LOG.debug("Failed to find access token for authentication " + authentication);
            }
        }

        return accessToken;
    }

    public void saveAccessToken(OAuth2ProtectedResourceDetails resource, Authentication authentication,
                                OAuth2AccessToken accessToken) {
        removeAccessToken(resource, authentication);
        String name = authentication==null ? null : authentication.getName();
        jdbcTemplate.update(
                insertAccessTokenSql,
                new Object[] { accessToken.getValue(), new SqlLobValue(SerializationUtils.serialize(accessToken)),
                        keyGenerator.extractKey(resource, authentication), name,
                        resource.getClientId() }, new int[] { Types.VARCHAR, Types.BLOB, Types.VARCHAR, Types.VARCHAR,
                        Types.VARCHAR });
    }

    public void removeAccessToken(OAuth2ProtectedResourceDetails resource, Authentication authentication) {
        jdbcTemplate.update(deleteAccessTokenSql, keyGenerator.extractKey(resource, authentication));
    }

    public void setInsertAccessTokenSql(String insertAccessTokenSql) {
        this.insertAccessTokenSql = insertAccessTokenSql;
    }

    public void setSelectAccessTokenSql(String selectAccessTokenSql) {
        this.selectAccessTokenSql = selectAccessTokenSql;
    }

    public void setDeleteAccessTokenSql(String deleteAccessTokenSql) {
        this.deleteAccessTokenSql = deleteAccessTokenSql;
    }

}
</code>```

Body:
1) JdbcClientDetailsService implements ClientDetailsService which uses the oauth_client_details table in hard-coded JDBC PreparedStatements.

2) JdbcClientTokenServices implements ClientTokenServices which uses the oauth_client_token table in hard-coded JDBC PreparedStatements.

3) JdbcAuthorizationCodeServices implements AuthorizationCodeServices which uses the oauth_code table in hard-coded JDBC PreparedStatements.

In your Oauth2Config.java or SecurityConfig (whatever you call it), when you wire up your Services, you could use a custom Service that you hand-jammed that implements the same interface as the Service you are trying to override.

So... If you wanted to store your Client tokens in a table called security_oauth_tokens, then you could just implement your own ClientTokenServices and wire it into your configuration instead.

Here is a rough example of how you could start to create a CustomClientTokenServices, that uses spring Repositories:

@Component
public class RepositoryClientTokenServices implements ClientTokenServices
{

    @Autowired
    TokenRepository repository;

    private ClientKeyGenerator keyGenerator = new DefaultClientKeyGenerator();

    @Override
    public OAuth2AccessToken getAccessToken(final OAuth2ProtectedResourceDetails resource, final Authentication authentication)
    {

        String accessToken = keyGenerator.extractKey(resource, authentication);
        TokenEntity tokenEntity = this.repository.findByAuthenticationId(accessToken);

        if (tokenEntity == null && LOG.isInfoEnabled())
        {
            LOG.debug("Failed to find access token for authentication " + authentication);
            return null;
        }

        return new DefaultOAuth2AccessToken(tokenEntity.getValue());
    }

    @Override
    public void saveAccessToken(final OAuth2ProtectedResourceDetails resource, final Authentication authentication, final OAuth2AccessToken accessToken)
    {
      //use the repository to save the token
    }

    @Override
    public void removeAccessToken(final OAuth2ProtectedResourceDetails resource, final Authentication authentication)
    {
      //use repository to remove the token
    }
}

But! Probably the easiest way would be to create a CustomJDBCClientTokenServices, that just does a find/replace on the table name like this:

@Component
public class CustomJdbcClientTokenServices implements ClientTokenServices {

    private static final Log LOG = LogFactory.getLog(JdbcClientTokenServices.class);

    private static final String DEFAULT_ACCESS_TOKEN_INSERT_STATEMENT = "insert into security_oauth_client_token (token_id, token, authentication_id, user_name, client_id) values (?, ?, ?, ?, ?)";

    private static final String DEFAULT_ACCESS_TOKEN_FROM_AUTHENTICATION_SELECT_STATEMENT = "select token_id, token from security_oauth_client_token where authentication_id = ?";

    private static final String DEFAULT_ACCESS_TOKEN_DELETE_STATEMENT = "delete from security_oauth_client_token where authentication_id = ?";

    private String insertAccessTokenSql = DEFAULT_ACCESS_TOKEN_INSERT_STATEMENT;

    private String selectAccessTokenSql = DEFAULT_ACCESS_TOKEN_FROM_AUTHENTICATION_SELECT_STATEMENT;

    private String deleteAccessTokenSql = DEFAULT_ACCESS_TOKEN_DELETE_STATEMENT;

    private ClientKeyGenerator keyGenerator = new DefaultClientKeyGenerator();

    private final JdbcTemplate jdbcTemplate;

    public CustomJdbcClientTokenServices(DataSource dataSource) {
        Assert.notNull(dataSource, "DataSource required");
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    public void setClientKeyGenerator(ClientKeyGenerator keyGenerator) {
        this.keyGenerator = keyGenerator;
    }

    public OAuth2AccessToken getAccessToken(OAuth2ProtectedResourceDetails resource, Authentication authentication) {

        OAuth2AccessToken accessToken = null;

        try {
            accessToken = jdbcTemplate.queryForObject(selectAccessTokenSql, new RowMapper<OAuth2AccessToken>() {
                public OAuth2AccessToken mapRow(ResultSet rs, int rowNum) throws SQLException {
                    return SerializationUtils.deserialize(rs.getBytes(2));
                }
            }, keyGenerator.extractKey(resource, authentication));
        }
        catch (EmptyResultDataAccessException e) {
            if (LOG.isInfoEnabled()) {
                LOG.debug("Failed to find access token for authentication " + authentication);
            }
        }

        return accessToken;
    }

    public void saveAccessToken(OAuth2ProtectedResourceDetails resource, Authentication authentication,
                                OAuth2AccessToken accessToken) {
        removeAccessToken(resource, authentication);
        String name = authentication==null ? null : authentication.getName();
        jdbcTemplate.update(
                insertAccessTokenSql,
                new Object[] { accessToken.getValue(), new SqlLobValue(SerializationUtils.serialize(accessToken)),
                        keyGenerator.extractKey(resource, authentication), name,
                        resource.getClientId() }, new int[] { Types.VARCHAR, Types.BLOB, Types.VARCHAR, Types.VARCHAR,
                        Types.VARCHAR });
    }

    public void removeAccessToken(OAuth2ProtectedResourceDetails resource, Authentication authentication) {
        jdbcTemplate.update(deleteAccessTokenSql, keyGenerator.extractKey(resource, authentication));
    }

    public void setInsertAccessTokenSql(String insertAccessTokenSql) {
        this.insertAccessTokenSql = insertAccessTokenSql;
    }

    public void setSelectAccessTokenSql(String selectAccessTokenSql) {
        this.selectAccessTokenSql = selectAccessTokenSql;
    }

    public void setDeleteAccessTokenSql(String deleteAccessTokenSql) {
        this.deleteAccessTokenSql = deleteAccessTokenSql;
    }

}


问:
Find a value based on one criteria and two match ranges
I have two data sources:

Source 1 contains product id and price date, need to find the price that corresponds with the date from Source 2 based on product id and between two date ranges because there is no exact date match.  Here are the tables:

Source 1

```<code>Product ID  Price Date  Need price
2512330 05/07/2016  ???
2512330 06/07/2016  ???
2512330 06/13/2016  ???
2512330 07/20/2016  ???
2512330 08/27/2016  ???
2512330 09/22/2016  ???
</code>```

Source 2:

```<code>Product ID  Current Update  Price   First Update    Price   Second Update   Price   Third Update    Price   Fourth Update   Price   Fifth Update    Price
2143480 5/2/2017    405.60  8/18/2016   375.60  12/23/2015  344.88  5/29/2015   319.08  10/20/2014  292.99  10/1/1996   0.00
2512330 5/2/2017    18.36   12/6/2016   16.70   6/3/2016    15.62   12/1/2015   14.22   5/14/2015   12.94   12/4/2014   11.77
3089421 1/1/2017    7.77    4/1/2016    7.20    8/24/2015   6.67    12/15/2014  6.30    3/17/2014   5.83    8/30/2013   5.31
</code>```

Thank in advance for your help.

octord

答:
Use this formula:

```<code>=INDEX(A:M,MATCH(P2,A:A,0),AGGREGATE(15,6,COLUMN(INDEX(A:M,MATCH(P2,A:A,0),0))/((INDEX(A:M,MATCH(P2,A:A,0),0)<=Q2)*(ISEVEN(COLUMN(INDEX(A:M,MATCH(P2,A:A,0),0))))),1)+1)
</code>```

You may need to change the ISEVEN to ISODD depending on the column in which the dates are found.

Body:
I have two data sources:

Source 1 contains product id and price date, need to find the price that corresponds with the date from Source 2 based on product id and between two date ranges because there is no exact date match.  Here are the tables:

Source 1

Product ID  Price Date  Need price
2512330 05/07/2016  ???
2512330 06/07/2016  ???
2512330 06/13/2016  ???
2512330 07/20/2016  ???
2512330 08/27/2016  ???
2512330 09/22/2016  ???

Source 2:

Product ID  Current Update  Price   First Update    Price   Second Update   Price   Third Update    Price   Fourth Update   Price   Fifth Update    Price
2143480 5/2/2017    405.60  8/18/2016   375.60  12/23/2015  344.88  5/29/2015   319.08  10/20/2014  292.99  10/1/1996   0.00
2512330 5/2/2017    18.36   12/6/2016   16.70   6/3/2016    15.62   12/1/2015   14.22   5/14/2015   12.94   12/4/2014   11.77
3089421 1/1/2017    7.77    4/1/2016    7.20    8/24/2015   6.67    12/15/2014  6.30    3/17/2014   5.83    8/30/2013   5.31

Thank in advance for your help.

octord

Body:
Use this formula:

=INDEX(A:M,MATCH(P2,A:A,0),AGGREGATE(15,6,COLUMN(INDEX(A:M,MATCH(P2,A:A,0),0))/((INDEX(A:M,MATCH(P2,A:A,0),0)<=Q2)*(ISEVEN(COLUMN(INDEX(A:M,MATCH(P2,A:A,0),0))))),1)+1)

You may need to change the ISEVEN to ISODD depending on the column in which the dates are found.


问:
Move a button by setting CSS using Javascript

 <!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

     <link rel="stylesheet" href="./files/font-awesome.min.css">

Do you love KWEB?

   <button onclick="alertKWEB()">I do</button>
   <button class="button2" onclick="alertKWEB2()" onmouseover="moveButtonRand()">.....</button>

 ```

I want to make the second button move to a random position when I put the cursor over it. I don't understand why this does not work; please help! This is my school homework which entails using the JS DOM, so please do not suggest other ways.

答:
function alertKWEB() {
  alert("Me too");
}

function alertKWEB2() {
  alert("K★W★E★B");
}

var m = Math;
m.c = m.ceil;
m.f = m.floor;
m.r = m.random;

function moveButtonRand() {
  var bTag = document.querySelector('.button2');
  var min = 1;
  var max = 95;
  // inclusive random number btw two values
  var res = m.f(m.r() * (max - min + 1)) + min;
  bTag.style.top = res + "%";
  bTag.style.left = res + "%";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="./files/jquery-1.11.2.min.js"></script>
  <script src="./files/bootstrap.min.js"></script>
  <link rel="stylesheet" href="./files/font-awesome.min.css">
  <style>
    body {
      font-family: "Helvetica Neue", Helvetica, Arial, NanumBarunGothic, NanumGothic, "Apple SD Gothic Neo", sans-serif;
    }

    a {
      font-size: 36px;
      font-weight: 500;
      text-decoration: none;
      transition: color 0.3s;
      color: #0099cc;
      background-color: transparent;
      box-sizing: border-box;
    }

    a:hover {
      color: #4dd2ff;
      outline: none;
      border-bottom: 1px dotted;
    }

    hr {
      margin-bottom: 23px;
      border: 0;
      border-top: 1px solid #b8b8b8;
    }

    .button2 {
      position: absolute;
    }
  </style>

</head>

<body>
  <div class="main" style="text-align: center; width: 100%; height: 100%">
    <h1>Do you love KWEB?</h1>
    <hr>
    <button onclick="alertKWEB()">I do</button>
    <button class="button2" onclick="alertKWEB2()" onmouseover="moveButtonRand()">.....</button>
  </div>
</body>

</html></code>```

This script selects the button whose class is ".button2" using the aforementioned suggestion of using document.querySelector. Also, it employs some shortcuts which reduces the verbosity. But, most importantly it uses a technique suggested by the MDN to improve the randomness.

Body:
 <!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

     <link rel="stylesheet" href="./files/font-awesome.min.css">

Do you love KWEB?

   <button onclick="alertKWEB()">I do</button>
   <button class="button2" onclick="alertKWEB2()" onmouseover="moveButtonRand()">.....</button>

I want to make the second button move to a random position when I put the cursor over it. I don't understand why this does not work; please help! This is my school homework which entails using the JS DOM, so please do not suggest other ways.

Body:
function alertKWEB() {
  alert("Me too");
}

function alertKWEB2() {
  alert("K★W★E★B");
}

var m = Math;
m.c = m.ceil;
m.f = m.floor;
m.r = m.random;

function moveButtonRand() {
  var bTag = document.querySelector('.button2');
  var min = 1;
  var max = 95;
  // inclusive random number btw two values
  var res = m.f(m.r() * (max - min + 1)) + min;
  bTag.style.top = res + "%";
  bTag.style.left = res + "%";
}

<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="./files/jquery-1.11.2.min.js"></script>
  <script src="./files/bootstrap.min.js"></script>
  <link rel="stylesheet" href="./files/font-awesome.min.css">
  <style>
    body {
      font-family: "Helvetica Neue", Helvetica, Arial, NanumBarunGothic, NanumGothic, "Apple SD Gothic Neo", sans-serif;
    }

    a {
      font-size: 36px;
      font-weight: 500;
      text-decoration: none;
      transition: color 0.3s;
      color: #0099cc;
      background-color: transparent;
      box-sizing: border-box;
    }

    a:hover {
      color: #4dd2ff;
      outline: none;
      border-bottom: 1px dotted;
    }

    hr {
      margin-bottom: 23px;
      border: 0;
      border-top: 1px solid #b8b8b8;
    }

    .button2 {
      position: absolute;
    }
  </style>

</head>

<body>
  <div class="main" style="text-align: center; width: 100%; height: 100%">
    <h1><a href="https://kweb.korea.ac.kr/">Do you love KWEB?</a></h1>
    <hr>
    <button onclick="alertKWEB()">I do</button>
    <button class="button2" onclick="alertKWEB2()" onmouseover="moveButtonRand()">.....</button>
  </div>
</body>

</html>

This script selects the button whose class is ".button2" using the aforementioned suggestion of using document.querySelector. Also, it employs some shortcuts which reduces the verbosity. But, most importantly it uses a technique suggested by the MDN to improve the randomness.


问:
Xcode UI Testing - Timestamped Event Matching Error
We are getting this error when recording a UI test.  At this point the recorder stops recording code.  What does it mean?

答:
Try adding your storyboard to the UI tests target membership.

Click the storyboard, then on the right click file inspector, then scroll down to target membership and click UI tests.


问:
4 images in one view using linear layout android
I wish to make 2 by 2 image using LinearLayout with you equal weight. Can someone please assist me thanks. Your help will be appreciated thanks

I am trying to get my xml for my Android app working but I have some problems. I am trying to display to equal sized 2 images side by side in a linear layout. There has to be a margin between them, on both sides right and left, and on top.

MY code can only give me 3 images but I need 4 images.
I'd appreciate any help solving this problem

This is my code:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:orientation="horiztontal"
    android:weightSum="2">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"

        />

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:weightSum="2">

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:weightSum="1">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/imageView3"
                android:layout_weight="1" />

        </LinearLayout>
    </LinearLayout>
</code>```

答:
use following layout

```<code> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="2">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:orientation="horizontal"
    android:weightSum="2">
    <ImageView
        android:layout_margin="10dp"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent" />
    <ImageView
        android:layout_margin="10dp"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent" />
</LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal"
        android:weightSum="2">
        <ImageView
            android:layout_margin="10dp"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent" />
        <ImageView
            android:layout_margin="10dp"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent" />
    </LinearLayout>
</LinearLayout>
</code>```

Note:further you can optimize this layout using Relative or ConstrainLayout.

Body:
I wish to make 2 by 2 image using LinearLayout with you equal weight. Can someone please assist me thanks. Your help will be appreciated thanks

I am trying to get my xml for my Android app working but I have some problems. I am trying to display to equal sized 2 images side by side in a linear layout. There has to be a margin between them, on both sides right and left, and on top.

MY code can only give me 3 images but I need 4 images.
I'd appreciate any help solving this problem

This is my code:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:orientation="horiztontal"
    android:weightSum="2">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"

        />

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:weightSum="2">

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:weightSum="1">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/imageView3"
                android:layout_weight="1" />

        </LinearLayout>
    </LinearLayout>

Body:
use following layout

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="2">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:orientation="horizontal"
    android:weightSum="2">
    <ImageView
        android:layout_margin="10dp"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent" />
    <ImageView
        android:layout_margin="10dp"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent" />
</LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal"
        android:weightSum="2">
        <ImageView
            android:layout_margin="10dp"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent" />
        <ImageView
            android:layout_margin="10dp"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent" />
    </LinearLayout>
</LinearLayout>

Note:further you can optimize this layout using Relative or ConstrainLayout.


问:
Why Python tries to compute some calculations in multiprocessing in advance
I am using Ubuntu 17.04 64-bit with processor-Intel® Core™ i7-7500U CPU @ 2.70GHz × 4 and 16gb of RAM.

So when I run this program, it uses a single core instead of using all the 4 cores.

```<code>import time
import multiprocessing

def boom1(*args):
    print(5**10000000000)

def boom2(*args):
    print(5**10000000000)

def boom3(*args):
    print(5**10000000000)

def boom4(*args):
    print(5**10000000000)

if __name__=="__main__":
    array = []
    p1 = multiprocessing.Process(target=boom1, args=(array,))
    p2 = multiprocessing.Process(target=boom2, args=(array,))
    p3 = multiprocessing.Process(target=boom3, args=(array,))
    p4 = multiprocessing.Process(target=boom4, args=(array,))

    p1.start()
    p2.start()
    p3.start()
    p4.start()

    p1.join()
    p2.join()
    p3.join()
    p4.join()

    print('Done')
</code>```

Now if I print some low power of 10 in each function:

```<code>print(5 ** 10000000)
</code>```

Now for small duration of time, a single core is processing 100% and then all 4 cores are performing 100%.
Why is this so? Shouldn't it start with all cores performing 100%.

What I had come to know was that python performs some operation before itself and hence was doing that from a single core. If it is so then what is the point of python being an interpreted language or am I missing something?does

答:
Most languages have a constant-folding optimization: when an operation between constants appears, the compiler will perform the operation and replace the expression with the single-constant result.

Python does this, as well.  I expect that your multi-node operation was simply the sequence of start-print-join on each node.

If you want to get longer runs on the four nodes, try an expression that can't be evaluated at parse-time.  For instance, pass the base in the argument list and use that instead of 5, or perhaps have each process pick a random number in the range 1-10 and add that to the exponent.  This should force run-time evaluation.

Body:
I am using Ubuntu 17.04 64-bit with processor-Intel® Core™ i7-7500U CPU @ 2.70GHz × 4 and 16gb of RAM.

So when I run this program, it uses a single core instead of using all the 4 cores.

import time
import multiprocessing

def boom1(*args):
    print(5**10000000000)

def boom2(*args):
    print(5**10000000000)

def boom3(*args):
    print(5**10000000000)

def boom4(*args):
    print(5**10000000000)

if __name__=="__main__":
    array = []
    p1 = multiprocessing.Process(target=boom1, args=(array,))
    p2 = multiprocessing.Process(target=boom2, args=(array,))
    p3 = multiprocessing.Process(target=boom3, args=(array,))
    p4 = multiprocessing.Process(target=boom4, args=(array,))

    p1.start()
    p2.start()
    p3.start()
    p4.start()

    p1.join()
    p2.join()
    p3.join()
    p4.join()

    print('Done')

Now if I print some low power of 10 in each function:

print(5 ** 10000000)

Now for small duration of time, a single core is processing 100% and then all 4 cores are performing 100%.
Why is this so? Shouldn't it start with all cores performing 100%.

What I had come to know was that python performs some operation before itself and hence was doing that from a single core. If it is so then what is the point of python being an interpreted language or am I missing something?does


问:
Perl UTF-8 problems with Locale::Maketext
The short story:

I've encountered a strange problem with Locale::Maketext. Something turns german umlauts into ISO-8859-1 encoding when using
the "use utf8" pragma in my lexicon.

The long story:

In my web application everything is kept in UTF-8:

the database

the source code files

the html doctype

and everything else as far a I can tell

I use Locale::Maketext for L10N and all mit Lexicons are defined in Perl Modules which are kept in UTF-8 and
"use utf8". All languages tested so far (e.g. pt, pl, fr, en, zh, ko, et. al.) work fine except the locale de.
As long a "use utf8" is enabled within this language's Lexicon something turns the german umlauts (probably everything thats
no 7-bit ASCII) into ISO-8859-1. I have the script that verifies that everything in my source tree is encoded in UTF-8 (inclduing 7-bit ASCII of course).

Let me repeat: If I remove the "use utf8" pragma for the Module MyApp::L10N::de the resulting encoding after using maketext in my app is UTF-8 which is fine. As long as the module uses utf8 the encoding is turned into ISO-8859-1 while all other languages work. I'm desperate to find out why, since this doesn't quite match what I've read about the utf8 pragma.

My Question is simple: Why does this happen? How can I fix this behaviour, i.e. how do I make my app work with use utf8 in all source files?

答:
The failure you are experiencing is documented in Locale::Maketext::Gettext:

An essential benefit of this Locale::Maketext::Gettext over the original Locale::Maketext(3) is that: GNU gettext is multibyte safe, but Perl source is not. […] Sorry to say this, but it is weird for a localization framework to be not multibyte-safe.

You are advised to migrate off Maketext to a Gettext-based solution, see rassie's remarkable rocalisation rant: http://rassie.org/archives/247


问:
Javascript array object Output
Can anybody help me I am new to javascript. I am not able to understand the below line of code. I spend hours to debug this code but I am not able to rectify.

```<code>var data = [
    {"name":"123123123123"},
    {"name":"123123123124"},
    {"name":"123123123125"},
    {"name":"123123123126"}
];
var x1 = {}
var basicS = {
    "question":[]
}
data.forEach(function(val,i){
   x1[val.name]=basicS;
});

console.log(x1);
data.forEach(function(val,i){
 x1[val.name].question.push('insert');
});
console.log(x1);
</code>```

Output:

```<code>{
 123123123123:{
    question:[
      0:"insert"
      1:"insert"
      2:"insert"
      3:"insert"
    ]
},
123123123124:{
    question:[
      0:"insert"
      1:"insert"
      2:"insert"
      3:"insert"
    ]
},
123123123125:{
    question:[
      0:"insert"
      1:"insert"
      2:"insert"
      3:"insert"
    ]
},
123123123126:{
    question:[
      0:"insert"
      1:"insert"
      2:"insert"
      3:"insert"
    ]
}
}
</code>```

Expected Output should be:

```<code>{
  123123123123:{
    question:[
      0:"insert"
    ]
},
123123123124:{
    question:[
      0:"insert"
    ]
},
123123123125:{
    question:[
      0:"insert"
              ]
},
123123123126:{
    question:[
      0:"insert"
    ]
}
}
</code>```

Not able to understand from where four values are inserted inside the each question array while i am inserting only  one in each question
array object.

Is there any alternative to solve this type of prblem.

Please help me out. I am totally confused. Thanks in advance.

答:
Keep it simple.

Use a new object as your container to populate.
Switch from "forEach" to "for" loop to avoid confusion.
Create a new instance of the array on every iteration for reference.
Assign index at 0 to insert.Take object at iteration and set it the name property value.
Then assign to an Object with the question property set to your array at key '0'

var data = [{
    "name": "123123123123"
  },
  {
    "name": "123123123124"
  },
  {
    "name": "123123123125"
  },
  {
    "name": "123123123126"
  }
];

var obj = {};

for (var i = 0; i < data.length; i++) {

  var insert = [];

  insert['0'] = 'insert';

  obj[data[i].name] = {
    question: insert
  }

};

console.log(obj);```

Title: Javascript array object Output

Body:
Can anybody help me I am new to javascript. I am not able to understand the below line of code. I spend hours to debug this code but I am not able to rectify.

var data = [
    {"name":"123123123123"},
    {"name":"123123123124"},
    {"name":"123123123125"},
    {"name":"123123123126"}
];
var x1 = {}
var basicS = {
    "question":[]
}
data.forEach(function(val,i){
   x1[val.name]=basicS;
});

console.log(x1);
data.forEach(function(val,i){
 x1[val.name].question.push('insert');
});
console.log(x1);

Output:

{
 123123123123:{
    question:[
      0:"insert"
      1:"insert"
      2:"insert"
      3:"insert"
    ]
},
123123123124:{
    question:[
      0:"insert"
      1:"insert"
      2:"insert"
      3:"insert"
    ]
},
123123123125:{
    question:[
      0:"insert"
      1:"insert"
      2:"insert"
      3:"insert"
    ]
},
123123123126:{
    question:[
      0:"insert"
      1:"insert"
      2:"insert"
      3:"insert"
    ]
}
}

Expected Output should be:

{
  123123123123:{
    question:[
      0:"insert"
    ]
},
123123123124:{
    question:[
      0:"insert"
    ]
},
123123123125:{
    question:[
      0:"insert"
              ]
},
123123123126:{
    question:[
      0:"insert"
    ]
}
}

Not able to understand from where four values are inserted inside the each question array while i am inserting only  one in each question
array object.

Is there any alternative to solve this type of prblem.

Please help me out. I am totally confused. Thanks in advance.


问:
How to allow images from facebook cdn in Ionic app?
I suddenly can't load profile images from Facebook (https://scontent.xx.fbcdn.net) in my Ionic 1 app (Firebase auth with Facebook provider). This has worked before, but now I just get a blank image (probably some sort of 4xx error code?). Both iOS and Android.

I have the cordova-plugin-whitelist installed, and my config.xml has <access origin="*"/>.

I have tried to add the content-security-policy meta-tag without any luck:

```<code><meta http-equiv="Content-Security-Policy" content="img-src *  blob: android-webview-video-poster: cdvphotolibrary:  'self' data: ws: wss://*; default-src * blob: 'self' gap: wss: ws: data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src * http: https: ws: wss://*;">
</code>```

Any ideas? I know that this has previously worked, so there might have been some changes in Cordova or iOS/Android causing this?

Thank you!

UPDATE:

I tried to use other external images, for instance a random one from a newspaper, and i worked. Can this be a Facebook-auth error, of some sort?

```<code>ionic info
--------------------------------
--------------------------------

Your system information:

Cordova CLI: 6.3.1
Gulp version:  CLI version 1.2.1
Gulp local:   Local version 3.9.1
Ionic Framework Version: 1.3.2
Ionic CLI Version: 2.1.1
Ionic App Lib Version: 2.1.1
ios-deploy version: 1.8.6
ios-sim version: 5.0.6
OS: Mac OS X Sierra
Node Version: v4.4.0
Xcode version: Xcode 8.3.1 Build version 8E1000a
</code>```

答:
I managed to get around the problem by fetching the profile image manually. The image provided by the Firebase SDK still doesn't work.</p>

```<code>var user = firebase.auth().currentUser;

if (user != null) {
  user.providerData.forEach(function (profile) {
    if (profile.providerId === "facebook.com") {
      user.updateProfile({
        photoURL : "https://graph.facebook.com/" + profile.uid + "/picture?height=200"
      });
    }
  });
}
</code>```

Body:
I suddenly can't load profile images from Facebook (https://scontent.xx.fbcdn.net) in my Ionic 1 app (Firebase auth with Facebook provider). This has worked before, but now I just get a blank image (probably some sort of 4xx error code?). Both iOS and Android.

I have the cordova-plugin-whitelist installed, and my config.xml has <access origin="*"/>.

I have tried to add the content-security-policy meta-tag without any luck:

<meta http-equiv="Content-Security-Policy" content="img-src *  blob: android-webview-video-poster: cdvphotolibrary:  'self' data: ws: wss://*; default-src * blob: 'self' gap: wss: ws: data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src * http: https: ws: wss://*;">

Any ideas? I know that this has previously worked, so there might have been some changes in Cordova or iOS/Android causing this?

Thank you!

UPDATE:

I tried to use other external images, for instance a random one from a newspaper, and i worked. Can this be a Facebook-auth error, of some sort?

ionic info
--------------------------------
--------------------------------

Your system information:

Cordova CLI: 6.3.1
Gulp version:  CLI version 1.2.1
Gulp local:   Local version 3.9.1
Ionic Framework Version: 1.3.2
Ionic CLI Version: 2.1.1
Ionic App Lib Version: 2.1.1
ios-deploy version: 1.8.6
ios-sim version: 5.0.6
OS: Mac OS X Sierra
Node Version: v4.4.0
Xcode version: Xcode 8.3.1 Build version 8E1000a

Body:
I managed to get around the problem by fetching the profile image manually. The image provided by the Firebase SDK still doesn't work.

var user = firebase.auth().currentUser;

if (user != null) {
  user.providerData.forEach(function (profile) {
    if (profile.providerId === "facebook.com") {
      user.updateProfile({
        photoURL : "https://graph.facebook.com/" + profile.uid + "/picture?height=200"
      });
    }
  });
}


问:
JavaFX children vs items
Why in JavaFX some controls and layout has "children" property, when other has "items" property for essentailly same purpose? Is there any philosophy behind or may be some technical difference?</p>

答:
The getChildren() method is defined in Parent, and consequently inherited by all subclasses of Parent, including Pane, and Control. The implementation of this method in Parent returns an unmodifiable list of child nodes (so it can be used for navigation through the scene graph, but cannot be used to manipulate what is contained in the parent).

The Pane class, and its subclasses, are designed to allow you to lay out other nodes in the scene graph. So Pane overrides getChildren() to return a modifiable list of these nodes: essentially the functionality of a Pane is to allow you to add nodes to it and remove them later if you need. The Pane subclasses position these nodes in various ways.

The Control class is a subclass of Parent, as controls contain other nodes. (E.g. a ComboBox contains a label or text field (if it's editable), and a button for displaying the drop down list.) Control inherits its getChildren() method from Parent, so it returns an unmodifiable list of the child nodes, but doesn't allow you to change that list (because if you removed nodes from a control, it would no longer behave in the way that control was designed to behave).

Some controls are designed to display other content. Trivially, a Label or Button can have a graphic, which is any node. The API for these classes allows you to change that node (via setGraphic()).

More complex controls allow you to add and remove a collection of nodes, as part of their intended functionality. So for example a SplitPane allows you to add as many nodes as you like, and remove them if you need. However, these are not the only nodes contained in the SplitPane. So the getChildren() method still has its implementation from the superclass: it returns an unmodifiable list of all the child nodes of the split pane: that includes the items you add, and the dividers (and potentially other things too). On the other hand, the getItems() method returns the list of nodes that you are allowed to change: so you can remove an item by calling splitPane.getItems().remove(...) (and the split pane will remove the corresponding divider from its child list as well).

Other complex controls have getItems() methods that might return specific types: e.g. Menu.getItems() returns an ObservableList<MenuItem> (so you can't put a TableView in a menu, you can only put menu items in there). Similarly TabPane.getItems() returns an ObservableList<Tab>.

So in short, the two things have completely different functionality. getChildren() returns the list of child nodes for the parent: it allows you to inspect and navigate the scene graph. Parent subclasses that specifically choose to do so may return a modifiable list, allowing you to use them as general containers.

The getItems() methods that some Control classes define are there to define specific functionality of that particular control. They still have getChildren() methods, which will return a different list.

Title: JavaFX children vs items


问:
How to change the page urls in grav CMS
URLs are automatically taken from folder structure. I want to change URLs to SEO-friendly URLs. Can anyone help me to do so. Thanks in advance.</p>

答:
In the Configuration of your site go to Redirects and Routes and add a route (SEO-friendly URL) to the desired page. (Make sure you have the Admin plugin installed!)

More info in the excellent documentation, chapter Redirects and Routes

Title: How to change the page urls in grav CMS


问:
OData returns array instead of JSON - How to convert?
I've been trying to figure how to properly receive an OData response in Javascript for a couple of days. The problem is the response is formatted as an array instead of JSON, so the function JSON.parse(mydata) does not work with the data I am receiving.

My question is two-fold: What is the proper way to request OData to send a response as JSON and/or how do I format my current response to be JSON?

Here is the code that I am using:

```<code>$.ajax({
                type: "GET",
                url: requestUri,
                dataType: "script",
                accept: "application/json",
                success: function(data, request) {
                    var jsonData = JSON.parse(data);
                },
                error: function(msg) {
                    alert(msg);
                }})
</code>```

Here is an example response of logging the variable data with console.log:

{"@odata.context":"http://localhost:5001/odata/$metadata#Movies","value":[{"Title":"Pulp Fiction","Genre":"Action","RunTime":0,"Sales":0,"Key":2}]}

答:
The problem is the response is formatted as an array instead of JSON

It can't be. You can't send "an array" over HTTP. You have to encode it somehow … e.g. as JSON.

jQuery will, unless you override it with the dataType option, use the Content-Type HTTP response header to determine how the data is encoded. If it is JSON, it will parse the JSON.

The value of data is what you would get if you read the raw responseText and passed it through JSON.parse.

So just don't try to parse it manually. jQuery has done it for you.

Skip the step:

```<code>var jsonData = JSON.parse(data);
</code>```

… and just work with data.

NB: The output of JSON.parse is an object, array or other JavaScript data type. JSON data is what you get from JSON.stringify.

Body:
I've been trying to figure how to properly receive an OData response in Javascript for a couple of days. The problem is the response is formatted as an array instead of JSON, so the function JSON.parse(mydata) does not work with the data I am receiving.

My question is two-fold: What is the proper way to request OData to send a response as JSON and/or how do I format my current response to be JSON?

Here is the code that I am using:

$.ajax({
                type: "GET",
                url: requestUri,
                dataType: "script",
                accept: "application/json",
                success: function(data, request) {
                    var jsonData = JSON.parse(data);
                },
                error: function(msg) {
                    alert(msg);
                }})

Here is an example response of logging the variable data with console.log:

{"@odata.context":"http://localhost:5001/odata/$metadata#Movies","value":[{"Title":"Pulp Fiction","Genre":"Action","RunTime":0,"Sales":0,"Key":2}]}

Body:
The problem is the response is formatted as an array instead of JSON

It can't be. You can't send "an array" over HTTP. You have to encode it somehow … e.g. as JSON.

jQuery will, unless you override it with the dataType option, use the Content-Type HTTP response header to determine how the data is encoded. If it is JSON, it will parse the JSON.

The value of data is what you would get if you read the raw responseText and passed it through JSON.parse.

So just don't try to parse it manually. jQuery has done it for you.

Skip the step:

var jsonData = JSON.parse(data);

… and just work with data.

NB: The output of JSON.parse is an object, array or other JavaScript data type. JSON data is what you get from JSON.stringify.


问:
How do I create a simple callback in static classes in c#
I have a static class that has a method that again calls two other static class methods

Basically In the first static class I want to know once the operation is done in the two other static classes

```<code> public static class FirstClass{

    public static async System.Threading.Tasks.Task FirstClassMethod()
        {
            SecondClass. SecondClassMethod();
            ThirdClass. ThirdClassMethod();
        }
 }

 public static class SecondClass{

    public static async System.Threading.Tasks.Task SecondClassMethod()
        {

        }
 }

 public static class ThirdClass{

    public static async System.Threading.Tasks.Task ThirdClassMethod()
        {

        }
 }
</code>```

Any help on solving my problem would be appreciated very much

答:
With the await keyword your waiting until the Task is done.

```<code>using System.Threading.Tasks;

public static async Task FirstClassMethod()
{
    await SecondClass. SecondClassMethod();
    await ThirdClass. ThirdClassMethod();
    ...
}
</code>```

BTW:

You should consider not using await only if you're sure that you don't want to wait for the asynchronous call to complete and that the called method won't raise any exceptions.

Body:
I have a static class that has a method that again calls two other static class methods

Basically In the first static class I want to know once the operation is done in the two other static classes

 public static class FirstClass{

    public static async System.Threading.Tasks.Task FirstClassMethod()
        {
            SecondClass. SecondClassMethod();
            ThirdClass. ThirdClassMethod();
        }
 }

 public static class SecondClass{

    public static async System.Threading.Tasks.Task SecondClassMethod()
        {

        }
 }

 public static class ThirdClass{

    public static async System.Threading.Tasks.Task ThirdClassMethod()
        {

        }
 }

Any help on solving my problem would be appreciated very much

Body:
With the await keyword your waiting until the Task is done.

using System.Threading.Tasks;

public static async Task FirstClassMethod()
{
    await SecondClass. SecondClassMethod();
    await ThirdClass. ThirdClassMethod();
    ...
}

BTW:

You should consider not using await only if you're sure that you don't want to wait for the asynchronous call to complete and that the called method won't raise any exceptions.


问:
Min-height on class doesn't work
I'm creating a website, but have a little problem, that I don't know how to solve.

```<code> <div id="middle">
        <div id="clock">Here shows JS clock</div><br>
        <div class="element">
            <img  height="80px" src="SOURCE"/><h1 style="float:left" >TITLE TEXT</h1><div class="clearboth"></div>
             TITLE TEXT
        </div>
        <div class="clearboth"></div>
        <div class="element">
            <img  height="80px" src="SOURCE"/><h1 style="float:left">TITLE TEXT</h1><div class="clearboth"></div>
            <p>SOME TEXT</p>
        </div>
</code>```

And CSS

```<code>    .element{
        background-color:#fff;
        min-heigth:100px;
    }
    #middle{
        font-family:'Roboto', monospace;
        padding-left:5px;
        padding-right:5px;
        min-height:1000px;
        width:1000px;
        background-color:#ffffff;
        margin:auto;
    }
    #middle > h1,h2,h3{
        font-family: 'VT323', monospace;
        font-size:34px;
        margin-left:20px;
    }
.clearboth{
    clear:both;
}

    #middle  p{
        text-indent: 40px;
        font-size:18px;
    }
</code>```

But it min-height doesn't work - next element starts right after previous one.

答: From what I can tell, it doesn't seem like the height of the items is changing (i.e. with percentages, etc). This means that the height remains static, so there is no reason for the min-height to activate, in a sense. Try doing that and fixing the other errors that the others have pointed out. Hope this helps.</p>

Title: Min-height on class doesn't work

Body:
I'm creating a website, but have a little problem, that I don't know how to solve.

Here shows JS clock

TITLE TEXT

             TITLE TEXT

TITLE TEXT

SOME TEXT

And CSS

    .element{
        background-color:#fff;
        min-heigth:100px;
    }
    #middle{
        font-family:'Roboto', monospace;
        padding-left:5px;
        padding-right:5px;
        min-height:1000px;
        width:1000px;
        background-color:#ffffff;
        margin:auto;
    }
    #middle > h1,h2,h3{
        font-family: 'VT323', monospace;
        font-size:34px;
        margin-left:20px;
    }
.clearboth{
    clear:both;
}

    #middle  p{
        text-indent: 40px;
        font-size:18px;
    }

But it min-height doesn't work - next element starts right after previous one.


问:
Unexpected behavior for stderr redirection in bash
My understanding of stdout/stderr is that a script can log to stderr, and produce 'useful' output in stdout, which will be piped or captured by the calling process if needed.

In practice, this doesn't work the way I thought it would.

```<code>➜ cat test.sh
echo diagnostic blah blah 1>&2
echo result
</code>```

My understanding is that if I do echo $(./test.sh), I should just get 'result', since 'diagnostic blah blah' was sent to stderr. However, I get:

```<code>➜ echo $(./test.sh)
diagnostic blah blah
result
</code>```

This works correctly which shows that the redirection to stderr is actually working:

```<code>➜ echo $(./test.sh 2>/dev/null)
result
</code>```

So I guess my understanding of how output is processed in shell scripts is wrong. What am I missing?

As another example, I wouldn't expect this to work:

```<code>➜ ./test.sh | grep diagnostic
diagnostic blah blah
</code>```

答:
Your test process doesn't provide any means of distinguishing between stdout and stderr. Consider instead:</p>

```<code>echo "stderr only here:"
result=$(./test.sh)      ## stderr goes straight to TTY, stdout gets captured
echo
echo "writing the previously-captured stdout:"
printf '%s\n' "$result"  ## printf is better-defined than echo
</code>```

Body:
My understanding of stdout/stderr is that a script can log to stderr, and produce 'useful' output in stdout, which will be piped or captured by the calling process if needed.

In practice, this doesn't work the way I thought it would.

➜ cat test.sh
echo diagnostic blah blah 1>&2
echo result

My understanding is that if I do echo $(./test.sh), I should just get 'result', since 'diagnostic blah blah' was sent to stderr. However, I get:

➜ echo $(./test.sh)
diagnostic blah blah
result

This works correctly which shows that the redirection to stderr is actually working:

➜ echo $(./test.sh 2>/dev/null)
result

So I guess my understanding of how output is processed in shell scripts is wrong. What am I missing?

As another example, I wouldn't expect this to work:

➜ ./test.sh | grep diagnostic
diagnostic blah blah

Body:
Your test process doesn't provide any means of distinguishing between stdout and stderr. Consider instead:

echo "stderr only here:"
result=$(./test.sh)      ## stderr goes straight to TTY, stdout gets captured
echo
echo "writing the previously-captured stdout:"
printf '%s\n' "$result"  ## printf is better-defined than echo


问:
setting UIDateFormatter from String in Swift (1.2)
What I want to do, is to retrieve date from string where it's saved, and pass it to UIDatePicker (scrolling date picker element), so here is my piece of code:

```<code>@IBOutlet weak var myDatePicker: UIDatePicker!
@IBOutlet weak var nameTextField: UITextField!

@IBOutlet weak var saveButton: UIBarButtonItem!

    //converting date to string to show in table cell

    func dateToString (date: NSDate) -> String {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
        return dateFormatter.stringFromDate(date)
    }

    //converting string from table cell to edit date

    func stringToDate (string: NSString) -> NSDate {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
        return dateFormatter.dateFromString(dateToString (myDatePicker.date))!
    }

// here we are saving our data picked from text field and date picker UIs

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if saveButton === sender {
            let name = nameTextField.text ?? ""
            let date = dateToString (myDatePicker.date) ?? ""
            item = Item (name: name, date: date)
        }
    }

// Here we are retrieving data when press tableCell cell:

override func viewDidLoad() {
        super.viewDidLoad()
        if let item = item {
            nameTextField.text = item.name
            myDatePicker.setDate(stringToDate(item.date), animated: true)

            // also need to pass date smhw
        }
    }
</code>```

Saving from UIDatePicker to string in UITableCell - no problem, passing string (UILabel) to UITextField - no problem, but I can not pass string to UIDatePicker.
It's no warnings, build - no problem, launch, but no action happened.
Please suggest the solution on this issue. I am coding swift 1.2.

答:
```<code>func stringToDate (string: String) -> NSDate {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
        return dateFormatter.dateFromString(string)!
    }
</code>```

This works.

Body:
What I want to do, is to retrieve date from string where it's saved, and pass it to UIDatePicker (scrolling date picker element), so here is my piece of code:

@IBOutlet weak var myDatePicker: UIDatePicker!
@IBOutlet weak var nameTextField: UITextField!

@IBOutlet weak var saveButton: UIBarButtonItem!

    //converting date to string to show in table cell

    func dateToString (date: NSDate) -> String {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
        return dateFormatter.stringFromDate(date)
    }

    //converting string from table cell to edit date

    func stringToDate (string: NSString) -> NSDate {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
        return dateFormatter.dateFromString(dateToString (myDatePicker.date))!
    }

// here we are saving our data picked from text field and date picker UIs

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if saveButton === sender {
            let name = nameTextField.text ?? ""
            let date = dateToString (myDatePicker.date) ?? ""
            item = Item (name: name, date: date)
        }
    }

// Here we are retrieving data when press tableCell cell:

override func viewDidLoad() {
        super.viewDidLoad()
        if let item = item {
            nameTextField.text = item.name
            myDatePicker.setDate(stringToDate(item.date), animated: true)

            // also need to pass date smhw
        }
    }

Saving from UIDatePicker to string in UITableCell - no problem, passing string (UILabel) to UITextField - no problem, but I can not pass string to UIDatePicker.
It's no warnings, build - no problem, launch, but no action happened.
Please suggest the solution on this issue. I am coding swift 1.2.

Body:
func stringToDate (string: String) -> NSDate {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
        return dateFormatter.dateFromString(string)!
    }

This works.