问:
Transactions in Typed DataSets
Have a typed dataset with several related tables, and relations defined between those tables.  As I process a datafeed, I'm adding, modifying, and removing records, then calling update on each table.

```<code>Requests        Reapprovals        UserRole
 RequestId ----- RequestId    ----- RoleId
 Reason          RoleId  ----/      UserId
</code>```

The reason for using a typed dataset is that I have to check existing data to determine whether I'm adding, modifying, or removing records... so I need the full dump of everything I'm working with (the alternative would be 10,000 queries against the database as I process the records one by one).

I want transactional support, but I'm not seeing a way to do it with typed datasets.  For example, I'm creating a new request when I create a new reapproval.  But if the reapproval fails to update, I don't want to keep the request.

Putting the update calls under a TransactionScope would mean that if any record fails, they all fail.  Not what I want.

How would I commit or roll back related rows in a typed dataset?

答:
You can use regular transactions and also achieve transaction like feature from TableAdapterManager as like in below examples.

First Approach to use regular transaction,

```<code>   public void  savewithTransacition()
    {
        DataSet1TableAdapters.Table1TableAdapter taTbl1 = new DataSet1TableAdapters.Table1TableAdapter();
        DataSet1TableAdapters.Table2TableAdapter taTbl2 = new DataSet1TableAdapters.Table2TableAdapter();
        SqlTransaction st = null;
        SqlConnection sc = new SqlConnection("ur conneciton string");
        try
        {
            sc.Open();
            st = sc.BeginTransaction();

            taTbl1.Transaction = st;
            taTbl2.Transaction = st;
            st.Commit();
        }
        catch (System.Exception ex)
        {
            st.Rollback();
            throw ex;
        }

    }
</code>```

Second..with table adapter manager..

```<code>  public void SaveWithManager()
    {
        DataSet1TableAdapters.TableAdapterManager mgr1 = new DataSet1TableAdapters.TableAdapterManager();
        DataSet1TableAdapters.Table1TableAdapter taTbl1 = new DataSet1TableAdapters.Table1TableAdapter();
        DataSet1TableAdapters.Table2TableAdapter taTbl2 = new DataSet1TableAdapters.Table2TableAdapter();

        mgr1.Table1TableAdapter = taTbl1;
        mgr1.Table2TableAdapter = taTbl2;
        mgr1.UpdateOrder = DataSet1TableAdapters.TableAdapterManager.UpdateOrderOption.InsertUpdateDelete;
        mgr1.UpdateAll(this);
    }
</code>```

With this option you can create TAManagers for group of tables to save. like if you want one group to save and even if another get fail.

Title: Transactions in Typed DataSets

Body:
Have a typed dataset with several related tables, and relations defined between those tables.  As I process a datafeed, I'm adding, modifying, and removing records, then calling update on each table.

Requests        Reapprovals        UserRole
 RequestId ----- RequestId    ----- RoleId
 Reason          RoleId  ----/      UserId

The reason for using a typed dataset is that I have to check existing data to determine whether I'm adding, modifying, or removing records... so I need the full dump of everything I'm working with (the alternative would be 10,000 queries against the database as I process the records one by one).

I want transactional support, but I'm not seeing a way to do it with typed datasets.  For example, I'm creating a new request when I create a new reapproval.  But if the reapproval fails to update, I don't want to keep the request.

Putting the update calls under a TransactionScope would mean that if any record fails, they all fail.  Not what I want.

How would I commit or roll back related rows in a typed dataset?

Body:
You can use regular transactions and also achieve transaction like feature from TableAdapterManager as like in below examples.

First Approach to use regular transaction,

   public void  savewithTransacition()
    {
        DataSet1TableAdapters.Table1TableAdapter taTbl1 = new DataSet1TableAdapters.Table1TableAdapter();
        DataSet1TableAdapters.Table2TableAdapter taTbl2 = new DataSet1TableAdapters.Table2TableAdapter();
        SqlTransaction st = null;
        SqlConnection sc = new SqlConnection("ur conneciton string");
        try
        {
            sc.Open();
            st = sc.BeginTransaction();

            taTbl1.Transaction = st;
            taTbl2.Transaction = st;
            st.Commit();
        }
        catch (System.Exception ex)
        {
            st.Rollback();
            throw ex;
        }

    }

Second..with table adapter manager..

  public void SaveWithManager()
    {
        DataSet1TableAdapters.TableAdapterManager mgr1 = new DataSet1TableAdapters.TableAdapterManager();
        DataSet1TableAdapters.Table1TableAdapter taTbl1 = new DataSet1TableAdapters.Table1TableAdapter();
        DataSet1TableAdapters.Table2TableAdapter taTbl2 = new DataSet1TableAdapters.Table2TableAdapter();

        mgr1.Table1TableAdapter = taTbl1;
        mgr1.Table2TableAdapter = taTbl2;
        mgr1.UpdateOrder = DataSet1TableAdapters.TableAdapterManager.UpdateOrderOption.InsertUpdateDelete;
        mgr1.UpdateAll(this);
    }

With this option you can create TAManagers for group of tables to save. like if you want one group to save and even if another get fail.


来源: stackexchange

问:
i want to update state field but drop down (State field) is not updating but other fields are updating. codeigniter
[Here is code of field state that i want to update, i am new and i really appreciate you  ]</p>

```<code><div class="">
                        <label class="control-label" >State</label>
                        <select name="state_id" class="form-control col-sm-5" >
                            <option value="" >Select State...</option>
                            <?php foreach ($all_state as $v_state) : ?>
                                <option value="<?php echo $v_state->state_id ?>" <?php
                                if (!empty($employee_info->state_id)) {
                                    echo $v_state->state_id == $employee_info->state_id ? 'selected' : '';
                                }
                                ?>><?php echo $v_state->name ?></option>
                                    <?php endforeach; ?>
                        </select>
                    </div>
</code>```

答:
You can try this solution for your problem : </p>

```<code><div class="">
    <label class="control-label" >State</label>
    <select name="state_id" class="form-control col-sm-5" >
        <option value="" >Select State...</option>
        <?php foreach ($all_state as $v_state) : ?>
                <option value="<?php echo $v_state->state_id ?>"
                        <?php
                        if (!empty($employee_info->state_id) && ($v_state->state_id == $employee_info->state_id)):
                            echo  'selected';
                        endif;
                        ?>>
                    <?php echo $v_state->name ?>
                </option>
            <?php endforeach; ?>
    </select>
</div>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
[Here is code of field state that i want to update, i am new and i really appreciate you  ]

                        State
                        <select name="state_id" class="form-control col-sm-5" >
                            <option value="" >Select State...</option>
                            <?php foreach ($all_state as $v_state) : ?>
                                <option value="<?php echo $v_state->state_id ?>" <?php
                                if (!empty($employee_info->state_id)) {
                                    echo $v_state->state_id == $employee_info->state_id ? 'selected' : '';
                                }
                                ?>><?php echo $v_state->name ?></option>
                                    <?php endforeach; ?>
                        </select>

Body:
You can try this solution for your problem :

<div class="">
    <label class="control-label" >State</label>
    <select name="state_id" class="form-control col-sm-5" >
        <option value="" >Select State...</option>
        <?php foreach ($all_state as $v_state) : ?>
                <option value="<?php echo $v_state->state_id ?>"
                        <?php
                        if (!empty($employee_info->state_id) && ($v_state->state_id == $employee_info->state_id)):
                            echo  'selected';
                        endif;
                        ?>>
                    <?php echo $v_state->name ?>
                </option>
            <?php endforeach; ?>
    </select>
</div>


问:
Any utility to test expand C/C++ #define macros?
It seems I often spend way too much time trying to get a #define macro to do exactly what i want. I'll post my current dilemma below and any help is appreciated. But really the bigger question is whether there is any utility someone could recommend, to quickly display what a macro is actually doing? It seems like even the slow trial and error process would go much faster if I could see what is wrong.

Currently, I'm dynamically loading a long list of functions from a DLL I made. The way I've set things up, the function pointers have the same nanes as the exported functions, and the typedef(s) used to prototype them have the same names, but with a prepended underscore. So I want to use a define to simplify assignments of a long long list of function pointers.

For example, In the code statement below, 'hexdump' is the name of a typedef'd function point, and is also the name of the function, while _hexdump is the name of the typedef. If GetProcAddress() fails, a failure counter in incremented.

```<code>if (!(hexdump = (_hexdump)GetProcAddress(h, "hexdump"))) --iFail;
</code>```

So let's say I'd like to replace each line like the above with a macro, like this...

```<code>GETADDR_FOR(hexdump )
</code>```

Well this is the best I've come up with so far. It doesn't work (my // comment is just to prevent text formatting in the message)...

```<code>// #define GETADDR_FOR(a) if (!(a = (#_#a)GetProcAddress(h, "/""#a"/""))) --iFail;
</code>```

And again, while I'd APPRECIATE an insight into what silly mistake I've made, it would make my day to have a utility that would show me the error of my ways, by simply plugging in my macro.

答: Go to https://godbolt.org/. Enter your code in the left pane and select compiler as gcc put the argument as -E in the right pane. Your pre-processed code will appear on the right.

Body:
It seems I often spend way too much time trying to get a #define macro to do exactly what i want. I'll post my current dilemma below and any help is appreciated. But really the bigger question is whether there is any utility someone could recommend, to quickly display what a macro is actually doing? It seems like even the slow trial and error process would go much faster if I could see what is wrong.

Currently, I'm dynamically loading a long list of functions from a DLL I made. The way I've set things up, the function pointers have the same nanes as the exported functions, and the typedef(s) used to prototype them have the same names, but with a prepended underscore. So I want to use a define to simplify assignments of a long long list of function pointers.

For example, In the code statement below, 'hexdump' is the name of a typedef'd function point, and is also the name of the function, while _hexdump is the name of the typedef. If GetProcAddress() fails, a failure counter in incremented.

if (!(hexdump = (_hexdump)GetProcAddress(h, "hexdump"))) --iFail;

So let's say I'd like to replace each line like the above with a macro, like this...

GETADDR_FOR(hexdump )

Well this is the best I've come up with so far. It doesn't work (my // comment is just to prevent text formatting in the message)...

// #define GETADDR_FOR(a) if (!(a = (#_#a)GetProcAddress(h, "/""#a"/""))) --iFail;

And again, while I'd APPRECIATE an insight into what silly mistake I've made, it would make my day to have a utility that would show me the error of my ways, by simply plugging in my macro.

ContentLicense: CC BY-SA 4.0


问:
maven build fails returns execution is : '127'
I am trying to rename an artifact using exec-maven-plugin. (I don't want to use antrun plugin as I am using that for a different purpose in the same phase and goal.)

Plugin in pom.xml :

```<code><plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.1.1</version>
    <executions>
      <execution>
        <id>some-execution</id>
        <phase>package</phase>
        <goals>
          <goal>exec</goal>
        </goals>
      </execution>
    </executions>
    <configuration>
      <executable>mv "${project.build.directory}/${project.artifactId}-${project.version}-myapp.jar" "${project.build.directory}/${project.artifactId}-${project.version}.app"</executable>
    </configuration>
  </plugin>
</code>```

It fails to rename the artifact and gives below error:

```<code>[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.1.1:exec (some-execution) on project cep: Result of /bin/sh -c cd /home/XYZ/workspace/myapp/solutions/cep && "mv "/home/XYZ/workspace/myapp/solutions/cep/target/cep-0.1.0-SNAPSHOT-myapp.jar" "/home/XYZ/workspace/myapp/solutions/cep/target/cep-0.1.0-SNAPSHOT.app"" **execution is: '127'**. -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.1.1:exec (some-execution) on project cep: Result of /bin/sh -c cd /home/XYZ/workspace/myapp/solutions/cep && "mv "/home/XYZ/workspace/myapp/solutions/cep/target/cep-0.1.0-SNAPSHOT-myapp.jar" "/home/XYZ/workspace/myapp/solutions/cep/target/cep-0.1.0-SNAPSHOT.app"" execution is: '127'.
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoExecutionException: Result of /bin/sh -c cd /home/XYZ/workspace/myapp/solutions/cep && "mv "/home/XYZ/workspace/myapp/solutions/cep/target/cep-0.1.0-SNAPSHOT-myapp.jar" "/home/XYZ/workspace/myapp/solutions/cep/target/cep-0.1.0-SNAPSHOT.app"" execution is: '127'.
    at org.codehaus.mojo.exec.ExecMojo.execute(ExecMojo.java:283)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
</code>```

DEBUG Log :

```<code>[DEBUG] Configuring mojo org.codehaus.mojo:exec-maven-plugin:1.1.1:exec from plugin realm ClassRealm[plugin>org.codehaus.mojo:exec-maven-plugin:1.1.1, parent: sun.misc.Launcher$AppClassLoader@762589c3]
[DEBUG] Configuring mojo 'org.codehaus.mojo:exec-maven-plugin:1.1.1:exec' with basic configurator -->
[DEBUG]   (f) basedir = /home/XYZ/workspace/myapp/solutions/cep
[DEBUG]   (f) classpathScope = compile
[DEBUG]   (f) executable = mv "/home/XYZ/workspace/myapp/solutions/cep/target/cep-0.1.0-SNAPSHOT-myapp.jar" "/home/XYZ/workspace/myapp/solutions/cep/target/cep-0.1.0-SNAPSHOT.app"
[DEBUG]   (f) project = MavenProject: com.myco:cep:0.1.0-SNAPSHOT @ /home/XYZ/workspace/myapp/solutions/cep/pom.xml
[DEBUG]   (f) session = org.apache.maven.execution.MavenSession@2b46c61f
[DEBUG]   (f) skip = false
[DEBUG] -- end configuration --
[INFO] /bin/sh: 1: mv /home/XYZ/workspace/myapp/solutions/cep/target/cep-0.1.0-SNAPSHOT-myapp.jar /home/XYZ/workspace/myapp/solutions/cep/target/cep-0.1.0-SNAPSHOT.app: **not found**
</code>```

From these log, I am sure something is missing but I am unable to find out what. My OS is ubuntu /bin/sh is available. ls also lists the artifact at the specified location.

答:
Solved it!
I was doing it wrong. The <executable> tag is supposed to have the command only. The arguments will be defined under <arguments>.

Please see the updated plugin definition:

```<code> <plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.1.1</version>
  <executions>
    <execution>
            <id>some-execution</id>
                <phase>package</phase>
                <goals>
                    <goal>exec</goal>
                </goals>
            <configuration>
                    <executable>mv</executable>
                            <arguments>
                                    <argument>${project.build.directory}/${project.artifactId}-${project.version}-myapp.jar</argument>
                                    <argument>${project.build.directory}/${project.artifactId}-${project.version}.app</argument>
                            </arguments>
            </configuration>
     </execution>
   </executions>
  </plugin>
</code>```

Body:
I am trying to rename an artifact using exec-maven-plugin. (I don't want to use antrun plugin as I am using that for a different purpose in the same phase and goal.)

Plugin in pom.xml :

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.1.1</version>
    <executions>
      <execution>
        <id>some-execution</id>
        <phase>package</phase>
        <goals>
          <goal>exec</goal>
        </goals>
      </execution>
    </executions>
    <configuration>
      <executable>mv "${project.build.directory}/${project.artifactId}-${project.version}-myapp.jar" "${project.build.directory}/${project.artifactId}-${project.version}.app"</executable>
    </configuration>
  </plugin>

It fails to rename the artifact and gives below error:

[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.1.1:exec (some-execution) on project cep: Result of /bin/sh -c cd /home/XYZ/workspace/myapp/solutions/cep && "mv "/home/XYZ/workspace/myapp/solutions/cep/target/cep-0.1.0-SNAPSHOT-myapp.jar" "/home/XYZ/workspace/myapp/solutions/cep/target/cep-0.1.0-SNAPSHOT.app"" **execution is: '127'**. -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.1.1:exec (some-execution) on project cep: Result of /bin/sh -c cd /home/XYZ/workspace/myapp/solutions/cep && "mv "/home/XYZ/workspace/myapp/solutions/cep/target/cep-0.1.0-SNAPSHOT-myapp.jar" "/home/XYZ/workspace/myapp/solutions/cep/target/cep-0.1.0-SNAPSHOT.app"" execution is: '127'.
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoExecutionException: Result of /bin/sh -c cd /home/XYZ/workspace/myapp/solutions/cep && "mv "/home/XYZ/workspace/myapp/solutions/cep/target/cep-0.1.0-SNAPSHOT-myapp.jar" "/home/XYZ/workspace/myapp/solutions/cep/target/cep-0.1.0-SNAPSHOT.app"" execution is: '127'.
    at org.codehaus.mojo.exec.ExecMojo.execute(ExecMojo.java:283)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)

DEBUG Log :

[DEBUG] Configuring mojo org.codehaus.mojo:exec-maven-plugin:1.1.1:exec from plugin realm ClassRealm[plugin>org.codehaus.mojo:exec-maven-plugin:1.1.1, parent: sun.misc.Launcher$AppClassLoader@762589c3]
[DEBUG] Configuring mojo 'org.codehaus.mojo:exec-maven-plugin:1.1.1:exec' with basic configurator -->
[DEBUG]   (f) basedir = /home/XYZ/workspace/myapp/solutions/cep
[DEBUG]   (f) classpathScope = compile
[DEBUG]   (f) executable = mv "/home/XYZ/workspace/myapp/solutions/cep/target/cep-0.1.0-SNAPSHOT-myapp.jar" "/home/XYZ/workspace/myapp/solutions/cep/target/cep-0.1.0-SNAPSHOT.app"
[DEBUG]   (f) project = MavenProject: com.myco:cep:0.1.0-SNAPSHOT @ /home/XYZ/workspace/myapp/solutions/cep/pom.xml
[DEBUG]   (f) session = org.apache.maven.execution.MavenSession@2b46c61f
[DEBUG]   (f) skip = false
[DEBUG] -- end configuration --
[INFO] /bin/sh: 1: mv /home/XYZ/workspace/myapp/solutions/cep/target/cep-0.1.0-SNAPSHOT-myapp.jar /home/XYZ/workspace/myapp/solutions/cep/target/cep-0.1.0-SNAPSHOT.app: **not found**

From these log, I am sure something is missing but I am unable to find out what. My OS is ubuntu /bin/sh is available. ls also lists the artifact at the specified location.

Body:
Solved it!
I was doing it wrong. The <executable> tag is supposed to have the command only. The arguments will be defined under <arguments>.

Please see the updated plugin definition:

 <plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.1.1</version>
  <executions>
    <execution>
            <id>some-execution</id>
                <phase>package</phase>
                <goals>
                    <goal>exec</goal>
                </goals>
            <configuration>
                    <executable>mv</executable>
                            <arguments>
                                    <argument>${project.build.directory}/${project.artifactId}-${project.version}-myapp.jar</argument>
                                    <argument>${project.build.directory}/${project.artifactId}-${project.version}.app</argument>
                            </arguments>
            </configuration>
     </execution>
   </executions>
  </plugin>


问:
Unix find command, what are the {} and \; for?
With this set of commands, what are the {} and \; characters for?

```<code>find . -name '*.clj' -exec grep -r resources {} \;
</code>```

答:
Consider this alternative command which I find easier to understand:</p>

```<code>find . -name *.clj | xargs grep -r resources
</code>```

OwnerDisplayName: Berlin Brown

Body:
With this set of commands, what are the {} and \; characters for?

find . -name '*.clj' -exec grep -r resources {} \;

LastEditorDisplayName: Joel Coehoorn

Body:
Consider this alternative command which I find easier to understand:

find . -name *.clj | xargs grep -r resources

OwnerDisplayName: ceretullis

ContentLicense: CC BY-SA 2.5


问:
SQL UPDATE Command - How can i tell how many records have been updated?
If i have a SQL statement like:

```<code>Update people
set people_name = "rambo"
where people = "Terminator"
</code>```

How can I show how many records have been updated? Is it possible?

答:
you can use @@rowcount

Update people set people_name =
  "rambo" where people = "Terminator"

SELECT @@rowcount AS 'RowsAffected'

Edit - you can use @@rowcount if you are using SQL Server

Body:
If i have a SQL statement like:

Update people
set people_name = "rambo"
where people = "Terminator"

How can I show how many records have been updated? Is it possible?


问:
Image Processing: how to imwarp with mask on destination
I want to implement a function similar to Matlab's imwarp

https://www.mathworks.com/help/images/ref/imwarp.html?requestedDomain=www.mathworks.com

```<code>function [output] = maskedImwarp(im, tform, mask)
    ???
end
</code>```

so that it will do the same as imwarp (for projective2d is enough, no need for any extras), but will only calculate for the ROI defined by mask.

I want to reduce the runtime by doing less calculations.

How can this be done in the most efficient and elegant way?

I would just do a for loop on every '1' in the mask, and calculate where it came from in 'im', and then interpolate, but I think it would be much slower than possible if I used some matrix magic.

答:
OpenCV and Matlab do not offer a mask for image warping, I think partly because it isn't completely clear what would happen in certain cases. For example, consider an image that was something like

```<code>170 200 120
100 230 200
70  120 20
</code>```

with mask

```<code>1 1 1
1 0 1
1 1 1
</code>```

What is exactly supposed to happen once you transform? Do you interpolate over the hole? Or do you leave it as black? If you transform to a smaller size and that hole after interpolation closes up, do you force it in again? It just seems like it could easily produce unintended consequences and so it's weird to deal with, and doesn't really make sense to force someone's hand here.

Of course, you're probably looking more to have an inclusive region that wouldn't have holes; e.g. a mask like

```<code>0 0 1
0 1 1
1 1 1
</code>```

or something, but even then, it could be weird. Rotations for example happen around the origin, but if your mask ignores the first couple rows and columns, it's not exactly clear if someone would want that transformation to be in reference to the whole original image or in reference to where the mask starts.

I can easily see the use case for masks, but I don't think you'll see it implemented in most libraries because there's no real clear right way to do it, each use case would be different. Not impossible to implement with some flags or anything of course, but there's probably just not a huge need to try and deal with those possibilities.

Anyways, I see three ways of doing this.

Filter out the colored mask regions after warping.

Warping the inverse mask locations themselves and the removing everything from the warped image where those pixels were moved to.

Get the indices with meshgrid and then only apply the warp to the masked indices of meshgrid and interpolate the masked image on top of just those points. I have no idea if this is possible to implement with built-in functions though since you cannot reasonably create a 2-D masked image with a non-rectangular mask without inserting junk values. So it looks like you might have to loop through to interpolate.

Body:
I want to implement a function similar to Matlab's imwarp

https://www.mathworks.com/help/images/ref/imwarp.html?requestedDomain=www.mathworks.com

function [output] = maskedImwarp(im, tform, mask)
    ???
end

so that it will do the same as imwarp (for projective2d is enough, no need for any extras), but will only calculate for the ROI defined by mask.

I want to reduce the runtime by doing less calculations.

How can this be done in the most efficient and elegant way?

I would just do a for loop on every '1' in the mask, and calculate where it came from in 'im', and then interpolate, but I think it would be much slower than possible if I used some matrix magic.

Body:
OpenCV and Matlab do not offer a mask for image warping, I think partly because it isn't completely clear what would happen in certain cases. For example, consider an image that was something like

170 200 120
100 230 200
70  120 20

with mask

1 1 1
1 0 1
1 1 1

What is exactly supposed to happen once you transform? Do you interpolate over the hole? Or do you leave it as black? If you transform to a smaller size and that hole after interpolation closes up, do you force it in again? It just seems like it could easily produce unintended consequences and so it's weird to deal with, and doesn't really make sense to force someone's hand here.

Of course, you're probably looking more to have an inclusive region that wouldn't have holes; e.g. a mask like

0 0 1
0 1 1
1 1 1

or something, but even then, it could be weird. Rotations for example happen around the origin, but if your mask ignores the first couple rows and columns, it's not exactly clear if someone would want that transformation to be in reference to the whole original image or in reference to where the mask starts.

I can easily see the use case for masks, but I don't think you'll see it implemented in most libraries because there's no real clear right way to do it, each use case would be different. Not impossible to implement with some flags or anything of course, but there's probably just not a huge need to try and deal with those possibilities.

Anyways, I see three ways of doing this.

Filter out the colored mask regions after warping.

Warping the inverse mask locations themselves and the removing everything from the warped image where those pixels were moved to.

Get the indices with meshgrid and then only apply the warp to the masked indices of meshgrid and interpolate the masked image on top of just those points. I have no idea if this is possible to implement with built-in functions though since you cannot reasonably create a 2-D masked image with a non-rectangular mask without inserting junk values. So it looks like you might have to loop through to interpolate.


问:
iOS Localization, simulator and device always uses Base.lproj instead of users preferred locale
I am creating an app that for now I would like to offer in English and German. I checked the Base localization mark in the project configuration and added German. I left English as the development language.

Then I created a file Translation.plist which basically consists of dictionaries that I call categories, e.g. I have one dictionary for button texts, label texts etc. Each of the category dictionaries again consists of dictionaries that contain two Strings: value and comment. Translation.plist is localized via XCode. The folders Base.lproj, en.lproj and de.lproj exist and contain a copy of the plist-file as expected.

Then I created a class Translator.swift that is supposed to load the Translation.plist file as an NSDictionary depending on the user's preferred locale. The code looks like this:

```<code>func relevantDictionary(category: String) -> NSDictionary {
    let preferredLocale = Bundle.main.preferredLocalizations.first ?? "Base"
    NSLog("User's preferred locale is \(preferredLocale)")
    guard let url = Bundle.main.url(forResource: "Translation", withExtension: "plist") else {
        fatalError("Could not find Translation.plist")
    }

    NSLog("Using \(url.absoluteURL) for translation")
    guard let root = NSDictionary(contentsOf: url) else {
        fatalError("Could not find dictionary for category (locale=\(preferredLocale)")
    }

    guard let relevant = root.value(forKey: category) as? NSDictionary else {
        fatalError("Could not create dictionary from Translation.plist")
    }

    return relevant
}
</code>```

Then I created a String extension that uses the Translator as follows:

```<code>func localize(category: String) -> String {
    return Translator.instance.translate(category: category, string: self)
}
</code>```

With this I call the Translator by "yes".localize("button"). In English I would expect "Yes", in German I would expect "Ja". The log says the following:

2017-07-05 08:45:24.728 myApp[13598:35048360] User's preferred locale is  de_DE

2017-07-05 08:45:24.728 myApp[13598:35048360] Using file:///Users/me/Library/Developer/CoreSimulator/Devices/A39D3318-943D-4EFE-BB97-5C2218279132/data/Containers/Bundle/Application/4614E696-B52E-4C30-BBE8-3C76F6392413/myApp.app/Base.lproj/Translation.plist for translation

I wonder why this happens and what I have missed. I would have expected that de.lproj/Translation.plist is loaded instead of Base.lproj/Translation.plist.

Any help is highly appreciated.

答:
You can do it with single .plist file. You don't need to create different .plist files for it.

```<code>Firstly, Add English and German countries with locale in Project -> info
https://i.stack.imgur.com/M4QIY.png

Once, you added countries with locale in Project -> info then add localizable.strings file in your bundle.
https://i.stack.imgur.com/lnjgL.png

At the end, just add country's locale in your language support class.

NSArray* languages = @[@"en", @"de"];`enter code here`
    NSString *current = [languages objectAtIndex:0];
    [self setLanguage:current];
</code>```

Hope it would help you.

Body:
I am creating an app that for now I would like to offer in English and German. I checked the Base localization mark in the project configuration and added German. I left English as the development language.

Then I created a file Translation.plist which basically consists of dictionaries that I call categories, e.g. I have one dictionary for button texts, label texts etc. Each of the category dictionaries again consists of dictionaries that contain two Strings: value and comment. Translation.plist is localized via XCode. The folders Base.lproj, en.lproj and de.lproj exist and contain a copy of the plist-file as expected.

Then I created a class Translator.swift that is supposed to load the Translation.plist file as an NSDictionary depending on the user's preferred locale. The code looks like this:

func relevantDictionary(category: String) -> NSDictionary {
    let preferredLocale = Bundle.main.preferredLocalizations.first ?? "Base"
    NSLog("User's preferred locale is \(preferredLocale)")
    guard let url = Bundle.main.url(forResource: "Translation", withExtension: "plist") else {
        fatalError("Could not find Translation.plist")
    }

    NSLog("Using \(url.absoluteURL) for translation")
    guard let root = NSDictionary(contentsOf: url) else {
        fatalError("Could not find dictionary for category (locale=\(preferredLocale)")
    }

    guard let relevant = root.value(forKey: category) as? NSDictionary else {
        fatalError("Could not create dictionary from Translation.plist")
    }

    return relevant
}

Then I created a String extension that uses the Translator as follows:

func localize(category: String) -> String {
    return Translator.instance.translate(category: category, string: self)
}

With this I call the Translator by "yes".localize("button"). In English I would expect "Yes", in German I would expect "Ja". The log says the following:

2017-07-05 08:45:24.728 myApp[13598:35048360] User's preferred locale is  de_DE

2017-07-05 08:45:24.728 myApp[13598:35048360] Using file:///Users/me/Library/Developer/CoreSimulator/Devices/A39D3318-943D-4EFE-BB97-5C2218279132/data/Containers/Bundle/Application/4614E696-B52E-4C30-BBE8-3C76F6392413/myApp.app/Base.lproj/Translation.plist for translation

I wonder why this happens and what I have missed. I would have expected that de.lproj/Translation.plist is loaded instead of Base.lproj/Translation.plist.

Any help is highly appreciated.

Body:
You can do it with single .plist file. You don't need to create different .plist files for it.

Firstly, Add English and German countries with locale in Project -> info
https://i.stack.imgur.com/M4QIY.png

Once, you added countries with locale in Project -> info then add localizable.strings file in your bundle.
https://i.stack.imgur.com/lnjgL.png

At the end, just add country's locale in your language support class.

NSArray* languages = @[@"en", @"de"];`enter code here`
    NSString *current = [languages objectAtIndex:0];
    [self setLanguage:current];

Hope it would help you.


问:
datewise multiple record display
Hi i have a class called ChatMessageBO which has properties such as Id, Msg, Name, and date.

i want to display data datewise.

```<code>List<chatmessagebo> SortedList = directChatWindow.messages.OrderBy(o => o.ts).ToList();
MessageList.DataSource = SortedList;
MessageList.DataBind();
</code>```

here i get all data properly but i want to display date and then name and msg.

example

03-07-2017

jaydeeep hello
rishi hi

04-07-2017

neha god mornin
jaydeep good moring all

view side code
date (Here i required help) 03-june contain 3 records so date then name,msg then 04 june contain 4 msg .

```<code>'<%#Eval("name")%><%#Eval("msg")%>'
</code>```

答:
You need to group the message objects coming from the database by the date. GroupBy method of LINQ should be useful.

Next thing you need to do is to use appropriate controls to display grouped data.
Consider following Example.

I have class ChatMessage and MessageGroup. ChatMessage is a simple class as yours with Id, Name, Message and Date properties. MessageGroup represents group of messages with Date as Grouping factor.

```<code>public class ChatMessage
{
    public int Id { get; set; }

    public string Message { get; set; }

    public string Name { get; set; }

    public DateTime Date { get; set; }
}

public class MessageGroup
{
    public DateTime Date { get; set; }

    public List<ChatMessage> Messages { get; set; }
}
</code>```

I am using asp:DataList control here to display messages.

```<code><asp:DataList ID="messageList" runat="server" OnItemDataBound="messageList_ItemDataBound" >
    <ItemTemplate>
        <table>
            <tr>
                <td>
                    <!--Displaying date first -->
                    <span><%# Eval("Date") %></span>
                </td>
                <td>
                    <!-- Inner DataList to display grouped messages-->
                    <asp:DataList ID="subMessageList" runat ="server">
                        <ItemTemplate>
                            <span><%# Eval("Name") %> : <%# Eval("Message") %></span>
                        </ItemTemplate>
                    </asp:DataList>
                </td>
            </tr>

            </table>
    </ItemTemplate>
</asp:DataList>
</code>```

Following is the approach to group the messages by Date and create List of MessageGroup objects and binding it to the datalist.

```<code>private void DisplayMessages()
{
    var messages = directChatWindow.messages.OrderBy(o => o.ts).ToList();

    var list = messages.GroupBy(msg => msg.Date).Select(grp => new MessageGroup { Date = grp.Key, Messages = grp.ToList() });

    messageList.DataSource = list;
    messageList.DataBind();
}
</code>```

Calling this method in the page load.

```<code>protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DisplayMessages();
    }
}
</code>```

This code will display only dates in the DataList. To display messages in the inner datalist we need to handle the ItemDataBound event of the main datalist.
In this event we will get the current DataItem bound to the current Item of the DataList. This DataItem is an object of MessageGroup. We will bind inner DataList to the Messages property of the MessageGroup instance.

```<code>protected void messageList_ItemDataBound(object sender, DataListItemEventArgs e)
{
    var messageGroup = e.Item.DataItem as MessageGroup;

    if(messageGroup != null)
    {
        var subList = e.Item.FindControl("subMessageList") as DataList;

        if(subList != null)
        {
            subList.DataSource = messageGroup.Messages;
            subList.DataBind();
        }
    }
}
</code>```

This way you can display the data the way you wanted.

Title: datewise multiple record display

Body:
Hi i have a class called ChatMessageBO which has properties such as Id, Msg, Name, and date.

i want to display data datewise.

List<chatmessagebo> SortedList = directChatWindow.messages.OrderBy(o => o.ts).ToList();
MessageList.DataSource = SortedList;
MessageList.DataBind();

here i get all data properly but i want to display date and then name and msg.

example

03-07-2017

jaydeeep hello
rishi hi

04-07-2017

neha god mornin
jaydeep good moring all

view side code
date (Here i required help) 03-june contain 3 records so date then name,msg then 04 june contain 4 msg .

'<%#Eval("name")%><%#Eval("msg")%>'

Body:
You need to group the message objects coming from the database by the date. GroupBy method of LINQ should be useful.

Next thing you need to do is to use appropriate controls to display grouped data.
Consider following Example.

I have class ChatMessage and MessageGroup. ChatMessage is a simple class as yours with Id, Name, Message and Date properties. MessageGroup represents group of messages with Date as Grouping factor.

public class ChatMessage
{
    public int Id { get; set; }

    public string Message { get; set; }

    public string Name { get; set; }

    public DateTime Date { get; set; }
}

public class MessageGroup
{
    public DateTime Date { get; set; }

    public List<ChatMessage> Messages { get; set; }
}

I am using asp:DataList control here to display messages.

<asp:DataList ID="messageList" runat="server" OnItemDataBound="messageList_ItemDataBound" >
    <ItemTemplate>
        <table>
            <tr>
                <td>
                    <!--Displaying date first -->
                    <span><%# Eval("Date") %></span>
                </td>
                <td>
                    <!-- Inner DataList to display grouped messages-->
                    <asp:DataList ID="subMessageList" runat ="server">
                        <ItemTemplate>
                            <span><%# Eval("Name") %> : <%# Eval("Message") %></span>
                        </ItemTemplate>
                    </asp:DataList>
                </td>
            </tr>

            </table>
    </ItemTemplate>
</asp:DataList>

Following is the approach to group the messages by Date and create List of MessageGroup objects and binding it to the datalist.

private void DisplayMessages()
{
    var messages = directChatWindow.messages.OrderBy(o => o.ts).ToList();

    var list = messages.GroupBy(msg => msg.Date).Select(grp => new MessageGroup { Date = grp.Key, Messages = grp.ToList() });

    messageList.DataSource = list;
    messageList.DataBind();
}

Calling this method in the page load.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DisplayMessages();
    }
}

This code will display only dates in the DataList. To display messages in the inner datalist we need to handle the ItemDataBound event of the main datalist.
In this event we will get the current DataItem bound to the current Item of the DataList. This DataItem is an object of MessageGroup. We will bind inner DataList to the Messages property of the MessageGroup instance.

protected void messageList_ItemDataBound(object sender, DataListItemEventArgs e)
{
    var messageGroup = e.Item.DataItem as MessageGroup;

    if(messageGroup != null)
    {
        var subList = e.Item.FindControl("subMessageList") as DataList;

        if(subList != null)
        {
            subList.DataSource = messageGroup.Messages;
            subList.DataBind();
        }
    }
}

This way you can display the data the way you wanted.


问:
Javafx Button size, EmptyBorder, and Read txt File into TextArea
I am trying to switch to javafx instead of swing but it has been a bit bumpy trying to find methods that do the exact tasks.

I am trying to get the buttons width to fill the entire scene and adjusts accordingly when you adjust the scene size.

Get a small empty border around text area and buttons.

Getting a method that reads a plain text file and replaces the current Text Area (not append).

```<code>package gui;

mport javafx.application.Application;
mport javafx.scene.Scene;
mport javafx.scene.control.Button;
mport javafx.stage.Stage;
mport javafx.scene.layout.*;
mport javafx.scene.control.TextArea;

public class Main extends Application{

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("TextArea Experiment 1");

        TextArea textArea = new TextArea();
        // Which TextArea method would I call to set a plain
        // text file into the text area ?
        BorderPane border = new BorderPane();
        border.setCenter(textArea);
        //border.setBorder(new EmptyBorder(10,10,10,10));
        // Is there a method like this in JavaFx ?
        GridPane grid = new GridPane();
        border.setBottom(grid);

        double screensize = border.getMaxWidth();
        Button option1 = new Button("Button 1");
        Button option2 = new Button("Button 2");
        Button option3 = new Button("Button 3");
        // how can I get the buttons to be max scene size and
        //adjust dynamically to scene dimensions ?
        option1.setMaxSize(Double.MAX_VALUE,Double.MAX_VALUE);
        //option1.setPrefWidth(Double.MAX_VALUE);
        System.out.println(screensize);
        grid.add(option1, 0,1);
        grid.add(option2,0,2);
        grid.add(option3,0,3);

        Scene scene = new Scene(border, 200, 100);
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args) {
           Application.launch(args);
    }
}
</code>```

答:
first of all I suggest that to take a look at this tutorial: http://code.makery.ch/library/javafx-8-tutorial/
If you want to build a well structured javafx application you have to make an .fxml file, a Controller class and (some) model class(es).

But for those points here are the answers.

If you want to set a Region's size you have to use .setPrefSize(double,double) method, if you want to set dynamic you have to use for example myButton.prefSizeProperty().bind(anyRegionYouWantToBindTo.widthProprty())

I don't really understand what you want, I think you would like to use some styling, then you can write a .css file then arr it to textArea's styleClass.

After you get the text from the file instead of using textArea.appendText(String) you have to user textArea.setText(String)

I think these are the sollutions for your problems but I strongly recommend to read a tutorial about javafx. So have fun :)

Body:
I am trying to switch to javafx instead of swing but it has been a bit bumpy trying to find methods that do the exact tasks.

I am trying to get the buttons width to fill the entire scene and adjusts accordingly when you adjust the scene size.

Get a small empty border around text area and buttons.

Getting a method that reads a plain text file and replaces the current Text Area (not append).

package gui;

mport javafx.application.Application;
mport javafx.scene.Scene;
mport javafx.scene.control.Button;
mport javafx.stage.Stage;
mport javafx.scene.layout.*;
mport javafx.scene.control.TextArea;

public class Main extends Application{

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("TextArea Experiment 1");

        TextArea textArea = new TextArea();
        // Which TextArea method would I call to set a plain
        // text file into the text area ?
        BorderPane border = new BorderPane();
        border.setCenter(textArea);
        //border.setBorder(new EmptyBorder(10,10,10,10));
        // Is there a method like this in JavaFx ?
        GridPane grid = new GridPane();
        border.setBottom(grid);

        double screensize = border.getMaxWidth();
        Button option1 = new Button("Button 1");
        Button option2 = new Button("Button 2");
        Button option3 = new Button("Button 3");
        // how can I get the buttons to be max scene size and
        //adjust dynamically to scene dimensions ?
        option1.setMaxSize(Double.MAX_VALUE,Double.MAX_VALUE);
        //option1.setPrefWidth(Double.MAX_VALUE);
        System.out.println(screensize);
        grid.add(option1, 0,1);
        grid.add(option2,0,2);
        grid.add(option3,0,3);

        Scene scene = new Scene(border, 200, 100);
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args) {
           Application.launch(args);
    }
}


问:
Password confirmation isn't working
For the life of me, I can't figure out what I've done wrong. I want a message to pop up when someone tries entering passwords that don't match below is the form code.

function passcheck() {
  var p1 = _("pass1").value;
  var p2 = _("pass2").value;
  if (p1 != p2) {
    status.innerHTML = "Your passwords don't match";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="signupform" id="signupform" onSubmit="return false;"><div id="password">Create Password:</div>
  <input id="pass1" type="password" maxlength="88" placeholder="●●●●●●●●●">
  <div id="confirm">Confirm Password:</div>
  <input id="pass2" type="password" onBlur="passcheck()" maxlength="88" placeholder="●●●●●●●●●"></code>```

What am I missing?

答:
```<code>function passcheck() {
  var p1 = $("#pass1").val();
  var p2 = $("#pass2").val();
  if (p1 != p2) {
    status.innerHTML = "Your passwords don't match";
  }
}
</code>```

Since you have tagged Jquery I am assuming u have Jquery in your HTML

In Jquery $("#idoftheField").val() to get value of the field

Title: Password confirmation isn't working

Body:
For the life of me, I can't figure out what I've done wrong. I want a message to pop up when someone tries entering passwords that don't match below is the form code.

function passcheck() {
  var p1 = _("pass1").value;
  var p2 = _("pass2").value;
  if (p1 != p2) {
    status.innerHTML = "Your passwords don't match";
  }
}

<form name="signupform" id="signupform" onSubmit="return false;">
Create Password:

  <input id="pass1" type="password" maxlength="88" placeholder="●●●●●●●●●">

Confirm Password:

  <input id="pass2" type="password" onBlur="passcheck()" maxlength="88" placeholder="●●●●●●●●●">

What am I missing?

Body:
function passcheck() {
  var p1 = $("#pass1").val();
  var p2 = $("#pass2").val();
  if (p1 != p2) {
    status.innerHTML = "Your passwords don't match";
  }
}

Since you have tagged Jquery I am assuming u have Jquery in your HTML

In Jquery $("#idoftheField").val() to get value of the field


问:
detecting function call with regex
I want to find out whether I can detect function call using regex. The basic case is easy: somefunction(1, 2);

But what if I had code:

somefunction(someotherfunction(), someotherotherfunction());

or

somefunction(function () { return 1; }, function() {return 2;});

or

caller_function(somefunction(function () { return 1; }, function() {return 2;}))

In this case I need to match same number of opening braces and closing braces so that I can find end of call to somefunction

Is it possible?

Thanks in advance.

答:
Your question is misleading. It's not as simple as you think.

First, the grammar isn't regular. Regular expressions are not the right tool.

Second, you ask "detecting function call" but the samples show anonymous function definitions, a totally different ball game.

Here's a start using Boost Spirit:

```<code>start   = skip(space) [ fcall ];
fcall   = ident >> '(' >> -args >> ')';
args    = arg % ',';
arg     = fdef | fcall;
fdef    = lexeme["function"] >> '(' >> -formals >> ')' >> body;
formals = ident % ',';

identch = alpha | char_("_");
ident   = identch >> *(identch|digit);
body    = '{' >> *~char_('}') >> '}';
</code>```

Which would map onto an AST like:

```<code>struct function_definition {
    std::vector<std::string> formal_arguments;
    std::string body;
};

struct function_call;

using argument = boost::variant<
    function_definition,
    boost::recursive_wrapper<function_call>
>;

struct function_call {
    std::string name;
    std::vector<argument> args;
};
</code>```

DEMO

Live On Coliru

```<code>// #define BOOST_SPIRIT_DEBUG
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/io.hpp>
#include <boost/fusion/adapted/struct.hpp>

struct function_definition {
    std::vector<std::string> formal_arguments;
    std::string body;
};

struct function_call;

using argument = boost::variant<
    function_definition,
    boost::recursive_wrapper<function_call>
>;

struct function_call {
    std::string name;
    std::vector<argument> args;
};

BOOST_FUSION_ADAPT_STRUCT(function_call, name, args)
BOOST_FUSION_ADAPT_STRUCT(function_definition, formal_arguments, body)

namespace qi = boost::spirit::qi;

template <typename It>
struct Parser : qi::grammar<It, function_call()> {
    Parser() : Parser::base_type(start) {
        using namespace qi;

        start   = skip(space) [ fcall ];
        fcall   = ident >> '(' >> -args >> ')';
        args    = arg % ',';
        arg     = fdef | fcall;
        fdef    = lexeme["function"] >> '(' >> -formals >> ')' >> body;
        formals = ident % ',';

        identch = alpha | char_("_");
        ident   = identch >> *(identch|digit);
        body    = '{' >> *~char_('}') >> '}';

        BOOST_SPIRIT_DEBUG_NODES((start)(fcall)(args)(arg)(fdef)(formals)(ident)(body))
    }
  private:
    using Skipper = qi::space_type;
    qi::rule<It, function_call()> start;
    qi::rule<It, function_call(), Skipper> fcall;
    qi::rule<It, argument(), Skipper> arg;
    qi::rule<It, std::vector<argument>(), Skipper> args;
    qi::rule<It, function_definition(), Skipper> fdef;
    qi::rule<It, std::vector<std::string>(), Skipper> formals;

    qi::rule<It, char()> identch;
    qi::rule<It, std::string()> ident, body;
};

// for debug:
#include <experimental/iterator>
static inline std::ostream& operator<<(std::ostream& os, function_definition const& v) {
    os << "function(";
    std::copy(v.formal_arguments.begin(), v.formal_arguments.end(), std::experimental::make_ostream_joiner(os, ", "));
    return os << ") {" << v.body << "}";
}

static inline std::ostream& operator<<(std::ostream& os, function_call const& v) {
    os << v.name << "(";
    std::copy(v.args.begin(), v.args.end(), std::experimental::make_ostream_joiner(os, ", "));
    return os << ")";
}

int main() {
    std::string const input = "caller_function(somefunction(function () { return 1; }, function() {return 2;}))";
    using It = std::string::const_iterator;
    Parser<It> const p;

    It f = input.begin(), l = input.end();
    function_call parsed;
    bool ok = parse(f, l, p, parsed);
    if (ok) {
        std::cout << "Parsed ok: " << parsed << "\n";
    } else {
        std::cout << "Parse failed\n";
    }

    if (f!=l)
        std::cout << "Remaining unparsed input: '" << std::string(f,l) << "'\n";
}
</code>```

Prints

```<code>Parsed ok: caller_function(somefunction(function() { return 1; }, function() {return 2;}))
</code>```

Title: detecting function call with regex

Body:
Your question is misleading. It's not as simple as you think.

First, the grammar isn't regular. Regular expressions are not the right tool.

Second, you ask "detecting function call" but the samples show anonymous function definitions, a totally different ball game.

Here's a start using Boost Spirit:

start   = skip(space) [ fcall ];
fcall   = ident >> '(' >> -args >> ')';
args    = arg % ',';
arg     = fdef | fcall;
fdef    = lexeme["function"] >> '(' >> -formals >> ')' >> body;
formals = ident % ',';

identch = alpha | char_("_");
ident   = identch >> *(identch|digit);
body    = '{' >> *~char_('}') >> '}';

Which would map onto an AST like:

struct function_definition {
    std::vector<std::string> formal_arguments;
    std::string body;
};

struct function_call;

using argument = boost::variant<
    function_definition,
    boost::recursive_wrapper<function_call>
>;

struct function_call {
    std::string name;
    std::vector<argument> args;
};

DEMO

Live On Coliru

// #define BOOST_SPIRIT_DEBUG
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/io.hpp>
#include <boost/fusion/adapted/struct.hpp>

struct function_definition {
    std::vector<std::string> formal_arguments;
    std::string body;
};

struct function_call;

using argument = boost::variant<
    function_definition,
    boost::recursive_wrapper<function_call>
>;

struct function_call {
    std::string name;
    std::vector<argument> args;
};

BOOST_FUSION_ADAPT_STRUCT(function_call, name, args)
BOOST_FUSION_ADAPT_STRUCT(function_definition, formal_arguments, body)

namespace qi = boost::spirit::qi;

template <typename It>
struct Parser : qi::grammar<It, function_call()> {
    Parser() : Parser::base_type(start) {
        using namespace qi;

        start   = skip(space) [ fcall ];
        fcall   = ident >> '(' >> -args >> ')';
        args    = arg % ',';
        arg     = fdef | fcall;
        fdef    = lexeme["function"] >> '(' >> -formals >> ')' >> body;
        formals = ident % ',';

        identch = alpha | char_("_");
        ident   = identch >> *(identch|digit);
        body    = '{' >> *~char_('}') >> '}';

        BOOST_SPIRIT_DEBUG_NODES((start)(fcall)(args)(arg)(fdef)(formals)(ident)(body))
    }
  private:
    using Skipper = qi::space_type;
    qi::rule<It, function_call()> start;
    qi::rule<It, function_call(), Skipper> fcall;
    qi::rule<It, argument(), Skipper> arg;
    qi::rule<It, std::vector<argument>(), Skipper> args;
    qi::rule<It, function_definition(), Skipper> fdef;
    qi::rule<It, std::vector<std::string>(), Skipper> formals;

    qi::rule<It, char()> identch;
    qi::rule<It, std::string()> ident, body;
};

// for debug:
#include <experimental/iterator>
static inline std::ostream& operator<<(std::ostream& os, function_definition const& v) {
    os << "function(";
    std::copy(v.formal_arguments.begin(), v.formal_arguments.end(), std::experimental::make_ostream_joiner(os, ", "));
    return os << ") {" << v.body << "}";
}

static inline std::ostream& operator<<(std::ostream& os, function_call const& v) {
    os << v.name << "(";
    std::copy(v.args.begin(), v.args.end(), std::experimental::make_ostream_joiner(os, ", "));
    return os << ")";
}

int main() {
    std::string const input = "caller_function(somefunction(function () { return 1; }, function() {return 2;}))";
    using It = std::string::const_iterator;
    Parser<It> const p;

    It f = input.begin(), l = input.end();
    function_call parsed;
    bool ok = parse(f, l, p, parsed);
    if (ok) {
        std::cout << "Parsed ok: " << parsed << "\n";
    } else {
        std::cout << "Parse failed\n";
    }

    if (f!=l)
        std::cout << "Remaining unparsed input: '" << std::string(f,l) << "'\n";
}

Prints

Parsed ok: caller_function(somefunction(function() { return 1; }, function() {return 2;}))


答:
Use @@rowcount: SELECT @@rowcount AS 'RowsChanged'

http://www.brettb.com/SQL_Help_Rowcount_Rows_Affected.asp

Title: SQL UPDATE Command - How can i tell how many records have been updated?


问:
App crashes on parse push notification when the app is not running
When I open my android app and test parse push notification, it works. But when I killed my app from multitasking and test again, app crashes.

```<code>protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Parse.initialize(MainActivity.this, "cMm2mJvkRlIButQ0wM4lfj5veFxrQYUKw8P4mdM4", "bOplHPHvWb9IRzv2EbQnylWFgyveTsDYEspV2qs0");
        ParseAnalytics.trackAppOpenedInBackground(getIntent());
        ParsePush.subscribeInBackground("", new SaveCallback() {
            @Override
            public void done(ParseException e) {
                if (e == null) {
                    Log.d("com.parse.push", "successfully subscribed to the broadcast channel.");
                } else {
                    Log.e("com.parse.push", "failed to subscribe for push", e);
                }
            }
        });
}
</code>```

Error Log

08-18 21:16:21.694  24406-24406/? E/AndroidRuntime﹕ FATAL EXCEPTION:
  main
      Process: com.myatminsoe.mkeyboard, PID: 24406
      java.lang.RuntimeException: Unable to create service com.parse.PushService: java.lang.NullPointerException: Attempt to
  invoke virtual method 'android.content.Context
  com.parse.ParsePlugins$Android.applicationContext()' on a null object
  reference
              at android.app.ActivityThread.handleCreateService(ActivityThread.java:2771)
              at android.app.ActivityThread.access$1800(ActivityThread.java:151)
              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1386)
              at android.os.Handler.dispatchMessage(Handler.java:102)
              at android.os.Looper.loop(Looper.java:135)
              at android.app.ActivityThread.main(ActivityThread.java:5254)
              at java.lang.reflect.Method.invoke(Native Method)
              at java.lang.reflect.Method.invoke(Method.java:372)
              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context
  com.parse.ParsePlugins$Android.applicationContext()' on a null object
  reference
              at com.parse.PushService.onCreate(PushService.java:238)
              at android.app.ActivityThread.handleCreateService(ActivityThread.java:2761)
              at android.app.ActivityThread.access$1800(ActivityThread.java:151)
              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1386)
              at android.os.Handler.dispatchMessage(Handler.java:102)
              at android.os.Looper.loop(Looper.java:135)
              at android.app.ActivityThread.main(ActivityThread.java:5254)
              at java.lang.reflect.Method.invoke(Native Method)
              at java.lang.reflect.Method.invoke(Method.java:372)
              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

答:
Do the parse initialisation in Application onCreate and make sure you are calling it in the mainThread.</p>

```<code>Parse.initialize(new Parse.Configuration.Builder(getApplicationContext()).applicationId(
                    ...).build());
</code>```

Body:
When I open my android app and test parse push notification, it works. But when I killed my app from multitasking and test again, app crashes.

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Parse.initialize(MainActivity.this, "cMm2mJvkRlIButQ0wM4lfj5veFxrQYUKw8P4mdM4", "bOplHPHvWb9IRzv2EbQnylWFgyveTsDYEspV2qs0");
        ParseAnalytics.trackAppOpenedInBackground(getIntent());
        ParsePush.subscribeInBackground("", new SaveCallback() {
            @Override
            public void done(ParseException e) {
                if (e == null) {
                    Log.d("com.parse.push", "successfully subscribed to the broadcast channel.");
                } else {
                    Log.e("com.parse.push", "failed to subscribe for push", e);
                }
            }
        });
}

Error Log

08-18 21:16:21.694  24406-24406/? E/AndroidRuntime﹕ FATAL EXCEPTION:
  main
      Process: com.myatminsoe.mkeyboard, PID: 24406
      java.lang.RuntimeException: Unable to create service com.parse.PushService: java.lang.NullPointerException: Attempt to
  invoke virtual method 'android.content.Context
  com.parse.ParsePlugins$Android.applicationContext()' on a null object
  reference
              at android.app.ActivityThread.handleCreateService(ActivityThread.java:2771)
              at android.app.ActivityThread.access$1800(ActivityThread.java:151)
              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1386)
              at android.os.Handler.dispatchMessage(Handler.java:102)
              at android.os.Looper.loop(Looper.java:135)
              at android.app.ActivityThread.main(ActivityThread.java:5254)
              at java.lang.reflect.Method.invoke(Native Method)
              at java.lang.reflect.Method.invoke(Method.java:372)
              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context
  com.parse.ParsePlugins$Android.applicationContext()' on a null object
  reference
              at com.parse.PushService.onCreate(PushService.java:238)
              at android.app.ActivityThread.handleCreateService(ActivityThread.java:2761)
              at android.app.ActivityThread.access$1800(ActivityThread.java:151)
              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1386)
              at android.os.Handler.dispatchMessage(Handler.java:102)
              at android.os.Looper.loop(Looper.java:135)
              at android.app.ActivityThread.main(ActivityThread.java:5254)
              at java.lang.reflect.Method.invoke(Native Method)
              at java.lang.reflect.Method.invoke(Method.java:372)
              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Body:
Do the parse initialisation in Application onCreate and make sure you are calling it in the mainThread.

Parse.initialize(new Parse.Configuration.Builder(getApplicationContext()).applicationId(
                    ...).build());


问:
How to fetch last row using distinct and group by same column
I want to retrieve balance of last row from table  using distinct accountid from last ledgerid

```<code>|---ledgerid---|--accountid--|--blance--|
|     1        |      1      |    500   |
|     2        |      1      |    800   |
</code>```

i want output as

```<code>|---ledgerid---|--accountid--|--blance--|
|     2        |      1      |    800   |
</code>```

答:
You can give row number based on accountid and in the descending order of ledgerid.

Query

```<code>select t2.`ledgerid`,
       t2.`accountid`,
       t2.`blance`
from (
   select `ledgerid`,
   `accountid`,
   `blance`, (
       case `accountid`
       when @curA
       then @curRow := @curRow + 1
       else @curRow := 1 and @curA := `accountid` end
     ) as `rn`
     from `your_table_name` t,
     (select @curRow := 0, @curA := '') r
     order by `accountid`, `ledgerid` desc
)t2
where t2.`rn` = 1;
</code>```

Find demo here

Body:
I want to retrieve balance of last row from table  using distinct accountid from last ledgerid

|---ledgerid---|--accountid--|--blance--|
|     1        |      1      |    500   |
|     2        |      1      |    800   |

i want output as

|---ledgerid---|--accountid--|--blance--|
|     2        |      1      |    800   |

Body:
You can give row number based on accountid and in the descending order of ledgerid.

Query

select t2.`ledgerid`,
       t2.`accountid`,
       t2.`blance`
from (
   select `ledgerid`,
   `accountid`,
   `blance`, (
       case `accountid`
       when @curA
       then @curRow := @curRow + 1
       else @curRow := 1 and @curA := `accountid` end
     ) as `rn`
     from `your_table_name` t,
     (select @curRow := 0, @curA := '') r
     order by `accountid`, `ledgerid` desc
)t2
where t2.`rn` = 1;

Find demo here


问:
javax.faces.FacesException: java.lang.RuntimeException: Cannot find FacesContext
I'm trying a simple project to work on jboss, but I'm stuck at  this error  (I already tried using .jsf on the URL). the application in tomcat work's fine

```<code>javax.servlet.ServletException: java.lang.RuntimeException: Cannot find FacesContext
 javax.faces.webapp.FacesServlet.service

root cause

javax.faces.FacesException: java.lang.RuntimeException: Cannot find FacesContext
 org.apache.myfaces.context.servlet.ServletExternalContextImpl.dispatch(ServletExternalContextImpl.java:425)
 org.apache.myfaces.application.jsp.JspViewHandlerImpl.renderView(JspViewHandlerImpl.java:211)
 org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:41)
 org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:132)
 javax.faces.webapp.FacesServlet.service(FacesServlet.java:140)
 org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96
</code>```

my web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
         version="2.4">
 <listener>
  <listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
 </listener>

<servlet>
    <servlet-name>javax.faces.FacesServlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>javax.faces.FacesServlet</servlet-name>
    <url-pattern>*.faces</url-pattern>
  </servlet-mapping>
  <filter>
    <filter-name>faces-redirect-filter</filter-name>
    <filter-class>core.FacesRedirectFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>faces-redirect-filter</filter-name>
    <url-pattern>*.jsp</url-pattern>
  </filter-mapping>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
</web-app>
</code>```

faces-config xml

```<code><?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
"http://java.sun.com/dtd/web-facesconfig_1_1.dtd">

<faces-config>
  <managed-bean>
    <managed-bean-name>resumeBean</managed-bean-name>
    <managed-bean-class>core.ResumeBean</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
  </managed-bean>
  <managed-bean>
    <managed-bean-name>colorBean</managed-bean-name>
    <managed-bean-class>core.ColorBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
  </managed-bean>
  <navigation-rule>
    <from-view-id>/customize.jsp</from-view-id>
    <navigation-case>
      <from-outcome>same-color</from-outcome>
      <to-view-id>/WEB-INF/results/same-color.jsp</to-view-id>
    </navigation-case>
    <navigation-case>
      <from-outcome>success</from-outcome>
      <to-view-id>/WEB-INF/results/show-preview.jsp</to-view-id>
    </navigation-case>
  </navigation-rule>
  <navigation-rule>
    <from-view-id>/customize-bg.jsp</from-view-id>
    <navigation-case>
      <from-outcome>success</from-outcome>
      <to-view-id>/WEB-INF/results/show-preview2.jsp</to-view-id>
    </navigation-case>
  </navigation-rule>
</faces-config>
</code>```

答:
javax.faces.FacesException: java.lang.RuntimeException: Cannot find FacesContext

JSF components in the JSP page are complaining that the FacesContext cannot be found. The one responsible for creating this is the FacesServlet.

Here,

```<code><servlet-mapping>
    <servlet-name>javax.faces.FacesServlet</servlet-name>
    <url-pattern>*.faces</url-pattern>
</servlet-mapping>
</code>```

you've declared the FacesServlet to listen on an url-pattern of *.faces. So, to get the FacesServlet to run (and to create the FacesContext) you need to ensure that the request URL matches http://example.com/context/page.faces and thus not http://example.com/context/page.jsp.

If you rather want to use http://example.com/context/page.jsf, then you need to change the url-pattern of the FacesServlet to *.jsf.

That said, the FacesRedirectFilter is suspicious as well. Isn't it redirecting *.jsp to *.jsf or so? If so, then you need to modify that filter as well. However, if the sole intent is to prevent users from accessing *.jsp files directly without involvement of FacesServlet, then better add the following security constraint to the web.xml:

```<code><security-constraint>
    <display-name>Restrict direct access to JSP files</display-name>
    <web-resource-collection>
        <web-resource-name>JSP files</web-resource-name>
        <url-pattern>*.jsp</url-pattern>
    </web-resource-collection>
    <auth-constraint />
</security-constraint>
</code>```

(and remove that Filter).

Unrelated to the problem, you mentioned JSF 1.2, but you've declared your faces-config.xml as JSF 1.1. Any JSF 1.2 implementation or newer will fall back to JSF 1.1 compatibility. You need to declare it as JSF 1.2 as well.

```<code><faces-config version="1.2"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xi="http://www.w3.org/2001/XInclude"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">
</code>```

(and get rid of that DOCTYPE)

Body:
I'm trying a simple project to work on jboss, but I'm stuck at  this error  (I already tried using .jsf on the URL). the application in tomcat work's fine

javax.servlet.ServletException: java.lang.RuntimeException: Cannot find FacesContext
 javax.faces.webapp.FacesServlet.service

root cause

javax.faces.FacesException: java.lang.RuntimeException: Cannot find FacesContext
 org.apache.myfaces.context.servlet.ServletExternalContextImpl.dispatch(ServletExternalContextImpl.java:425)
 org.apache.myfaces.application.jsp.JspViewHandlerImpl.renderView(JspViewHandlerImpl.java:211)
 org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:41)
 org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:132)
 javax.faces.webapp.FacesServlet.service(FacesServlet.java:140)
 org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96

my web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
         version="2.4">
 <listener>
  <listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
 </listener>

<servlet>
    <servlet-name>javax.faces.FacesServlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>javax.faces.FacesServlet</servlet-name>
    <url-pattern>*.faces</url-pattern>
  </servlet-mapping>
  <filter>
    <filter-name>faces-redirect-filter</filter-name>
    <filter-class>core.FacesRedirectFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>faces-redirect-filter</filter-name>
    <url-pattern>*.jsp</url-pattern>
  </filter-mapping>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
</web-app>

faces-config xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
"http://java.sun.com/dtd/web-facesconfig_1_1.dtd">

<faces-config>
  <managed-bean>
    <managed-bean-name>resumeBean</managed-bean-name>
    <managed-bean-class>core.ResumeBean</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
  </managed-bean>
  <managed-bean>
    <managed-bean-name>colorBean</managed-bean-name>
    <managed-bean-class>core.ColorBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
  </managed-bean>
  <navigation-rule>
    <from-view-id>/customize.jsp</from-view-id>
    <navigation-case>
      <from-outcome>same-color</from-outcome>
      <to-view-id>/WEB-INF/results/same-color.jsp</to-view-id>
    </navigation-case>
    <navigation-case>
      <from-outcome>success</from-outcome>
      <to-view-id>/WEB-INF/results/show-preview.jsp</to-view-id>
    </navigation-case>
  </navigation-rule>
  <navigation-rule>
    <from-view-id>/customize-bg.jsp</from-view-id>
    <navigation-case>
      <from-outcome>success</from-outcome>
      <to-view-id>/WEB-INF/results/show-preview2.jsp</to-view-id>
    </navigation-case>
  </navigation-rule>
</faces-config>

Body:
javax.faces.FacesException: java.lang.RuntimeException: Cannot find FacesContext

JSF components in the JSP page are complaining that the FacesContext cannot be found. The one responsible for creating this is the FacesServlet.

Here,

<servlet-mapping>
    <servlet-name>javax.faces.FacesServlet</servlet-name>
    <url-pattern>*.faces</url-pattern>
</servlet-mapping>

you've declared the FacesServlet to listen on an url-pattern of *.faces. So, to get the FacesServlet to run (and to create the FacesContext) you need to ensure that the request URL matches http://example.com/context/page.faces and thus not http://example.com/context/page.jsp.

If you rather want to use http://example.com/context/page.jsf, then you need to change the url-pattern of the FacesServlet to *.jsf.

That said, the FacesRedirectFilter is suspicious as well. Isn't it redirecting *.jsp to *.jsf or so? If so, then you need to modify that filter as well. However, if the sole intent is to prevent users from accessing *.jsp files directly without involvement of FacesServlet, then better add the following security constraint to the web.xml:

<security-constraint>
    <display-name>Restrict direct access to JSP files</display-name>
    <web-resource-collection>
        <web-resource-name>JSP files</web-resource-name>
        <url-pattern>*.jsp</url-pattern>
    </web-resource-collection>
    <auth-constraint />
</security-constraint>

(and remove that Filter).

Unrelated to the problem, you mentioned JSF 1.2, but you've declared your faces-config.xml as JSF 1.1. Any JSF 1.2 implementation or newer will fall back to JSF 1.1 compatibility. You need to declare it as JSF 1.2 as well.

<faces-config version="1.2"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xi="http://www.w3.org/2001/XInclude"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">

(and get rid of that DOCTYPE)


问:
Python Get System Environment Variable Linux
I've exposed one system environment variable say KEY1 with value VALUE1 in /etc/profile (I know, I know, it's probably bad)

Now in my shell if I do

```<code>$ echo $KEY1
VALUE1
</code>```

But when I do

```<code>$ python -c "import os; print os.environ.get('KEY1')"
None
$
</code>```

Why might this be the case?

答:
You might not have exported the variable. You can think of export as a way of making a shell variable public and not private to the shell. Take a look at the export man page.</p>

```<code>➜  ~ K=1
➜  ~ echo $K
1
➜  ~ python -c "import os; print os.environ.get('K')"
None
➜  ~ export K=1
➜  ~ python -c "import os; print os.environ.get('K')"
1
</code>```

Body:
I've exposed one system environment variable say KEY1 with value VALUE1 in /etc/profile (I know, I know, it's probably bad)

Now in my shell if I do

$ echo $KEY1
VALUE1

But when I do

$ python -c "import os; print os.environ.get('KEY1')"
None
$

Why might this be the case?

Body:
You might not have exported the variable. You can think of export as a way of making a shell variable public and not private to the shell. Take a look at the export man page.

➜  ~ K=1
➜  ~ echo $K
1
➜  ~ python -c "import os; print os.environ.get('K')"
None
➜  ~ export K=1
➜  ~ python -c "import os; print os.environ.get('K')"
1


问:
How to place image correctly in input tag
I created a input tag with two images cross and arrow.

Here is my code.

```<code><div id="chart_line" style="position: relative;">
    <input type="text" id="myInput" list="myUL" onclick="openingList()" onkeyup="openingList()" style="width:30%;">
        <div id="triggers">
            <img class="trigger" onclick="deleteValue()" src="css/clearT.png" id="cross">
            <img class="trigger" src="css/combo_arrow.png" onclick="openingList()" id="arrow">
        </div>
</div>
</code>```

Here is my fiddle :

Fiddle

I am facing two problem here.

I want my image should be at the end with respect to input tag. Right now I am giving manually in CSS. You can see

#triggers {
      position: absolute;
      left : 110px;
      top: 5px;
    }

I am giving left : 110px How can I fix this always at end of input tag. Input tag width may change.

I want to restrict my input tag just before the image start. Right now text is coming below the image. Even cursor is also going below the image. Any idea how to fix that.

Here is image for your reference.

Thanks

答:
You need to do a trick here. You need to put both the input and imgs inside a div then remove the border and properly style the components to make it look natural.

Here is a reference on how to do it.
Put icon inside input element in a form

Body:
I created a input tag with two images cross and arrow.

Here is my code.

    <input type="text" id="myInput" list="myUL" onclick="openingList()" onkeyup="openingList()" style="width:30%;">

Here is my fiddle :

Fiddle

I am facing two problem here.

I want my image should be at the end with respect to input tag. Right now I am giving manually in CSS. You can see

#triggers {
      position: absolute;
      left : 110px;
      top: 5px;
    }

I am giving left : 110px How can I fix this always at end of input tag. Input tag width may change.

I want to restrict my input tag just before the image start. Right now text is coming below the image. Even cursor is also going below the image. Any idea how to fix that.

Here is image for your reference.

Thanks


问:
DocumentDb Repository to Query Child Documents Generically
In DocumentDb, is it possible to search for child documents that meet a certain criteria without having to involve the parent class in the query?

BACKGROUND

I'm (trying to start by) using the DocumentDbRepository.cs that is generated for you automatically in the Azure Portal when you create a new Azure Cosmos DB account.  However, it's obvious that this was meant merely as a starting point and will require some additional work for individual scenarios.

In a C# Console app (.NET Core) I have a simple parent-child relationship between Company and Employees:

```<code>public class Customer
{
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; }

    [JsonProperty(PropertyName = "name")]
    public string Name { get; set; }

    [JsonProperty(PropertyName = "location")]
    public string Location { get; set; }

    [JsonProperty(PropertyName = "employees")]
    public List<Employee> Employees { get; set; }

    public Customer()
    {
        Employees = new List<Employee>();
    }
}

public class Employee
{
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; }

    [JsonProperty(PropertyName = "firstName")]
    public string FirstName { get; set; }

    [JsonProperty(PropertyName = "lastName")]
    public string LastName { get; set; }

    [JsonProperty(PropertyName = "sales")]
    public double Sales { get; set; }

}
</code>```

In the Document Explorer, I can see that I have one instance of this class structure like so:

```<code>{
  "id": "7",
  "name": "ACME Corp",
  "location": "New York",
  "employees": [
    {
      "id": "c4202793-da55-4324-88c9-b9c9fe8f4b6c",
      "firstName": "John",
      "lastName": "Smith",
      "sales": 123
    }
  ]
}
</code>```

If I wanted to get all Companies that meet a certain criteria, it would be a fairly easy operation using the generated DocumentDbRepository.cs methods:

```<code>DocumentDBRepository<Customer>.Initialize();
var customers = DocumentDBRepository<Customer>.GetItemsAsync(p => p.Location.Equals("New York")).Result;
</code>```

... for reference, the generated GetItemsAsync() from Microsoft method looks like this:

```<code>    public static async Task<IEnumerable<T>> GetItemsAsync(Expression<Func<T, bool>> predicate)
    {
        IDocumentQuery<T> query = client.CreateDocumentQuery<T>(
                UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId),
                new FeedOptions { MaxItemCount = -1 })
            .Where(predicate)
            .AsDocumentQuery();

        List<T> results = new List<T>();
        while (query.HasMoreResults)
        {
            results.AddRange(await query.ExecuteNextAsync<T>());
        }

        return results;
    }
</code>```

PROBLEM

HOWEVER, if I want to retrieve ONLY EMPLOYEES regardless of the Company they belong to, I'm not sure how to write a method in the repository class that will accomplish this.

First, I think I'll need some sort of type property so I can differentiate what a Customer is versus an Employee (versus other domain class types I may want to also add in the same collection).

Second, I would probably query that using that type property for all queries and not use the DocumentDbRepository.cs methods which seem to only work with root data.  In other words, the DocumentDbRepository.cs methods seem to only be concerned with non-hierarchical entities.

But this is where things break down ... given the generic nature of this sample repository class, I can't quite connect the dots in my mind required to query sub-documents / children.

I am merely asking for a nudge in the right direction here.  Thank you.

答:
I want to retrieve ONLY EMPLOYEES regardless of the Company

If I understanding correctly, you want to query employees according employees' property  from Customer. If it is that case, we could do that with SQL as following, and we just need to change the where <filter_condition> as we want.

```<code>SELECT c as employees
FROM c IN Customer.employees
WHERE c.firstName = 'John'
</code>```

I test with your mentioned document from Azure portal, it works correctly on my side.

The following is the c# demo code:

```<code>var endpointUrl = "https://yourdocumentdbname.documents.azure.com:443/";
var authorizationKey = "xxxxx";
var databaseId = "database name";
var collectionId = "collecton name";
var client =  new DocumentClient(new Uri(endpointUrl), authorizationKey);
var sql = "SELECT c as employee FROM c IN Customer.employees WHERE c.firstName = 'xx'";
var collection = client.CreateDocumentCollectionIfNotExistsAsync(
            UriFactory.CreateDatabaseUri(databaseId), new DocumentCollection
            {
                Id = collectionId

            }).Result.Resource;
var query = client.CreateDocumentQuery(collection.SelfLink, sql).AsDocumentQuery();

while (query.HasMoreResults)
{
  var documents =  query.ExecuteNextAsync().Result;
  //do something
}
</code>```

Body:
In DocumentDb, is it possible to search for child documents that meet a certain criteria without having to involve the parent class in the query?

BACKGROUND

I'm (trying to start by) using the DocumentDbRepository.cs that is generated for you automatically in the Azure Portal when you create a new Azure Cosmos DB account.  However, it's obvious that this was meant merely as a starting point and will require some additional work for individual scenarios.

In a C# Console app (.NET Core) I have a simple parent-child relationship between Company and Employees:

public class Customer
{
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; }

    [JsonProperty(PropertyName = "name")]
    public string Name { get; set; }

    [JsonProperty(PropertyName = "location")]
    public string Location { get; set; }

    [JsonProperty(PropertyName = "employees")]
    public List<Employee> Employees { get; set; }

    public Customer()
    {
        Employees = new List<Employee>();
    }
}

public class Employee
{
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; }

    [JsonProperty(PropertyName = "firstName")]
    public string FirstName { get; set; }

    [JsonProperty(PropertyName = "lastName")]
    public string LastName { get; set; }

    [JsonProperty(PropertyName = "sales")]
    public double Sales { get; set; }

}

In the Document Explorer, I can see that I have one instance of this class structure like so:

{
  "id": "7",
  "name": "ACME Corp",
  "location": "New York",
  "employees": [
    {
      "id": "c4202793-da55-4324-88c9-b9c9fe8f4b6c",
      "firstName": "John",
      "lastName": "Smith",
      "sales": 123
    }
  ]
}

If I wanted to get all Companies that meet a certain criteria, it would be a fairly easy operation using the generated DocumentDbRepository.cs methods:

DocumentDBRepository<Customer>.Initialize();
var customers = DocumentDBRepository<Customer>.GetItemsAsync(p => p.Location.Equals("New York")).Result;

... for reference, the generated GetItemsAsync() from Microsoft method looks like this:

    public static async Task<IEnumerable<T>> GetItemsAsync(Expression<Func<T, bool>> predicate)
    {
        IDocumentQuery<T> query = client.CreateDocumentQuery<T>(
                UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId),
                new FeedOptions { MaxItemCount = -1 })
            .Where(predicate)
            .AsDocumentQuery();

        List<T> results = new List<T>();
        while (query.HasMoreResults)
        {
            results.AddRange(await query.ExecuteNextAsync<T>());
        }

        return results;
    }

PROBLEM

HOWEVER, if I want to retrieve ONLY EMPLOYEES regardless of the Company they belong to, I'm not sure how to write a method in the repository class that will accomplish this.

First, I think I'll need some sort of type property so I can differentiate what a Customer is versus an Employee (versus other domain class types I may want to also add in the same collection).

Second, I would probably query that using that type property for all queries and not use the DocumentDbRepository.cs methods which seem to only work with root data.  In other words, the DocumentDbRepository.cs methods seem to only be concerned with non-hierarchical entities.

But this is where things break down ... given the generic nature of this sample repository class, I can't quite connect the dots in my mind required to query sub-documents / children.

I am merely asking for a nudge in the right direction here.  Thank you.

Body:
I want to retrieve ONLY EMPLOYEES regardless of the Company

If I understanding correctly, you want to query employees according employees' property  from Customer. If it is that case, we could do that with SQL as following, and we just need to change the where <filter_condition> as we want.

SELECT c as employees
FROM c IN Customer.employees
WHERE c.firstName = 'John'

I test with your mentioned document from Azure portal, it works correctly on my side.

The following is the c# demo code:

var endpointUrl = "https://yourdocumentdbname.documents.azure.com:443/";
var authorizationKey = "xxxxx";
var databaseId = "database name";
var collectionId = "collecton name";
var client =  new DocumentClient(new Uri(endpointUrl), authorizationKey);
var sql = "SELECT c as employee FROM c IN Customer.employees WHERE c.firstName = 'xx'";
var collection = client.CreateDocumentCollectionIfNotExistsAsync(
            UriFactory.CreateDatabaseUri(databaseId), new DocumentCollection
            {
                Id = collectionId

            }).Result.Resource;
var query = client.CreateDocumentQuery(collection.SelfLink, sql).AsDocumentQuery();

while (query.HasMoreResults)
{
  var documents =  query.ExecuteNextAsync().Result;
  //do something
}


问:
Match JSON String to new POJO Object
I am using Spring RestTemplate to communicate with an provided REST service that delivers JSON. To Map the response I am using Jaxon, but I will gladly switch to anything else that works.

I would like to create an POJO that contains sub-content of the delivered data but in a different Structure.

It boils down to this:

Source: { "a": "val_a", "b" : {"c" : "val_c", "d": "val_d"}}

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
class Foo {
   // should contains the content of `"a": "val_a"`
   // but contains null
   private Baa;

   // getter and setter
}

@JsonIgnoreProperties(ignoreUnknown = true)
class Baa {
  private String a;

  // getter and setter
}

// This should be the operation that is done internally by Spring when calling
// ResponseEntity<Foo>response = restTemplate.exchange(url, HttpMethod.GET, entity, Foo.class);
// response.getBody();
private Foo read(String s) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    return mapper.readValue(s, Foo.class);
}
</code>```

The result of the deserialization is an empty Baa object. The actual JSON and POJO Object structure is more complex but this sums it up.

Any Technology that achieves this would be welcome.
The only possibility I came up with is deserializing the JSON in the provided structure and write a Converter class that generates the desired Object but I was hoping to avoid this.

----- Update/clarification ------
The problem is, that the property a should be mapped within class Baa, which lies within Foo but is provided in the root path (is this the right term?) of the provided JSON objekt

答:
If you don't want to write the java bean that rappresent the JSON structure, you have to use a different library. Jackson forces you to create a java structure that reflects the JSON structure. In my opinion Jackson works great and i suggest you to use it, but the alternative could be JSON library.

With this one you can select only the element you want from the json, and map it to the bean you want.

Little example:

```<code>JSONObject response =  new JSONObject("{\"a\": \"val_a\", \"b\" : {\"c\" : \"val_c\", \"d\": \"val_d\"}}");

JSONObject bObject =  response.getJSONObject("b");
String cElement = (String) elenco.get("c");
</code>```

The value of bObject is {"d":"val_d","c":"val_c"}, and the value of cElement is val_c

This libray uses JSONObject and JSONArray generic objects, to map the content of the json to a java object.

Title: Match JSON String to new POJO Object

Body:
I am using Spring RestTemplate to communicate with an provided REST service that delivers JSON. To Map the response I am using Jaxon, but I will gladly switch to anything else that works.

I would like to create an POJO that contains sub-content of the delivered data but in a different Structure.

It boils down to this:

Source: { "a": "val_a", "b" : {"c" : "val_c", "d": "val_d"}}

@JsonIgnoreProperties(ignoreUnknown = true)
class Foo {
   // should contains the content of `"a": "val_a"`
   // but contains null
   private Baa;

   // getter and setter
}

@JsonIgnoreProperties(ignoreUnknown = true)
class Baa {
  private String a;

  // getter and setter
}

// This should be the operation that is done internally by Spring when calling
// ResponseEntity<Foo>response = restTemplate.exchange(url, HttpMethod.GET, entity, Foo.class);
// response.getBody();
private Foo read(String s) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    return mapper.readValue(s, Foo.class);
}

The result of the deserialization is an empty Baa object. The actual JSON and POJO Object structure is more complex but this sums it up.

Any Technology that achieves this would be welcome.
The only possibility I came up with is deserializing the JSON in the provided structure and write a Converter class that generates the desired Object but I was hoping to avoid this.

----- Update/clarification ------
The problem is, that the property a should be mapped within class Baa, which lies within Foo but is provided in the root path (is this the right term?) of the provided JSON objekt

Body:
If you don't want to write the java bean that rappresent the JSON structure, you have to use a different library. Jackson forces you to create a java structure that reflects the JSON structure. In my opinion Jackson works great and i suggest you to use it, but the alternative could be JSON library.

With this one you can select only the element you want from the json, and map it to the bean you want.

Little example:

JSONObject response =  new JSONObject("{\"a\": \"val_a\", \"b\" : {\"c\" : \"val_c\", \"d\": \"val_d\"}}");

JSONObject bObject =  response.getJSONObject("b");
String cElement = (String) elenco.get("c");

The value of bObject is {"d":"val_d","c":"val_c"}, and the value of cElement is val_c

This libray uses JSONObject and JSONArray generic objects, to map the content of the json to a java object.


问:
create dtype array column in dataframe
How to create 'col new' in dataframe ?

```<code>          'col 1'   'col 2'   'col new'
0           a         b         [a, b]
1           c         d         [c, d]
2           e         f         [e, f]
</code>```

Thank in advance

答:
Here's one simpler way</p>

```<code>In [216]: df['col new'] = df[['col 1', 'col 2']].values.tolist()

In [217]: df
Out[217]:
  col 1 col 2 col new
0     a     b  [a, b]
1     c     d  [c, d]
2     e     f  [e, f]
</code>```

Title: create dtype array column in dataframe

Body:
How to create 'col new' in dataframe ?

          'col 1'   'col 2'   'col new'
0           a         b         [a, b]
1           c         d         [c, d]
2           e         f         [e, f]

Thank in advance

Body:
Here's one simpler way

In [216]: df['col new'] = df[['col 1', 'col 2']].values.tolist()

In [217]: df
Out[217]:
  col 1 col 2 col new
0     a     b  [a, b]
1     c     d  [c, d]
2     e     f  [e, f]