问:
Android SyncAdapter and concurrent write accesses
I am developing a RESTful Android app using SyncAdapter. I have watched some screencasts and read some tutorials, but they only address basic dynamics. Before starting to write the code, I would like to try and receive feedback from expert users about concurrency issues.

Step 1. The user U inserts a new entry E into the table T of the database. The entry has a column status = TO_SYNC.

Step 2. Before the entry E is synced, U decides to modify it. An activity A starts for modifying the column values of E.

Step 3. While the user is modifying the entry, the SyncAdapter starts and sends the entries with status == TO_SYNC to the server. For each entry, the SyncAdapter sets status = SYNCED once it receives a positive answer from the server.

Step 4. Let's say that a concurrent access to the same entry E causes a conflict:

The SyncAdapter reads E, sends E to the server

The activity A completes and sets E status to TO_SYNC

The SyncAdapter receives the ok from the server and sets the status of E to SYNCED

At this point the new values of E will not be synced since the value TO_SYNC has been overwritten by the SyncAdapter.

My question is: how can I avoid such issue without blocking the entire database with a begin/end transaction while syncing (which could take a long time to complete)? Should I fall back on a classical java lock on single entries? Is there a more elegant way?

答:
Another way, with second column "updated_at"

The SyncAdapter reads E, sends E to the server

The activity A completes and sets E status to TO_SYNC and updated_at at NOW

The SyncAdapter receives the ok from the server

The SyncAdapter reads E_bis, compare E.updated_at and E_bis.updated_at, if different => request new sync, else => sets the status of E to SYNCED


来源: stackexchange

问:
mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists
While starting mysql server 5.7.17 using mysqld_safe, following error occcours.

```<code>2017-02-10T17:05:44.870970Z mysqld_safe Logging to '/var/log/mysql/error.log'.
2017-02-10T17:05:44.872874Z mysqld_safe Logging to '/var/log/mysql/error.log'.
2017-02-10T17:05:44.874547Z mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists.
</code>```

How to fix it ?

答:
When I used the code mysqld_safe --skip-grant-tables & but I get the error:

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists.

```<code>$ systemctl stop  mysql.service
$ ps -eaf|grep mysql
$ mysqld_safe --skip-grant-tables &
</code>```

I solved:

```<code>$ mkdir -p /var/run/mysqld
$ chown mysql:mysql /var/run/mysqld
</code>```

Now I use the same code mysqld_safe --skip-grant-tables & and get

mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql

If I use $ mysql -u root I'll get :

Server version: 5.7.18-0ubuntu0.16.04.1 (Ubuntu)

Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

Now time to change password:

```<code>mysql> use mysql
mysql> describe user;
</code>```

Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed

```<code>mysql> FLUSH PRIVILEGES;
mysql> SET PASSWORD FOR root@'localhost' = PASSWORD('newpwd');
</code>```

or If you have a mysql root account that can connect from everywhere, you should also do:

```<code>UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';
</code>```

Alternate Method:

```<code>   USE mysql
   UPDATE user SET Password = PASSWORD('newpwd')
   WHERE Host = 'localhost' AND User = 'root';
</code>```

And if you have a root account that can access from everywhere:

```<code> USE mysql
 UPDATE user SET Password = PASSWORD('newpwd')
 WHERE Host = '%' AND User = 'root';`enter code here
</code>```

now need to quit from mysql and stop/start

```<code>FLUSH PRIVILEGES;
sudo /etc/init.d/mysql stop
sudo /etc/init.d/mysql start
</code>```

now again ` mysql -u root -p' and use the new password to get

mysql>

ContentLicense: CC BY-SA 3.0

Body:
While starting mysql server 5.7.17 using mysqld_safe, following error occcours.

2017-02-10T17:05:44.870970Z mysqld_safe Logging to '/var/log/mysql/error.log'.
2017-02-10T17:05:44.872874Z mysqld_safe Logging to '/var/log/mysql/error.log'.
2017-02-10T17:05:44.874547Z mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists.

How to fix it ?

Body:
When I used the code mysqld_safe --skip-grant-tables & but I get the error:

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists.

$ systemctl stop  mysql.service
$ ps -eaf|grep mysql
$ mysqld_safe --skip-grant-tables &

I solved:

$ mkdir -p /var/run/mysqld
$ chown mysql:mysql /var/run/mysqld

Now I use the same code mysqld_safe --skip-grant-tables & and get

mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql

If I use $ mysql -u root I'll get :

Server version: 5.7.18-0ubuntu0.16.04.1 (Ubuntu)

Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

Now time to change password:

mysql> use mysql
mysql> describe user;

Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed

mysql> FLUSH PRIVILEGES;
mysql> SET PASSWORD FOR root@'localhost' = PASSWORD('newpwd');

or If you have a mysql root account that can connect from everywhere, you should also do:

UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';

Alternate Method:

   USE mysql
   UPDATE user SET Password = PASSWORD('newpwd')
   WHERE Host = 'localhost' AND User = 'root';

And if you have a root account that can access from everywhere:

 USE mysql
 UPDATE user SET Password = PASSWORD('newpwd')
 WHERE Host = '%' AND User = 'root';`enter code here

now need to quit from mysql and stop/start

FLUSH PRIVILEGES;
sudo /etc/init.d/mysql stop
sudo /etc/init.d/mysql start

now again ` mysql -u root -p' and use the new password to get

mysql>


问:
How to use single object instance for class to set the multiple member value?
Curretly i am using below code to set the DateRanges Class member variables.

```<code>       DateRanges DateRanges1 = new DateRanges();
       DateRanges DateRanges2 = new DateRanges();
       DateRanges DateRanges3 = new DateRanges();

        DateRanges1.Label = "Last Week";
        DateRanges1.Range = Lastweek;
        this.dateRange.Ranges.Add(DateRanges1);
        DateRanges2.Label = "Last 1 Month";
        DateRanges2.Range = Lastmonth;
        this.dateRange.Ranges.Add(DateRanges2);
        DateRanges3.Label = "Last 2 Months";
        DateRanges3.Range = Last2month;
        this.dateRange.Ranges.Add(DateRanges3);
</code>```

I want to reduce the code in this. is there any way to do this.

Here DateRanges, class that have label(string type), ranges(object) members.
this.daterange.ranges is my custom component property.
Thanks for any help.

答:
To make this code cleaner, I'd suggest:

Renaming Lastmonth etc to follow .NET naming conventions

Not bothering with any separate variables (but if you do, make them follow .NET naming conventions too)

Renaming DateRanges to DateRange (as it only appears to be a single date range)

Creating a constructor for DateRange accepting the range and the label

You can then have:

```<code>dateRange.Ranges.Add(new DateRange(LastWeek, "Last Week"));
dateRange.Ranges.Add(new DateRange(LastMonth, "Last 1 Month"));
dateRange.Ranges.Add(new DateRange(Last2Months, "Last 2 Months"));
</code>```

Or possibly (depending on the type of Ranges):

```<code>// Here AddRange would be expected to accept IEnumerable<DateRange>
dateRange.Ranges.AddRange(new[] {
    new DateRange(LastWeek, "Last Week"),
    new DateRange(LastMonth, "Last 1 Month"),
    new DateRange(Last2Months, "Last 2 Months")
});
</code>```

Both of those are considerably cleaner IMO than using an object initializer and an unconventional local variable name.

If you're doing this around the same code you're initializing dateRanges, you could just use:

```<code>dateRanges = new FooBar // Whatever the type actually is
{
    // Other properties as well
    Ranges =
    {
        new DateRange(LastWeek, "Last Week"),
        new DateRange(LastMonth, "Last 1 Month"),
        new DateRange(Last2Months, "Last 2 Months")
    }
};
</code>```

Body:
Curretly i am using below code to set the DateRanges Class member variables.

       DateRanges DateRanges1 = new DateRanges();
       DateRanges DateRanges2 = new DateRanges();
       DateRanges DateRanges3 = new DateRanges();

        DateRanges1.Label = "Last Week";
        DateRanges1.Range = Lastweek;
        this.dateRange.Ranges.Add(DateRanges1);
        DateRanges2.Label = "Last 1 Month";
        DateRanges2.Range = Lastmonth;
        this.dateRange.Ranges.Add(DateRanges2);
        DateRanges3.Label = "Last 2 Months";
        DateRanges3.Range = Last2month;
        this.dateRange.Ranges.Add(DateRanges3);

I want to reduce the code in this. is there any way to do this.

Here DateRanges, class that have label(string type), ranges(object) members.
this.daterange.ranges is my custom component property.
Thanks for any help.

Body:
To make this code cleaner, I'd suggest:

Renaming Lastmonth etc to follow .NET naming conventions

Not bothering with any separate variables (but if you do, make them follow .NET naming conventions too)

Renaming DateRanges to DateRange (as it only appears to be a single date range)

Creating a constructor for DateRange accepting the range and the label

You can then have:

dateRange.Ranges.Add(new DateRange(LastWeek, "Last Week"));
dateRange.Ranges.Add(new DateRange(LastMonth, "Last 1 Month"));
dateRange.Ranges.Add(new DateRange(Last2Months, "Last 2 Months"));

Or possibly (depending on the type of Ranges):

// Here AddRange would be expected to accept IEnumerable<DateRange>
dateRange.Ranges.AddRange(new[] {
    new DateRange(LastWeek, "Last Week"),
    new DateRange(LastMonth, "Last 1 Month"),
    new DateRange(Last2Months, "Last 2 Months")
});

Both of those are considerably cleaner IMO than using an object initializer and an unconventional local variable name.

If you're doing this around the same code you're initializing dateRanges, you could just use:

dateRanges = new FooBar // Whatever the type actually is
{
    // Other properties as well
    Ranges =
    {
        new DateRange(LastWeek, "Last Week"),
        new DateRange(LastMonth, "Last 1 Month"),
        new DateRange(Last2Months, "Last 2 Months")
    }
};


问:
how can i run code that need a long time without the computer sleep or exit user?
I wrote a code in C ++ that requires a long run time (days-weeks)
But when I run it after a little while the computer goes to sleep or it leaves the user or the screen turns off
Is there a way that the program will continue to run? Function maybe?</p>

答:
On Windows you need to use SetThreadExecutionState.
From MSDN:

Enables an application to inform the system that it is in use, thereby preventing the system from entering sleep or turning off the display while the application is running.


问:
How to check if the inputted data exist in database
I would like to know if what am I lacking here, I can't compare the 'id' from the Textfield to the data from the database.

For example:

If TextField1 == to the data in the database.

Output: Swept by GSW.

```<code>Connection con = connect.getConnection();
        String query = "SELECT * FROM item_list WHERE id = ?";

        Statement st;
        ResultSet rs;
        int id;

        try{
            st = con.createStatement();
            rs = st.executeQuery(query);

            while(rs.next()){
              id = rs.getInt("id");

              if(Integer.parseInt(TF[0].getText()) == id){
                System.out.println(id);
                }
            }
        }catch(SQLException exc){
            System.out.println("Not Found!");
        }
</code>```

Kindly Check the Image Output.
I attached the image file below.

Sample Output

答:
First of all, you need to log a stack trace of an exception that is thrown. At least you can use exc.printStackTrace() in your catch section.

Second, your issue is that you declared a parameter for your SQL query, but you have not put any value to it.

```<code>    PreparedStatement p = con.prepareStatement("SELECT * FROM item_list WHERE id = ?");
    p.setString(1, TF[0].getText() ); //VALUE_FROM_YOUR_TEXT_INPUT
</code>```

You don't need to iterate over all result set to check if a user with such id exists. You can just check that result set is not empty.

Body:
I would like to know if what am I lacking here, I can't compare the 'id' from the Textfield to the data from the database.

For example:

If TextField1 == to the data in the database.

Output: Swept by GSW.

Connection con = connect.getConnection();
        String query = "SELECT * FROM item_list WHERE id = ?";

        Statement st;
        ResultSet rs;
        int id;

        try{
            st = con.createStatement();
            rs = st.executeQuery(query);

            while(rs.next()){
              id = rs.getInt("id");

              if(Integer.parseInt(TF[0].getText()) == id){
                System.out.println(id);
                }
            }
        }catch(SQLException exc){
            System.out.println("Not Found!");
        }

Kindly Check the Image Output.
I attached the image file below.

Sample Output

Body:
First of all, you need to log a stack trace of an exception that is thrown. At least you can use exc.printStackTrace() in your catch section.

Second, your issue is that you declared a parameter for your SQL query, but you have not put any value to it.

    PreparedStatement p = con.prepareStatement("SELECT * FROM item_list WHERE id = ?");
    p.setString(1, TF[0].getText() ); //VALUE_FROM_YOUR_TEXT_INPUT

You don't need to iterate over all result set to check if a user with such id exists. You can just check that result set is not empty.


问:
WP_Query orderby meta_key and id
I'm trying to make a wp_query get the last x posts order by a meta_value and ID. The prop_featured  value can be 1 or 0 . I want to get the list of post with the ones having prop_featured=1 as the first ones and then the others ordered by ID.
 Here is my arg array :

```<code>           $args = array(
            'post_type'         => $type,
            'post_status'       => 'publish',
            'paged'             => 0,
            'posts_per_page'    => 10,
            'meta_key'          => 'prop_featured',
            'orderby'           => 'meta_value ID',
            'order'             => 'DESC'

        );
</code>```

I also try using filters

```<code>         function my_order($orderby) {
         global $wpdb;
         $orderby = 'wp_postmeta.meta_value, wp_posts.ID DESC';
         return $orderby;
         }

   add_filter( 'posts_orderby', 'my_order' );
   $recent_posts = new WP_Query($args);
   remove_filter( 'posts_orderby', 'my_order' );
</code>```

答:
To my mind, the easiest solution is to replace your initial orderby by an array (and delete your order entry), like this:

```<code>$args = array(
    'post_type'      => $type,
    'post_status'    => 'publish',
    'paged'          => 0,
    'posts_per_page' => 10,
    'meta_key'       => 'prop_featured',
    'orderby'        => array( 'meta_value_num' => 'DESC', 'ID' => 'DESC' )
);
</code>```

Title: WP_Query orderby meta_key and id

Body:
I'm trying to make a wp_query get the last x posts order by a meta_value and ID. The prop_featured  value can be 1 or 0 . I want to get the list of post with the ones having prop_featured=1 as the first ones and then the others ordered by ID.
 Here is my arg array :

           $args = array(
            'post_type'         => $type,
            'post_status'       => 'publish',
            'paged'             => 0,
            'posts_per_page'    => 10,
            'meta_key'          => 'prop_featured',
            'orderby'           => 'meta_value ID',
            'order'             => 'DESC'

        );

I also try using filters

         function my_order($orderby) {
         global $wpdb;
         $orderby = 'wp_postmeta.meta_value, wp_posts.ID DESC';
         return $orderby;
         }

   add_filter( 'posts_orderby', 'my_order' );
   $recent_posts = new WP_Query($args);
   remove_filter( 'posts_orderby', 'my_order' );

Body:
To my mind, the easiest solution is to replace your initial orderby by an array (and delete your order entry), like this:

$args = array(
    'post_type'      => $type,
    'post_status'    => 'publish',
    'paged'          => 0,
    'posts_per_page' => 10,
    'meta_key'       => 'prop_featured',
    'orderby'        => array( 'meta_value_num' => 'DESC', 'ID' => 'DESC' )
);

ContentLicense: CC BY-SA 4.0


问:
Multiple observables one subscriber
I need to consume events from multiple sources. Amount of sources varies, a source may be dinamically added or removed.

As I want a possibility to change set of sources 'on the fly', without need to resubscribe, merge is not a case.

Have tried something like

```<code>PublishSubject<Integer> sourcesSubject = PublishSubject.create();

sourcesSubject.subscribe(...);

Observable<Integer> source1 = ...;
source1.subscribe(sourcesSubject); // add first source

Observable<Integer> source2 = ...;
source2.subscribe(sourcesSubject); // add second source

..... // How to remove a source?
</code>```

but have no idea how to remove a source.

Is there a simple solution?

答: I would suggest to look at combining operators like merge (and instance variant mergeWith) or concat (concatWith) which will remove the need to use Subject. When you unsubscribe all the sources will be stopped.

Title: Multiple observables one subscriber

Body:
I need to consume events from multiple sources. Amount of sources varies, a source may be dinamically added or removed.

As I want a possibility to change set of sources 'on the fly', without need to resubscribe, merge is not a case.

Have tried something like

PublishSubject<Integer> sourcesSubject = PublishSubject.create();

sourcesSubject.subscribe(...);

Observable<Integer> source1 = ...;
source1.subscribe(sourcesSubject); // add first source

Observable<Integer> source2 = ...;
source2.subscribe(sourcesSubject); // add second source

..... // How to remove a source?

but have no idea how to remove a source.

Is there a simple solution?


问:
Add particles on button click in unity
I am new to unity 3d, I have to do some enhancement in exiting project.. if user choose correct option then I have to show some particles around the button at runtime.
My code for adding particles is below ..not working:

```<code>ParticleSystem ps = GetComponent<ParticleSystem>();
ps.Play ();
</code>```

I have also added particles component from unity editor..

Thanks in advance

Edit :

as @kardux suggested:

declaration :

```<code>[SerializeField] private ParticleSystem ps;
</code>```

on method :

```<code>ps.Play()
</code>```

Screenshot from inspector:

Error:

```<code>I/Unity   (23313): NullReferenceException
I/Unity   (23313):   at UnityEngine.ParticleSystem.<Play>m__0 (UnityEngine.ParticleSystem ps) [0x00001] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3666
I/Unity   (23313):   at UnityEngine.ParticleSystem.IterateParticleSystems (Boolean recurse, UnityEngine.IteratorDelegate func) [0x00003] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3780
I/Unity   (23313):   at UnityEngine.ParticleSystem.Play (Boolean withChildren) [0x00020] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3666
I/Unity   (23313):   at UnityEngine.ParticleSystem.Play () [0x00005] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3661
</code>```

答:
Provided you have a particle system on the same gameObject as the script that is calling it, it should be fine.

Are you using a UI button? If so, have a look here..
http://answers.unity3d.com/questions/852397/particle-system-in-46-ui.html

It's old but still relevant.

Title: Add particles on button click in unity

Body:
I am new to unity 3d, I have to do some enhancement in exiting project.. if user choose correct option then I have to show some particles around the button at runtime.
My code for adding particles is below ..not working:

ParticleSystem ps = GetComponent<ParticleSystem>();
ps.Play ();

I have also added particles component from unity editor..

Thanks in advance

Edit :

as @kardux suggested:

declaration :

[SerializeField] private ParticleSystem ps;

on method :

ps.Play()

Screenshot from inspector:

Error:

I/Unity   (23313): NullReferenceException
I/Unity   (23313):   at UnityEngine.ParticleSystem.<Play>m__0 (UnityEngine.ParticleSystem ps) [0x00001] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3666
I/Unity   (23313):   at UnityEngine.ParticleSystem.IterateParticleSystems (Boolean recurse, UnityEngine.IteratorDelegate func) [0x00003] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3780
I/Unity   (23313):   at UnityEngine.ParticleSystem.Play (Boolean withChildren) [0x00020] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3666
I/Unity   (23313):   at UnityEngine.ParticleSystem.Play () [0x00005] in /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/ParticleSystem/ParticleSystemBindings.gen.cs:3661


问:
Vba code stops after workbook open. No errors
I have some code that is meant to open an xlsm workbook, copy some data from it and paste it in the workbook with the code. Both workbooks are password protected and the code is password protected. I have some code that is setup to run before save, open and close which locks the workbook.

So the problem is that the code stops with no errors after the workbook is opened by vba as seen below. I thought it has something to do with the shift key, a problem I have seen all over the net with the open method but I altered the code to fix that and the problem was still there. I then tried removing the code for the on open in the workbook being opened and it worked. Why is this? I have run code just like this before with workbooks that have code on open and it worked just fine.

I am using Excel 2013.

```<code>Sub User_Update()

Application.ScreenUpdating = False

Dim strCurrentProgram As String
Dim MainProgramName As String
Dim strLocation As String

strLocation = "X:\Produktionsmesstechnik\Gehaeuse_Freigabe\"
strCurrentProgram = Dir(strLocation & "*.xlsm")

Do While strCurrentProgram <> ""
    If InStr(strCurrentProgram, "Gehäuse Freigabe Program Ver") = 1 Then

        If MainProgramName = "" Then
            MainProgramName = strCurrentProgram
        ElseIf CInt(Mid(MainProgramName, 29, 3)) < CInt(Mid(strCurrentProgram, 29, 3)) Then
            MainProgramName = strCurrentProgram
        End If

    End If
    strCurrentProgram = Dir
Loop

Workbooks.Open Filename:=strLocation & MainProgramName <<<< CODE STOPS HERE

ActiveWorkbook.Sheets("Users").Range(Cells(4, 1), Cells(100, 11)).Copy
Call UserPassword_Unlock
ThisWorkbook.Sheets("Users").Range("A4").Paste
ThisWorkbook.Save
Workbooks(MainProgramName).Close
Call UserPassword_Lock
</code>```

End Sub

答:
I can see a couple of things wrong with your code aside from the code stopping.

The code may be stopping due to code in the other workbook firing when it opens, so that needs to be stopped.

The other problems I see are that you're not referencing the newly opened workbook with a variable, instead using ActiveWorkbook which may not always be correct.

The line where you're copy the range is using Users as the range reference, but the cell references are using the currently active sheet.

After your do loop I'd add this code:

```<code>Dim wrkBk As Workbook

Application.EnableEvents = False
Set wrkBk = Workbooks.Open(strLocation & MainProgramName)
Call UserPassword_Unlock
With wrkBk.Worksheets("Users")
    .Range(.Cells(4, 1), .Cells(100, 11)).Copy _
        Destination:=ThisWorkbook.Worksheets("Users").Range("A4")
End With
ThisWorkbook.Save
wrkBk.Close SaveChanges:=False
Call UserPassword_Lock
Application.EnableEvents = True
</code>```

Note I use wrkBk to reference the newly opened workbook.  The Copy and Paste are shortened to a single line with each cell and range reference fully qualified using With wrkbk.Worksheets("Users").

Application.EnableEvents = False should stop any code firing when the workbook is opened.

Body:
I have some code that is meant to open an xlsm workbook, copy some data from it and paste it in the workbook with the code. Both workbooks are password protected and the code is password protected. I have some code that is setup to run before save, open and close which locks the workbook.

So the problem is that the code stops with no errors after the workbook is opened by vba as seen below. I thought it has something to do with the shift key, a problem I have seen all over the net with the open method but I altered the code to fix that and the problem was still there. I then tried removing the code for the on open in the workbook being opened and it worked. Why is this? I have run code just like this before with workbooks that have code on open and it worked just fine.

I am using Excel 2013.

Sub User_Update()

Application.ScreenUpdating = False

Dim strCurrentProgram As String
Dim MainProgramName As String
Dim strLocation As String

strLocation = "X:\Produktionsmesstechnik\Gehaeuse_Freigabe\"
strCurrentProgram = Dir(strLocation & "*.xlsm")

Do While strCurrentProgram <> ""
    If InStr(strCurrentProgram, "Gehäuse Freigabe Program Ver") = 1 Then

        If MainProgramName = "" Then
            MainProgramName = strCurrentProgram
        ElseIf CInt(Mid(MainProgramName, 29, 3)) < CInt(Mid(strCurrentProgram, 29, 3)) Then
            MainProgramName = strCurrentProgram
        End If

    End If
    strCurrentProgram = Dir
Loop

Workbooks.Open Filename:=strLocation & MainProgramName <<<< CODE STOPS HERE

ActiveWorkbook.Sheets("Users").Range(Cells(4, 1), Cells(100, 11)).Copy
Call UserPassword_Unlock
ThisWorkbook.Sheets("Users").Range("A4").Paste
ThisWorkbook.Save
Workbooks(MainProgramName).Close
Call UserPassword_Lock

End Sub

Body:
I can see a couple of things wrong with your code aside from the code stopping.

The code may be stopping due to code in the other workbook firing when it opens, so that needs to be stopped.

The other problems I see are that you're not referencing the newly opened workbook with a variable, instead using ActiveWorkbook which may not always be correct.

The line where you're copy the range is using Users as the range reference, but the cell references are using the currently active sheet.

After your do loop I'd add this code:

Dim wrkBk As Workbook

Application.EnableEvents = False
Set wrkBk = Workbooks.Open(strLocation & MainProgramName)
Call UserPassword_Unlock
With wrkBk.Worksheets("Users")
    .Range(.Cells(4, 1), .Cells(100, 11)).Copy _
        Destination:=ThisWorkbook.Worksheets("Users").Range("A4")
End With
ThisWorkbook.Save
wrkBk.Close SaveChanges:=False
Call UserPassword_Lock
Application.EnableEvents = True

Note I use wrkBk to reference the newly opened workbook.  The Copy and Paste are shortened to a single line with each cell and range reference fully qualified using With wrkbk.Worksheets("Users").

Application.EnableEvents = False should stop any code firing when the workbook is opened.


问:
Xamarin project broken on update CardView package
My project was working fine untill I updated this package

Xamarin.Android.Support.v7.CardView

I'm a starter with Xamarin, so I hope anyone here can push me in the right direction.

Didn't work

Delete and reinstall

Downgrading the package

答: The problem was a bug in Xamarin. After a release of a new version everything worked fine. More explanation can be find here.</p>


问:
wordpress/woocommerce: Remove price if zero
I'm busy with a wordpress/woocommerce site and I'd like to hide the price of an item when it's zero on the product category/archive page.

I've tried looking on the web and in the php files but couldn't find where I should add the if statement.

My php knowledge is pretty limited. I was wondering if someone else has experience with this or could help me in the right way

Thanks!

答:
This one finally did it for me (using woocommerce 3.0.8):</p>

```<code>function cw_change_product_price_display( $price ) {
    $clear = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9 ]/', ' ', urldecode(html_entity_decode(strip_tags($price))))));
    if($clear == "0 00"){
      return '';
    }
    return $price;
  }
  add_filter( 'woocommerce_get_price_html', 'cw_change_product_price_display' );
  add_filter( 'woocommerce_cart_item_price', 'cw_change_product_price_display' );
</code>```

Body:
This one finally did it for me (using woocommerce 3.0.8):

function cw_change_product_price_display( $price ) {
    $clear = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9 ]/', ' ', urldecode(html_entity_decode(strip_tags($price))))));
    if($clear == "0 00"){
      return '';
    }
    return $price;
  }
  add_filter( 'woocommerce_get_price_html', 'cw_change_product_price_display' );
  add_filter( 'woocommerce_cart_item_price', 'cw_change_product_price_display' );


问:
JVM failure - fail over
I have read on high availability and scalability for J2EE apps. What I could not find is there any patterns on HA (resilience) that we can adopt to mitigate JVM failures.

Let me give an example.

A service is performing some business logic , writing or reading to/from DB and so on and there is a JVM crash. The reasons could be from pulling the power cord to kill the java process etc etc..

How do we do failover for the transactions that were the victims of such unexpected?

Thanks a lot for giving me the insight into your experience and approaches.

Regards
Sandeep

答: Take a look at HA-JDBC a <em>"JDBC proxy that provides light-weight, transparent, fault tolerant clustering capability to any underlying JDBC driver."</em>  It utilizes the group membership awareness capabilities of JGroups. </p>

ContentLicense: CC BY-SA 2.5

Title: JVM failure - fail over

Body: Take a look at HA-JDBC a "JDBC proxy that provides light-weight, transparent, fault tolerant clustering capability to any underlying JDBC driver."  It utilizes the group membership awareness capabilities of JGroups.


问:
Dispatch Redux action in React
I'm trying to fetch test API using FetchAPI and Redux.

The problem is with dispatch redux action.

Here's my code:

```<code>ProductList.js
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as productActions from '../actions/product';
import RaisedButton from 'material-ui/RaisedButton';

function fetchProductsWithRedux() {
    console.log("fetchProductsWithRedux-1");
    return (dispatch) => {
        console.log("fetchProductsWithRedux-2");
        dispatch(this.props.action.fetchProdutcsRequest());
        return fetchProdutcs().then(([response, json]) => {
            if (response.status === 200) {
                console.log("success");
                dispatch(this.props.action.fetchProductsSucesss(json))
            }
            else {
                console.log("error");
                dispatch(this.props.action.fetchProductsError())
            }
        })
    }
}

function fetchProdutcs() {
    const URL = "https://jsonplaceholder.typicode.com/posts";
    return fetch(URL, { method: 'GET' })
        .then(response => Promise.all([response, response.json()]));
}

class ProductList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            productList: [
                'product 1',
                'product 2',
                'product 3'
            ]
        }
    }
    componentDidMount() {
        fetchProductsWithRedux();
    }
    render() {
        return (
            <div className="ProductList">
                <h2>Products</h2>
                <ul>
                    {
                        this.props.posts &&
                        this.props.posts.map((post) => {
                            return (
                                <li>{post.title}</li>
                            )
                        })
                    }
                </ul>

                <ol>
                    <RaisedButton label="Get Products Action" onClick={this.props.action.getProducts} />
                </ol>
            </div>
        );
    }
}

function mapStateToProps(state, props) {
    return {
        product: state.product,
        posts: state.posts
    };
}
function mapDispatchToProps(dispatch) {
    return {
        action: bindActionCreators(productActions, dispatch)
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(ProductList);
</code>```

product.js (actions)

```<code>export function fetchProductsRequest() {
  console.log('fetchProductsRequest');
  return {
    type: 'FETCH_PRODUCTS_REQUEST'
  }
}

export function fetchProductsSuccess(payload) {
  console.log('fetchProductsSuccess');
  return {
    type: 'FETCH_PRODUCTS_SUCCESS'
  }
}

export function fetchProductsError() {
  console.log('fetchProductsError');
  return {
    type: 'FETCH_PRODUCTS_ERROR'
  }
}
</code>```

product.js (reducer)

```<code>export default(state = [], payload) => {
    switch (payload.type) {
        case 'FETCH_PRODUCTS_REQUEST':
            console.log('FETCH_PRODUCTS_REQUEST action');
            return state;
        case 'FETCH_PRODUCTS_SUCCESS':
            console.log('FETCH_PRODUCTS_SUCCES action');
            return {...state, posts: payload.payload}
        default:
            return state;
    }
};
</code>```

store.js

```<code>import { createStore } from 'redux';
import rootReducer from './reducers';

export default(initialState) => {
    return createStore(rootReducer, initialState);
}

Product.js (pages, component)
import React, { Component } from 'react';
import ProductList from '../../components/ProductList';
import RaisedButton from 'material-ui/RaisedButton';
//import './Product.css';

class Product extends Component {
    render() {
        return (
            <div className="Product">
                <h1>ProductList Page</h1>
                <RaisedButton label="Default" />
                <ProductList />
            </div>
        );
    }
}
export default Product;
</code>```

The line console.log("fetchProductsWithRedux-2"); in ProductList.js has never been reached.

What's wrong? Any ideas? Thanks in advance.

答: seem you missed import thunk from 'redux-thunk'. You can't return a function in redux action if you dont use any middleware like 'redux-thunk'</p>

Title: Dispatch Redux action in React

Body:
I'm trying to fetch test API using FetchAPI and Redux.

The problem is with dispatch redux action.

Here's my code:

ProductList.js
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as productActions from '../actions/product';
import RaisedButton from 'material-ui/RaisedButton';

function fetchProductsWithRedux() {
    console.log("fetchProductsWithRedux-1");
    return (dispatch) => {
        console.log("fetchProductsWithRedux-2");
        dispatch(this.props.action.fetchProdutcsRequest());
        return fetchProdutcs().then(([response, json]) => {
            if (response.status === 200) {
                console.log("success");
                dispatch(this.props.action.fetchProductsSucesss(json))
            }
            else {
                console.log("error");
                dispatch(this.props.action.fetchProductsError())
            }
        })
    }
}

function fetchProdutcs() {
    const URL = "https://jsonplaceholder.typicode.com/posts";
    return fetch(URL, { method: 'GET' })
        .then(response => Promise.all([response, response.json()]));
}

class ProductList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            productList: [
                'product 1',
                'product 2',
                'product 3'
            ]
        }
    }
    componentDidMount() {
        fetchProductsWithRedux();
    }
    render() {
        return (

Products

                    {
                        this.props.posts &&
                        this.props.posts.map((post) => {
                            return (

{post.title}

                            )
                        })
                    }

                    <RaisedButton label="Get Products Action" onClick={this.props.action.getProducts} />

        );
    }
}

function mapStateToProps(state, props) {
    return {
        product: state.product,
        posts: state.posts
    };
}
function mapDispatchToProps(dispatch) {
    return {
        action: bindActionCreators(productActions, dispatch)
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(ProductList);

product.js (actions)

export function fetchProductsRequest() {
  console.log('fetchProductsRequest');
  return {
    type: 'FETCH_PRODUCTS_REQUEST'
  }
}

export function fetchProductsSuccess(payload) {
  console.log('fetchProductsSuccess');
  return {
    type: 'FETCH_PRODUCTS_SUCCESS'
  }
}

export function fetchProductsError() {
  console.log('fetchProductsError');
  return {
    type: 'FETCH_PRODUCTS_ERROR'
  }
}

product.js (reducer)

export default(state = [], payload) => {
    switch (payload.type) {
        case 'FETCH_PRODUCTS_REQUEST':
            console.log('FETCH_PRODUCTS_REQUEST action');
            return state;
        case 'FETCH_PRODUCTS_SUCCESS':
            console.log('FETCH_PRODUCTS_SUCCES action');
            return {...state, posts: payload.payload}
        default:
            return state;
    }
};

store.js

import { createStore } from 'redux';
import rootReducer from './reducers';

export default(initialState) => {
    return createStore(rootReducer, initialState);
}

Product.js (pages, component)
import React, { Component } from 'react';
import ProductList from '../../components/ProductList';
import RaisedButton from 'material-ui/RaisedButton';
//import './Product.css';

class Product extends Component {
    render() {
        return (

ProductList Page

                <RaisedButton label="Default" />
                <ProductList />

        );
    }
}
export default Product;

The line console.log("fetchProductsWithRedux-2"); in ProductList.js has never been reached.

What's wrong? Any ideas? Thanks in advance.


问:
Android Firebase phone authentication INVALID_APP_CREDENTIAL:App validation failed
I am really new to android firebase and I have implemented the necessary libraries for Firebase Auth. I try putting a valid number, but the log says its:

```<code>W/JEJE: onVerificationFailed
com.google.firebase.FirebaseException: An internal error has occurred. [ INVALID_APP_CREDENTIAL:App validation failed ]
at com.google.android.gms.internal.nf.zzK(Unknown Source)
at com.google.android.gms.internal.og.zza(Unknown Source)
at com.google.android.gms.internal.oh.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6176)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
</code>```

Here is my code:

```<code>public class MainActivity extends AppCompatActivity {

    private static String mVerificationId;
    private static PhoneAuthProvider.ForceResendingToken mResendToken;
    private static FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText editText = (EditText) findViewById(R.id.phone);
        Button submit = (Button) findViewById(R.id.submit);

        final PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallBacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
            @Override
            public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
                Log.d("JEJE", "onVerificationCompleted:" + phoneAuthCredential);

                signInWithPhoneAuthCredential(phoneAuthCredential);
            }

            @Override
            public void onVerificationFailed(FirebaseException e) {
                Log.w("JEJE", "onVerificationFailed", e);

                if (e instanceof FirebaseAuthInvalidCredentialsException) {
                    Log.d("JEJE", "INVALID REQUEST");
                } else if (e instanceof FirebaseTooManyRequestsException) {
                    Log.d("JEJE", "Too many Request");
                }
            }

            @Override
            public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
                super.onCodeSent(s, forceResendingToken);
                Log.d("JEJE", "onCodeSent:" + s);

                mVerificationId = s;
                mResendToken = forceResendingToken;

            }
        };

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phoneNum = editText.getText().toString();
                Toast.makeText(MainActivity.this, phoneNum, Toast.LENGTH_SHORT).show();
                verifyPhone(phoneNum,mCallBacks);
            }

        });
    }

    private void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
        mAuth.signInWithCredential(phoneAuthCredential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()){
                    FirebaseUser user = task.getResult().getUser();
                }else {
                    if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                        // The verification code entered was invalid
                    }
                }
            }
        });
    }

    public void verifyPhone(String phoneNumber, PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks){
        PhoneAuthProvider.getInstance().verifyPhoneNumber(
                "+639952874699",        // Phone number to verify
                60,                 // Timeout duration
                TimeUnit.SECONDS,   // Unit of timeout
                this,               // Activity (for callback binding)
                mCallbacks);        // OnVerificationStateChangedCallback
    }

}
</code>```

please tell me whats wrong thanks..

答: Try upgrading your firebase-tools lib to the latest version, then call firebase logout followed by firebase login.</p>

Body:
I am really new to android firebase and I have implemented the necessary libraries for Firebase Auth. I try putting a valid number, but the log says its:

W/JEJE: onVerificationFailed
com.google.firebase.FirebaseException: An internal error has occurred. [ INVALID_APP_CREDENTIAL:App validation failed ]
at com.google.android.gms.internal.nf.zzK(Unknown Source)
at com.google.android.gms.internal.og.zza(Unknown Source)
at com.google.android.gms.internal.oh.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6176)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)

Here is my code:

public class MainActivity extends AppCompatActivity {

    private static String mVerificationId;
    private static PhoneAuthProvider.ForceResendingToken mResendToken;
    private static FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText editText = (EditText) findViewById(R.id.phone);
        Button submit = (Button) findViewById(R.id.submit);

        final PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallBacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
            @Override
            public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
                Log.d("JEJE", "onVerificationCompleted:" + phoneAuthCredential);

                signInWithPhoneAuthCredential(phoneAuthCredential);
            }

            @Override
            public void onVerificationFailed(FirebaseException e) {
                Log.w("JEJE", "onVerificationFailed", e);

                if (e instanceof FirebaseAuthInvalidCredentialsException) {
                    Log.d("JEJE", "INVALID REQUEST");
                } else if (e instanceof FirebaseTooManyRequestsException) {
                    Log.d("JEJE", "Too many Request");
                }
            }

            @Override
            public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
                super.onCodeSent(s, forceResendingToken);
                Log.d("JEJE", "onCodeSent:" + s);

                mVerificationId = s;
                mResendToken = forceResendingToken;

            }
        };

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phoneNum = editText.getText().toString();
                Toast.makeText(MainActivity.this, phoneNum, Toast.LENGTH_SHORT).show();
                verifyPhone(phoneNum,mCallBacks);
            }

        });
    }

    private void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
        mAuth.signInWithCredential(phoneAuthCredential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()){
                    FirebaseUser user = task.getResult().getUser();
                }else {
                    if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                        // The verification code entered was invalid
                    }
                }
            }
        });
    }

    public void verifyPhone(String phoneNumber, PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks){
        PhoneAuthProvider.getInstance().verifyPhoneNumber(
                "+639952874699",        // Phone number to verify
                60,                 // Timeout duration
                TimeUnit.SECONDS,   // Unit of timeout
                this,               // Activity (for callback binding)
                mCallbacks);        // OnVerificationStateChangedCallback
    }

}

please tell me whats wrong thanks..


问:
Invert some values in SQL Server
I have a table like this one:

```<code>ID   |   Description  |  Account  |  DepAccount  |  Value
----------------------------------------------------------
0    |  Something     | 110       | 0            | 500,50
1    |  Something x   | 0         | 110          | -320,95
</code>```

Now I need a query to sum the values but there is an issue with it.

Like in the example, if the account is 110, it is fine, if the DepAccount is 110, I need to invert the value so I sum 320,95 instead of -320,95

So the query should return value: 821,45

So something like:

```<code>SELECT SUM(Value) As Total
FROM Table
WHERE Account = 110 OR DepAccount = 110 WHERE etc...
</code>```

Who can help? I'm using SQL Server 2008 Express Edition

答:
Assuming  one of Account and DepAccount  is always 0, you can write</p>

```<code>SELECT
CASE
 WHEN DepAccount = 0 THEN Account
 WHEN Account = 0  THEN DepAccount
END AS acct,
SUM(abs(Value)) AS Total
FROM Table
GROUP BY
 CASE
 WHEN DepAccount = 0 THEN Account
 WHEN Account = 0  THEN DepAccount
END
</code>```

Title: Invert some values in SQL Server

Body:
I have a table like this one:

ID   |   Description  |  Account  |  DepAccount  |  Value
----------------------------------------------------------
0    |  Something     | 110       | 0            | 500,50
1    |  Something x   | 0         | 110          | -320,95

Now I need a query to sum the values but there is an issue with it.

Like in the example, if the account is 110, it is fine, if the DepAccount is 110, I need to invert the value so I sum 320,95 instead of -320,95

So the query should return value: 821,45

So something like:

SELECT SUM(Value) As Total
FROM Table
WHERE Account = 110 OR DepAccount = 110 WHERE etc...

Who can help? I'm using SQL Server 2008 Express Edition

Body:
Assuming  one of Account and DepAccount  is always 0, you can write

SELECT
CASE
 WHEN DepAccount = 0 THEN Account
 WHEN Account = 0  THEN DepAccount
END AS acct,
SUM(abs(Value)) AS Total
FROM Table
GROUP BY
 CASE
 WHEN DepAccount = 0 THEN Account
 WHEN Account = 0  THEN DepAccount
END


问:
Spring Cloud Stream: how to pass deployment properties to specific applications when they have identical names
Simple example from app starters:

```<code>stream create --name fileTofile --definition 'file --file.directory=./input | file --file.directory=./output'
</code>```

Next, when deploying the stream I would like to override "file.directory" property for one of the apps. How do I distinguish between the apps with the same name, when passing a deployment property?

答:
You need to use label for the app when creating the stream in the DSL. and refer the label when specifying the deployment properties.

In your case,

stream create --name fileTofile --definition 'source-file:file --file.directory=./input | sink-file:file --file.directory=./output'

You can refer the doc for it here

Body:
Simple example from app starters:

stream create --name fileTofile --definition 'file --file.directory=./input | file --file.directory=./output'

Next, when deploying the stream I would like to override "file.directory" property for one of the apps. How do I distinguish between the apps with the same name, when passing a deployment property?


问:
Convert date/time into timestamp
I want to convert following date and time, into a timestamp 13 digits. Note I use strict mode.

Date:

Thu Jun 01 2017 00:00:00 GMT+0200 (CEST)

Time:
03:00

I tried to use Date.parse() but it was not working. What is the best way to do this?

Title: Convert date/time into timestamp

Body: console.log(+new Date("Thu Jun 01 2017 00:00:00 GMT+0200 (CEST)"))


问:
How to use Vectors in Xcode 8
I'm looking for solution of problem that I get image from my server and that image will be only be one(not for compatible all devices) and that image will also use in android device too so as you know android support SVG but iOS isn't (that 1 image should be use on all iOS devices even on iPad too). I look into this Tutorial and this use from PDF and also use local pdf.

So what will be approach from iOS end or server end to download 1 image (with one size) and will be show on all devices.

Looking for suggestions and help to resolve this issue.

答:
You can try to implement PocketSVG (https://github.com/pocketsvg/PocketSVG) to do that.

There is one downfall though: it only supports SVG features that can be drawn using CGPaths or UIPaths.

Title: How to use Vectors in Xcode 8


问:
Adding camera profile correction to dng_validate.exe [Adobe DNG SDK]
Using Lightroom I know how to apply a camera profile (*.dcp file) to my *.DNG image.

I would like to do the same in an application which I'm writing, so I guess a good starting point would be to append this functionality to the dng_validate.exe application.

So I started to add:

```<code>#include "dng_camera_profile.h"
</code>```

Then added:

```<code>static dng_string gDumpDCP;
</code>```

And add the following to the error print:

```<code>"-dcp <file>   Load camera profile from <file>.dcp\"\n"
</code>```

Then I added the function to read the dcp from cli:

```<code>else if (option.Matches("dcp", true))
{
   gDumpDCP.Clear();
   if (index + 1 < argc)
   {
      gDumpDCP.Set(argv[++index]);
   }

   if (gDumpDCP.IsEmpty() || gDumpDCP.StartsWith("-"))
   {
      fprintf(stderr, "*** Missing file name after -dcp\n");
      return 1;
   }

   if (!gDumpDCP.EndsWith(".dcp"))
   {
      gDumpDCP.Append(".dcp");
   }

}
</code>```

Then I load the profile from disk [line 421]:

```<code>if (gDumpTIF.NotEmpty ())
{
   dng_camera_profile profile;
   if (gDumpDCP.NotEmpty())
   {
      dng_file_stream inStream(gDumpDCP.Get());
      profile.ParseExtended(inStream);
   }
   // Render final image.
   .... rest of code as it was
</code>```

So how do I now use the profile data to correct the render and write the corrected image?

答:
So after playing around for a couple of days, I now found the solution. Actually the negative can have multiple camera profiles. So with negative->AddProfile(profile) you just add one. But this won't be used if it's not the first profile! So we first need to clean the profiles and than add one.

```<code>AutoPtr<dng_camera_profile> profile(new dng_camera_profile);
if (gDumpDCP.NotEmpty())
{
    negative->ClearProfiles();
    dng_file_stream inStream(gDumpDCP.Get());
    profile->ParseExtended(inStream);

    profile->SetWasReadFromDNG();
    negative->AddProfile(profile);

    printf("Profile count: \"%d\"\n", negative->ProfileCount()); // will be 1 now!
}
</code>```

Next thing to get the image correctly is to have correct white balance. This can be done in camera or afterwards. For my application with 4 different cameras, the result was the best when using afterward white balance correction. So I found 4 (Temperature,Tint) pairs using Lightroom.

The question was how to add these values in the dng_validate.exe program. I did it like this:

#include "dng_temperature.h"

```<code>if (gTemp != NULL && gTint != NULL)
{
    dng_temperature temperature(gTemp, gTint);
    render.SetWhiteXY(temperature.Get_xy_coord());
}
</code>```

The resulting images are slightly different from the Lightroom result, but close enough. Also the camera to camera differences are gone now! :)

Body:
Using Lightroom I know how to apply a camera profile (*.dcp file) to my *.DNG image.

I would like to do the same in an application which I'm writing, so I guess a good starting point would be to append this functionality to the dng_validate.exe application.

So I started to add:

#include "dng_camera_profile.h"

Then added:

static dng_string gDumpDCP;

And add the following to the error print:

"-dcp <file>   Load camera profile from <file>.dcp\"\n"

Then I added the function to read the dcp from cli:

else if (option.Matches("dcp", true))
{
   gDumpDCP.Clear();
   if (index + 1 < argc)
   {
      gDumpDCP.Set(argv[++index]);
   }

   if (gDumpDCP.IsEmpty() || gDumpDCP.StartsWith("-"))
   {
      fprintf(stderr, "*** Missing file name after -dcp\n");
      return 1;
   }

   if (!gDumpDCP.EndsWith(".dcp"))
   {
      gDumpDCP.Append(".dcp");
   }

}

Then I load the profile from disk [line 421]:

if (gDumpTIF.NotEmpty ())
{
   dng_camera_profile profile;
   if (gDumpDCP.NotEmpty())
   {
      dng_file_stream inStream(gDumpDCP.Get());
      profile.ParseExtended(inStream);
   }
   // Render final image.
   .... rest of code as it was

So how do I now use the profile data to correct the render and write the corrected image?

Body:
So after playing around for a couple of days, I now found the solution. Actually the negative can have multiple camera profiles. So with negative->AddProfile(profile) you just add one. But this won't be used if it's not the first profile! So we first need to clean the profiles and than add one.

AutoPtr<dng_camera_profile> profile(new dng_camera_profile);
if (gDumpDCP.NotEmpty())
{
    negative->ClearProfiles();
    dng_file_stream inStream(gDumpDCP.Get());
    profile->ParseExtended(inStream);

    profile->SetWasReadFromDNG();
    negative->AddProfile(profile);

    printf("Profile count: \"%d\"\n", negative->ProfileCount()); // will be 1 now!
}

Next thing to get the image correctly is to have correct white balance. This can be done in camera or afterwards. For my application with 4 different cameras, the result was the best when using afterward white balance correction. So I found 4 (Temperature,Tint) pairs using Lightroom.

The question was how to add these values in the dng_validate.exe program. I did it like this:

#include "dng_temperature.h"

if (gTemp != NULL && gTint != NULL)
{
    dng_temperature temperature(gTemp, gTint);
    render.SetWhiteXY(temperature.Get_xy_coord());
}

The resulting images are slightly different from the Lightroom result, but close enough. Also the camera to camera differences are gone now! :)


问:
why char like "$" "\" are not bash shell metacharacter
While reading the Bash Reference Manual I noticed in the Definitions:

metacharacter

A character that, when unquoted, separates words. A metacharacter is a space, tab, newline, or one of the following characters: ‘|’, ‘&’, ‘;’, ‘(’, ‘)’, ‘<’, or ‘>’.

but chars like $, \ and others have all a special meaning. Why aren't they  listed as metacharacters?

答:
You posted the answer in the question (as part of the text you quoted from the documentation).

A metacharacter is:

A character that, when unquoted, separates words.

Neither $, nor \ are used to separate words. When not quoted, both of them are kept together with the character(s) that follow(s) them.

$ is the sigil of a variable.

\ is used as escape character.


问:
How can I make a checkbox readonly? not disabled?
I have a form where I have to post form values to my action class. In this form I have a checkbox that needs to be readonly. I tried setting disabled="true" but that doesn't work when posting to the action class.

So please advice??

答:
Make a fake checkbox with no name and value, force the value in an hidden field:

```<code><input type="checkbox" disabled="disabled" checked="checked">
<input type="hidden" name="name" value="true">
</code>```

Note: if you put name and value in the checkbox, it will be anyway overwritten by the input with the same name

Body:
Make a fake checkbox with no name and value, force the value in an hidden field:

<input type="checkbox" disabled="disabled" checked="checked">
<input type="hidden" name="name" value="true">

Note: if you put name and value in the checkbox, it will be anyway overwritten by the input with the same name


问:
How to access icons from icons8.com in web application?
I want to use icons from icons8.com website. How can I access the icons in my web application from icons8.com?</p>

答:
Click on an icon and either download it using the Download button or press Generate HTML to get the HTML, and then put that in your code.

There's a dropdown to the left also to change the size and format. In addition down the right hand side of the page there are a load of buttons to change the colour and/or style of the icon.


问:
SQL Server substring w/o custom functions
I have a dilemma regarding how to extract a sub string from a larger string without using custom functions
The string is of this form:

```<code>"    [1].[2]"
"        [1].[2].[3]"
"            [1].[2].[3].[4]"
</code>```

Basically, it's a hierarchy that has 4 leading spaces for every child of a node. The task is to maintain those 4 leading spaces for every node, but get only the child in the end, without the full path

So, the final result should be something like this:

```<code>"    [2]"
"        [3]"
"            [4]"
</code>```

Could anyone help me?

Edit: or, if it's the case, should I modify the CTE that is building the result set?

The CTE is like the one below:

```<code>WITH Hierarchy(cid, cname, parent_id, Parents, nname)
AS
(
    SELECT map_id, name, parent_id, CAST('' AS VARCHAR(MAX)), CAST(''+name AS VARCHAR(MAX))
        FROM tblMapping AS tm1
        WHERE parent_id = 0
    UNION ALL
    SELECT tm.map_id, tm.name, Parent.cid,
    CAST(CASE WHEN Parent.Parents = ''
        THEN(CAST(tm.parent_id AS VARCHAR(MAX)))
        ELSE(Parent.Parents + '.' + CAST(tm.parent_id AS VARCHAR(MAX)))
    END AS VARCHAR(MAX)),
    -- add the formated column description
    CAST(CASE WHEN Parent.Parents = ''
        THEN(Parent.cname)
        ELSE('    '+Parent.nname+ '.'+tm.name)
    END AS VARCHAR(MAX))
        FROM tblMapping AS tm
        INNER JOIN Hierarchy AS Parent ON tm.parent_id = Parent.cid
)
SELECT *
    FROM Hierarchy
ORDER BY ltrim(nname)
OPTION(MAXRECURSION 32767)
</code>```

Thank you!

答:
I would concatenate the spaces part with the last index.
Something like

```<code>Select left(your_string, char_index(your_string, "[") - 1) +
       right(your_string, 3) from your_table
</code>```

The 3 is assuming there's always one digit. If not, this is a bit complex because no last index of in SQLServer:

```<code> Select left(your_string, char_index(your_string, "[") - 1) +
        reverse(left(reverse(your_string), char_index(reverse(your_string), "[")))
        from your_table
</code>```

Body:
I have a dilemma regarding how to extract a sub string from a larger string without using custom functions
The string is of this form:

"    [1].[2]"
"        [1].[2].[3]"
"            [1].[2].[3].[4]"

Basically, it's a hierarchy that has 4 leading spaces for every child of a node. The task is to maintain those 4 leading spaces for every node, but get only the child in the end, without the full path

So, the final result should be something like this:

"    [2]"
"        [3]"
"            [4]"

Could anyone help me?

Edit: or, if it's the case, should I modify the CTE that is building the result set?

The CTE is like the one below:

WITH Hierarchy(cid, cname, parent_id, Parents, nname)
AS
(
    SELECT map_id, name, parent_id, CAST('' AS VARCHAR(MAX)), CAST(''+name AS VARCHAR(MAX))
        FROM tblMapping AS tm1
        WHERE parent_id = 0
    UNION ALL
    SELECT tm.map_id, tm.name, Parent.cid,
    CAST(CASE WHEN Parent.Parents = ''
        THEN(CAST(tm.parent_id AS VARCHAR(MAX)))
        ELSE(Parent.Parents + '.' + CAST(tm.parent_id AS VARCHAR(MAX)))
    END AS VARCHAR(MAX)),
    -- add the formated column description
    CAST(CASE WHEN Parent.Parents = ''
        THEN(Parent.cname)
        ELSE('    '+Parent.nname+ '.'+tm.name)
    END AS VARCHAR(MAX))
        FROM tblMapping AS tm
        INNER JOIN Hierarchy AS Parent ON tm.parent_id = Parent.cid
)
SELECT *
    FROM Hierarchy
ORDER BY ltrim(nname)
OPTION(MAXRECURSION 32767)

Thank you!

Body:
I would concatenate the spaces part with the last index.
Something like

Select left(your_string, char_index(your_string, "[") - 1) +
       right(your_string, 3) from your_table

The 3 is assuming there's always one digit. If not, this is a bit complex because no last index of in SQLServer:

 Select left(your_string, char_index(your_string, "[") - 1) +
        reverse(left(reverse(your_string), char_index(reverse(your_string), "[")))
        from your_table


问:
Python Pandas Dataframe cell value split
I am lost on how to split the binary values such that each (0,1)value takes up a column of the data frame.
from jupyter</p>

答:
You can use concat with apply list:

```<code>df = pd.DataFrame({0:[1,2,3], 1:['1010','1100','0101']})
print (df)
   0     1
0  1  1010
1  2  1100
2  3  0101

df = pd.concat([df[0],
                df[1].apply(lambda x: pd.Series(list(x))).astype(int)],
                axis=1, ignore_index=True)
print (df)

   0  1  2  3  4
0  1  1  0  1  0
1  2  1  1  0  0
2  3  0  1  0  1
</code>```

Another solution with DataFrame constructor:

```<code>df = pd.concat([df[0],
                pd.DataFrame(df[1].apply(list).values.tolist()).astype(int)],
                axis=1, ignore_index=True)
print (df)

   0  1  2  3  4
0  1  1  0  1  0
1  2  1  1  0  0
2  3  0  1  0  1
</code>```

EDIT:

```<code>df = pd.DataFrame({0:['1010','1100','0101']})

df1 = pd.DataFrame(df[0].apply(list).values.tolist()).astype(int)
print (df1)
   0  1  2  3
0  1  0  1  0
1  1  1  0  0
2  0  1  0  1
</code>```

But if need lists:

```<code>df[0] = df[0].apply(lambda x: [int(y) for y in list(x)])
print (df)
              0
0  [1, 0, 1, 0]
1  [1, 1, 0, 0]
2  [0, 1, 0, 1]
</code>```

Body:
You can use concat with apply list:

df = pd.DataFrame({0:[1,2,3], 1:['1010','1100','0101']})
print (df)
   0     1
0  1  1010
1  2  1100
2  3  0101

df = pd.concat([df[0],
                df[1].apply(lambda x: pd.Series(list(x))).astype(int)],
                axis=1, ignore_index=True)
print (df)

   0  1  2  3  4
0  1  1  0  1  0
1  2  1  1  0  0
2  3  0  1  0  1

Another solution with DataFrame constructor:

df = pd.concat([df[0],
                pd.DataFrame(df[1].apply(list).values.tolist()).astype(int)],
                axis=1, ignore_index=True)
print (df)

   0  1  2  3  4
0  1  1  0  1  0
1  2  1  1  0  0
2  3  0  1  0  1

EDIT:

df = pd.DataFrame({0:['1010','1100','0101']})

df1 = pd.DataFrame(df[0].apply(list).values.tolist()).astype(int)
print (df1)
   0  1  2  3
0  1  0  1  0
1  1  1  0  0
2  0  1  0  1

But if need lists:

df[0] = df[0].apply(lambda x: [int(y) for y in list(x)])
print (df)
              0
0  [1, 0, 1, 0]
1  [1, 1, 0, 0]
2  [0, 1, 0, 1]


问:
cell to matrix matching / map / cellOperations (MATLAB)
I cannot find the string equivalent of the finalAnswer using the data below.  Please, I cannot use if/for loops!  A final answer is preferred with each element as an array (i.e. the format of mainData)</p>

```<code>mainData = {'IBM' [201] [1] ;
            'GE' [403] [1] ;
            'MSFT' [502] [3] ;
            'GM' [101] [2]       } ;

finalAns = [ 101 2 0.5; 403 1 0.6 ]                  ;

%% I tried doing this ->
temp = cell2mat(mainData(:,[2 3])) ;

tf = ismember(temp, finalAns(:,[1 2],'rows') ;
secIDs = mainData(tf) ;
</code>```

答:
In order to get the entries in each row of mainData that match those in finalAns (based on the last two columns of mainData and the first two columns of finalAns) and to get them in the same order that they appear in finalAns and with the last column of finalAns appended, you can do this:

```<code>>> temp = cell2mat(mainData(:,2:3));
>> [isThere,index] = ismember(finalAns(:,1:2),temp,'rows');
>> output = [mainData(index(isThere),:) num2cell(finalAns(isThere,3))]

output =

    'GM'    [101]    [2]    [0.5000]
    'GE'    [403]    [1]    [0.6000]
</code>```

The output is a 2-by-4 cell array with each value in a separate cell. If you want the last three columns to be collected in a vector, you can replace the calculation of output above with this:

```<code>>> temp = [temp(index(isThere),:) finalAns(isThere,3)];
>> output = [mainData(index(isThere),1) num2cell(temp,2)]

output =

    'GM'    [1x3 double]
    'GE'    [1x3 double]
</code>```

Note that now you have a 2-by-2 cell array where cells in the second column contain 1-by-3 double arrays.

Body:
I cannot find the string equivalent of the finalAnswer using the data below.  Please, I cannot use if/for loops!  A final answer is preferred with each element as an array (i.e. the format of mainData)

mainData = {'IBM' [201] [1] ;
            'GE' [403] [1] ;
            'MSFT' [502] [3] ;
            'GM' [101] [2]       } ;

finalAns = [ 101 2 0.5; 403 1 0.6 ]                  ;

%% I tried doing this ->
temp = cell2mat(mainData(:,[2 3])) ;

tf = ismember(temp, finalAns(:,[1 2],'rows') ;
secIDs = mainData(tf) ;

Body:
In order to get the entries in each row of mainData that match those in finalAns (based on the last two columns of mainData and the first two columns of finalAns) and to get them in the same order that they appear in finalAns and with the last column of finalAns appended, you can do this:

>> temp = cell2mat(mainData(:,2:3));
>> [isThere,index] = ismember(finalAns(:,1:2),temp,'rows');
>> output = [mainData(index(isThere),:) num2cell(finalAns(isThere,3))]

output =

    'GM'    [101]    [2]    [0.5000]
    'GE'    [403]    [1]    [0.6000]

The output is a 2-by-4 cell array with each value in a separate cell. If you want the last three columns to be collected in a vector, you can replace the calculation of output above with this:

>> temp = [temp(index(isThere),:) finalAns(isThere,3)];
>> output = [mainData(index(isThere),1) num2cell(temp,2)]

output =

    'GM'    [1x3 double]
    'GE'    [1x3 double]

Note that now you have a 2-by-2 cell array where cells in the second column contain 1-by-3 double arrays.


问:
How to fix unreliable WebRTC calling?
WebRTC calls are not reliable in our application. Sometimes we see the black screen, sometimes we don’t see call start at all and sometimes there are seen huge delays or de-sync in audio/video.

Setup:

Google’s public STUN server stun:stun.l.google.com:19302;

TURN server is Coturn hosted in azure in docker;

Signaling server is a customized https://github.com/andyet/signalmaster that using express as a web server

On client JS is used, with simplewebrtc as client;

For iOS support used Cordova plugin - https://github.com/eface2face/cordova-plugin-iosrtc

Almost 100% reproduced issue is calling from one client on LTE to another on Wi-Fi. In this case we see black screen on both devices, however, default bg-color is white, so at least something happens on WebRTC side.

What was done to address issues:

Examined Coturn logs... Sometimes we see "Unauthorized" errors there, but it's hard to say if they affect anything;

Checked Coturn's traffic: in Wi-Fi to Wi-Fi scenarios it is low, so peer-to-peer connection is really made. If there is LTE, we see around 40–120KiB/sec load (Isn't that too low for audio/video?), so TURN seems to work;

Checked client app logs, nothing special;

Please, suggest any possible way of research or fix to make WebRTC as much reliable as possible.

答:
The above scheme is from this article I wrote which goes into a lot of detail on this topic.

Shortly, problems can appear in any of the 3 steps:

signaling

discovery using STUN/TURN

p2p connection

Here's what I would do:

Use a low minimum resolution in constraints like 320x240, this will make sure there are no simple to avoid getUserMedia() errors

Make sure signaling is done over port 80 or 443

In many cases a peer can not communicate with the STUN/TURN servers so try  communicating with STUN/TURN using TCP (stun:stun.l.google.com:19302?transport=tcp) and port 80 (default is UDP port 3478 or 19302 for Google's STUN and they might be blocked by your router/firewall/proxy/mobile network )

Use TrickleICE (with your own STUN/TURN) and the WebRTC Troubleshooter on the LTE/WiFi devices and you'll learn a lot about how they can be connected to

Title: How to fix unreliable WebRTC calling?


问:
Insert a new line in shiny's modalDialog
In my shiny app I would like to have a popup window with some text. To make the text more readable I would like to include some linebreaks, but so far I have failed. Any idea how would I do that? I am currently using modalDialog()

```<code> ui = basicPage(
actionButton("show", "Show modal dialog")
),
server = function(input, output) {
observeEvent(input$show, {
  showModal(modalDialog(
    title = "My text",
    "This is the first line.
     This should be the second."
  ))
})
}
</code>```

I have tried: br(), \n and several variations of those. Nothing worked.

Help!!!

答:
You can wrap it in HTML() and then use
, similar to your attempt mentioned above. So you could use instead: HTML("This is the first line.

      This should be the second.")

For the full app, see below:

```<code>ui = basicPage(
  actionButton("show", "Show modal dialog")
)
server = function(input, output) {
  observeEvent(input$show, {
    showModal(modalDialog(
      title = "My text",
      HTML("This is the first line.<br>
      This should be the second.")
    ))
  })
}
shinyApp(ui, server)
</code>```

Body:
In my shiny app I would like to have a popup window with some text. To make the text more readable I would like to include some linebreaks, but so far I have failed. Any idea how would I do that? I am currently using modalDialog()

 ui = basicPage(
actionButton("show", "Show modal dialog")
),
server = function(input, output) {
observeEvent(input$show, {
  showModal(modalDialog(
    title = "My text",
    "This is the first line.
     This should be the second."
  ))
})
}

I have tried: br(), \n and several variations of those. Nothing worked.

Help!!!

Body:
You can wrap it in HTML() and then use <br>, similar to your attempt mentioned above. So you could use instead: HTML("This is the first line.<br>
      This should be the second.")

For the full app, see below:

ui = basicPage(
  actionButton("show", "Show modal dialog")
)
server = function(input, output) {
  observeEvent(input$show, {
    showModal(modalDialog(
      title = "My text",
      HTML("This is the first line.<br>
      This should be the second.")
    ))
  })
}
shinyApp(ui, server)


问:
GC overhead limit exceeded when reading large pipe-separated values file
I am trying to parse a large file (6.5 million rows) but am getting the mentioned out-of-memory error. I am using this same method to read other files of around 50K rows, and it works fairly quickly. Here it runs extremely slowly, then fails with the error. I originally had 2 GB dedicated to intelliJ, which I changed to 4 GB (-Xmx4000m), then 6 GB (-Xmx6000m), and still finish with the same error. My computer only has 8 GB RAM so I can't go any higher. Any suggestions?

Thanks!

```<code>public static List<UmlsEntry> umlsEntries(Resource resource) throws
 IOException {
 return CharStreams.readLines(new InputStreamReader(resource.getInputStream())).stream().distinct()
    .map(UmlsParser::toUmlsEntry).collect(Collectors.toList());
}

private static UmlsEntry toUmlsEntry(String line) {
 String[] umlsEntry = line.split("|");

 return new UmlsEntry(umlsEntry[UNIQUE_IDENTIFIER_FOR_CONCEPT_COLUMN_INDEX],
    umlsEntry[LANGUAGE_OF_TERM_COLUMN_INDEX], umlsEntry[TERM_STATUS_COLUMN_INDEX],
    umlsEntry[UNIQUE_IDENTIFIER_FOR_TERM_COLUMN_INDEX], umlsEntry[STRING_TYPE_COLUMN_INDEX],
    umlsEntry[UNIQUE_IDENTIFIER_FOR_STRING_COLUMN_INDEX],
    umlsEntry[IS_PREFERRED_STRING_WITHIN_THIS_CONCEPT_COLUMN_INDEX],
    umlsEntry[UNIQUE_IDENTIFIER_FOR_ATOM_COLUMN_INDEX], umlsEntry[SOURCE_ASSERTED_ATOM_INDENTIFIER_COLUMN_INDEX],
    umlsEntry[SOURCE_ASSERTED_CONCEPT_IDENTIFIER_COLUMN_INDEX],
    umlsEntry[SOURCE_ASSERTED_DESCRIPTOR_IDENTIFIER_COLUMN_INDEX],
    umlsEntry[ABBREVIATED_SOURCE_NAME_COLUMN_IDENTIFIER_COLUMN_INDEX],
    umlsEntry[ABBREVIATION_FOR_TERM_TYPE_IN_SOURCE_VOCABULARY_COLUMN_INDEX],
    umlsEntry[MOST_USEFUL_SOURCE_ASSERTED_IDENTIFIER_COLUMN_INDEX], umlsEntry[STRING_COLUMN_INDEX],
    umlsEntry[SOURCE_RESTRICTION_LEVEL_COLUMN_INDEX], umlsEntry[SUPPRESSIBLE_FLAG_COLUMN_INDEX],
    umlsEntry[CONTENT_VIEW_FLAG_COLUMN_INDEX]);
 }
</code>```

答:
You need to treat the lines a few at a time to avoid using up all available memory, since the file doesn't fit in memory. CharStreams.readLines confusingly isn't streaming. It reads all lines at once and returns you a list. This won't work. Try File.lines instead. I suspect that you will get into trouble with distinct as well. It will need to keep track of all hashes of all lines, and if this balloons too far you might have to change that tactic as well. Oh, and collect won't work either if you don't have enough memory to hold the result. Then you might want to write to a new file or a database or so.

Here is an example of how you can stream lines from a file, compute distinct entries and print the md5 of each line:

```<code>Files.lines(FileSystems.getDefault().getPath("/my/file"))
            .distinct()
            .map(DigestUtils::md5)
            .forEach(System.out::println);
</code>```

If you run into trouble detecting distinct rows, sort the file in-place first and then filter out identical adjacent rows only.

Body:
I am trying to parse a large file (6.5 million rows) but am getting the mentioned out-of-memory error. I am using this same method to read other files of around 50K rows, and it works fairly quickly. Here it runs extremely slowly, then fails with the error. I originally had 2 GB dedicated to intelliJ, which I changed to 4 GB (-Xmx4000m), then 6 GB (-Xmx6000m), and still finish with the same error. My computer only has 8 GB RAM so I can't go any higher. Any suggestions?

Thanks!

public static List<UmlsEntry> umlsEntries(Resource resource) throws
 IOException {
 return CharStreams.readLines(new InputStreamReader(resource.getInputStream())).stream().distinct()
    .map(UmlsParser::toUmlsEntry).collect(Collectors.toList());
}

private static UmlsEntry toUmlsEntry(String line) {
 String[] umlsEntry = line.split("|");

 return new UmlsEntry(umlsEntry[UNIQUE_IDENTIFIER_FOR_CONCEPT_COLUMN_INDEX],
    umlsEntry[LANGUAGE_OF_TERM_COLUMN_INDEX], umlsEntry[TERM_STATUS_COLUMN_INDEX],
    umlsEntry[UNIQUE_IDENTIFIER_FOR_TERM_COLUMN_INDEX], umlsEntry[STRING_TYPE_COLUMN_INDEX],
    umlsEntry[UNIQUE_IDENTIFIER_FOR_STRING_COLUMN_INDEX],
    umlsEntry[IS_PREFERRED_STRING_WITHIN_THIS_CONCEPT_COLUMN_INDEX],
    umlsEntry[UNIQUE_IDENTIFIER_FOR_ATOM_COLUMN_INDEX], umlsEntry[SOURCE_ASSERTED_ATOM_INDENTIFIER_COLUMN_INDEX],
    umlsEntry[SOURCE_ASSERTED_CONCEPT_IDENTIFIER_COLUMN_INDEX],
    umlsEntry[SOURCE_ASSERTED_DESCRIPTOR_IDENTIFIER_COLUMN_INDEX],
    umlsEntry[ABBREVIATED_SOURCE_NAME_COLUMN_IDENTIFIER_COLUMN_INDEX],
    umlsEntry[ABBREVIATION_FOR_TERM_TYPE_IN_SOURCE_VOCABULARY_COLUMN_INDEX],
    umlsEntry[MOST_USEFUL_SOURCE_ASSERTED_IDENTIFIER_COLUMN_INDEX], umlsEntry[STRING_COLUMN_INDEX],
    umlsEntry[SOURCE_RESTRICTION_LEVEL_COLUMN_INDEX], umlsEntry[SUPPRESSIBLE_FLAG_COLUMN_INDEX],
    umlsEntry[CONTENT_VIEW_FLAG_COLUMN_INDEX]);
 }

Body:
You need to treat the lines a few at a time to avoid using up all available memory, since the file doesn't fit in memory. CharStreams.readLines confusingly isn't streaming. It reads all lines at once and returns you a list. This won't work. Try File.lines instead. I suspect that you will get into trouble with distinct as well. It will need to keep track of all hashes of all lines, and if this balloons too far you might have to change that tactic as well. Oh, and collect won't work either if you don't have enough memory to hold the result. Then you might want to write to a new file or a database or so.

Here is an example of how you can stream lines from a file, compute distinct entries and print the md5 of each line:

Files.lines(FileSystems.getDefault().getPath("/my/file"))
            .distinct()
            .map(DigestUtils::md5)
            .forEach(System.out::println);

If you run into trouble detecting distinct rows, sort the file in-place first and then filter out identical adjacent rows only.


问:
Kentico - Display query string as value of input field
I want to display the query string (if it's not empty) as the value of an input field, something like this <input name="campaign" type="hidden" value="ABC Campaign {% if (QueryString.GetValue("utm_source") != null) { return "| QueryString.GetValue("utm_source")"} %}" />

but couldn't make it work due to all the double quotes. I've tried escaping the quotes with back slash but didn't work. Could you help?
(The above code is placed inside the Form > Layout)

答:
Also you can use another syntax to get query parameters:</p>

```<code>{% !String.IsNullOrEmpty(QueryString.utm_source)?QueryString.utm_source:"" %}
</code>```

Body:
Also you can use another syntax to get query parameters:

{% !String.IsNullOrEmpty(QueryString.utm_source)?QueryString.utm_source:"" %}


问:
akka stream consumer of rabbitmq with AMQP connector
I want to consume data from rabbitMQ queue with akka stream (Java). I took help from following link: http://developer.lightbend.com/docs/alpakka/latest/amqp.html

I would like to know about acknowledgement flow to rabbitMQ after element is consumed.

Can I consume the element in parallel? (Java snippet will be really helpful)

Thanks

答: The current Alpakka AMQP connector does naive acking of messages as soon as they are emitted downstream, there is a ticket tracking adding a more flexible solution that you can follow here: https://github.com/akka/alpakka/issues/97</p>


问:
Dispatch Redux action in React
I'm trying to fetch test API using FetchAPI and Redux.

The problem is with dispatch redux action.

Here's my code:

```<code>ProductList.js
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as productActions from '../actions/product';
import RaisedButton from 'material-ui/RaisedButton';

function fetchProductsWithRedux() {
    console.log("fetchProductsWithRedux-1");
    return (dispatch) => {
        console.log("fetchProductsWithRedux-2");
        dispatch(this.props.action.fetchProdutcsRequest());
        return fetchProdutcs().then(([response, json]) => {
            if (response.status === 200) {
                console.log("success");
                dispatch(this.props.action.fetchProductsSucesss(json))
            }
            else {
                console.log("error");
                dispatch(this.props.action.fetchProductsError())
            }
        })
    }
}

function fetchProdutcs() {
    const URL = "https://jsonplaceholder.typicode.com/posts";
    return fetch(URL, { method: 'GET' })
        .then(response => Promise.all([response, response.json()]));
}

class ProductList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            productList: [
                'product 1',
                'product 2',
                'product 3'
            ]
        }
    }
    componentDidMount() {
        fetchProductsWithRedux();
    }
    render() {
        return (
            <div className="ProductList">
                <h2>Products</h2>
                <ul>
                    {
                        this.props.posts &&
                        this.props.posts.map((post) => {
                            return (
                                <li>{post.title}</li>
                            )
                        })
                    }
                </ul>

                <ol>
                    <RaisedButton label="Get Products Action" onClick={this.props.action.getProducts} />
                </ol>
            </div>
        );
    }
}

function mapStateToProps(state, props) {
    return {
        product: state.product,
        posts: state.posts
    };
}
function mapDispatchToProps(dispatch) {
    return {
        action: bindActionCreators(productActions, dispatch)
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(ProductList);
</code>```

product.js (actions)

```<code>export function fetchProductsRequest() {
  console.log('fetchProductsRequest');
  return {
    type: 'FETCH_PRODUCTS_REQUEST'
  }
}

export function fetchProductsSuccess(payload) {
  console.log('fetchProductsSuccess');
  return {
    type: 'FETCH_PRODUCTS_SUCCESS'
  }
}

export function fetchProductsError() {
  console.log('fetchProductsError');
  return {
    type: 'FETCH_PRODUCTS_ERROR'
  }
}
</code>```

product.js (reducer)

```<code>export default(state = [], payload) => {
    switch (payload.type) {
        case 'FETCH_PRODUCTS_REQUEST':
            console.log('FETCH_PRODUCTS_REQUEST action');
            return state;
        case 'FETCH_PRODUCTS_SUCCESS':
            console.log('FETCH_PRODUCTS_SUCCES action');
            return {...state, posts: payload.payload}
        default:
            return state;
    }
};
</code>```

store.js

```<code>import { createStore } from 'redux';
import rootReducer from './reducers';

export default(initialState) => {
    return createStore(rootReducer, initialState);
}

Product.js (pages, component)
import React, { Component } from 'react';
import ProductList from '../../components/ProductList';
import RaisedButton from 'material-ui/RaisedButton';
//import './Product.css';

class Product extends Component {
    render() {
        return (
            <div className="Product">
                <h1>ProductList Page</h1>
                <RaisedButton label="Default" />
                <ProductList />
            </div>
        );
    }
}
export default Product;
</code>```

The line console.log("fetchProductsWithRedux-2"); in ProductList.js has never been reached.

What's wrong? Any ideas? Thanks in advance.

答:
```<code>function fetchProductsWithRedux() {
console.log("fetchProductsWithRedux-1");
return (dispatch) => {
    console.log("fetchProductsWithRedux-2");
    ...
    }
</code>```

This returns a function function(dispatch){...}, which is not called in

```<code>componentDidMount() {
    fetchProductsWithRedux();
}
</code>```

Title: Dispatch Redux action in React

Body:
I'm trying to fetch test API using FetchAPI and Redux.

The problem is with dispatch redux action.

Here's my code:

ProductList.js
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as productActions from '../actions/product';
import RaisedButton from 'material-ui/RaisedButton';

function fetchProductsWithRedux() {
    console.log("fetchProductsWithRedux-1");
    return (dispatch) => {
        console.log("fetchProductsWithRedux-2");
        dispatch(this.props.action.fetchProdutcsRequest());
        return fetchProdutcs().then(([response, json]) => {
            if (response.status === 200) {
                console.log("success");
                dispatch(this.props.action.fetchProductsSucesss(json))
            }
            else {
                console.log("error");
                dispatch(this.props.action.fetchProductsError())
            }
        })
    }
}

function fetchProdutcs() {
    const URL = "https://jsonplaceholder.typicode.com/posts";
    return fetch(URL, { method: 'GET' })
        .then(response => Promise.all([response, response.json()]));
}

class ProductList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            productList: [
                'product 1',
                'product 2',
                'product 3'
            ]
        }
    }
    componentDidMount() {
        fetchProductsWithRedux();
    }
    render() {
        return (

Products

                    {
                        this.props.posts &&
                        this.props.posts.map((post) => {
                            return (

{post.title}

                            )
                        })
                    }

                    <RaisedButton label="Get Products Action" onClick={this.props.action.getProducts} />

        );
    }
}

function mapStateToProps(state, props) {
    return {
        product: state.product,
        posts: state.posts
    };
}
function mapDispatchToProps(dispatch) {
    return {
        action: bindActionCreators(productActions, dispatch)
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(ProductList);

product.js (actions)

export function fetchProductsRequest() {
  console.log('fetchProductsRequest');
  return {
    type: 'FETCH_PRODUCTS_REQUEST'
  }
}

export function fetchProductsSuccess(payload) {
  console.log('fetchProductsSuccess');
  return {
    type: 'FETCH_PRODUCTS_SUCCESS'
  }
}

export function fetchProductsError() {
  console.log('fetchProductsError');
  return {
    type: 'FETCH_PRODUCTS_ERROR'
  }
}

product.js (reducer)

export default(state = [], payload) => {
    switch (payload.type) {
        case 'FETCH_PRODUCTS_REQUEST':
            console.log('FETCH_PRODUCTS_REQUEST action');
            return state;
        case 'FETCH_PRODUCTS_SUCCESS':
            console.log('FETCH_PRODUCTS_SUCCES action');
            return {...state, posts: payload.payload}
        default:
            return state;
    }
};

store.js

import { createStore } from 'redux';
import rootReducer from './reducers';

export default(initialState) => {
    return createStore(rootReducer, initialState);
}

Product.js (pages, component)
import React, { Component } from 'react';
import ProductList from '../../components/ProductList';
import RaisedButton from 'material-ui/RaisedButton';
//import './Product.css';

class Product extends Component {
    render() {
        return (

ProductList Page

                <RaisedButton label="Default" />
                <ProductList />

        );
    }
}
export default Product;

The line console.log("fetchProductsWithRedux-2"); in ProductList.js has never been reached.

What's wrong? Any ideas? Thanks in advance.

Body:
function fetchProductsWithRedux() {
console.log("fetchProductsWithRedux-1");
return (dispatch) => {
    console.log("fetchProductsWithRedux-2");
    ...
    }

This returns a function function(dispatch){...}, which is not called in

componentDidMount() {
    fetchProductsWithRedux();
}


问:
maven resource filtering skipping files
I got a Vaadin project with the following structure:

```<code>Project-Root
  src
    main
    resources
      properties.json
      META-INF
        persistance.xml
    webapp
      WEB-INF
        classes
          hibernate-dashboard.cfg.xml
          quartz.properties
</code>```

Until now I built my project from my IDE (IntelliJ)

```<code>mvn vaadin:compile vaadin:compile-theme -P development
</code>```

and then packaged the WAR with 'Build' -> 'Build Artifacts...' and deployed the WAR.

My resource filtering is the following:

```<code>..
<build>
 <resources>
     <resource>
         <directory>src/main/webapp/WEB-INF/classes/</directory>
         <filtering>true</filtering>
     </resource>
     <resource>
         <directory>src/main/resources/</directory>
         <filtering>true</filtering>
     </resource>
     <resource>
         <directory>src/main/resources/META-INF</directory>
         <filtering>true</filtering>
     </resource>
 </resources>
 <plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-resources-plugin</artifactId>
     <version>2.6</version>
     <configuration>
         <encoding>${project.encoding}</encoding>
     </configuration>
 </plugin>
</code>```

Problem: When I try to build the whole project with maven

```<code>mvn clean package -P development
</code>```

the resources under webapp/WEB-INF/classes get skipped, they are in the target/Project/WEB-INF/classes directory, but the variables are ${..} (hibernate-dashboard.cfg.xml and quartz.properties)

The remaining resources (properties.json and persistance.xml) get filtered correctly.

Question: How can I filter all my resources and build/package my project with maven?

答:
Maven only handles files in src/main/resources so I added

```<code><configuration>
  <webResources>
      <resource>
          <directory>src/main/webapp/WEB-INF/classes</directory>
          <targetPath>WEB-INF/classes</targetPath>
          <filtering>true</filtering>
      </resource>
  </webResources>
</configuration>
</code>```

to the maven-war-plugin and now I get a correct packaged WAR file.

Title: maven resource filtering skipping files

Body:
I got a Vaadin project with the following structure:

Project-Root
  src
    main
    resources
      properties.json
      META-INF
        persistance.xml
    webapp
      WEB-INF
        classes
          hibernate-dashboard.cfg.xml
          quartz.properties

Until now I built my project from my IDE (IntelliJ)

mvn vaadin:compile vaadin:compile-theme -P development

and then packaged the WAR with 'Build' -> 'Build Artifacts...' and deployed the WAR.

My resource filtering is the following:

..
<build>
 <resources>
     <resource>
         <directory>src/main/webapp/WEB-INF/classes/</directory>
         <filtering>true</filtering>
     </resource>
     <resource>
         <directory>src/main/resources/</directory>
         <filtering>true</filtering>
     </resource>
     <resource>
         <directory>src/main/resources/META-INF</directory>
         <filtering>true</filtering>
     </resource>
 </resources>
 <plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-resources-plugin</artifactId>
     <version>2.6</version>
     <configuration>
         <encoding>${project.encoding}</encoding>
     </configuration>
 </plugin>

Problem: When I try to build the whole project with maven

mvn clean package -P development

the resources under webapp/WEB-INF/classes get skipped, they are in the target/Project/WEB-INF/classes directory, but the variables are ${..} (hibernate-dashboard.cfg.xml and quartz.properties)

The remaining resources (properties.json and persistance.xml) get filtered correctly.

Question: How can I filter all my resources and build/package my project with maven?

Body:
Maven only handles files in src/main/resources so I added

<configuration>
  <webResources>
      <resource>
          <directory>src/main/webapp/WEB-INF/classes</directory>
          <targetPath>WEB-INF/classes</targetPath>
          <filtering>true</filtering>
      </resource>
  </webResources>
</configuration>

to the maven-war-plugin and now I get a correct packaged WAR file.


问:
Posting Json string to web api c#
I'm quite new to handling json data and web apis but I'm currently creating an application to further my knowledge on them.

At the moment I can do get requests and these work fine however I'm having issues with posts. I'm trying to post json data to Jira Confluence to create a new page.

On https://developer.atlassian.com/confdev/confluence-server-rest-api/confluence-rest-api-examples it gives the below code to make a curl request

curl -u admin:admin -X POST -H 'Content-Type: application/json' -d'{"type":"page","title":"new page",
"ancestors":[{"id":456}], "space":{"key":"TST"},"body":{"storage":{"value":
"
This is a new page
","representation":"storage"}}}'
http://localhost:8080/confluence/rest/api/content/ | python -mjson.tool```
</div>
</div>
</p>

<p>I am currently using the below code and it comes back with a status 200 but I don't see the created page on confluence. I was wondering if anyone could help me out</p>

```HttpClient _webRequest = new HttpClient();
byte[] cred = UTF8Encoding.UTF8.GetBytes(credentials);
_webRequest.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
_webRequest.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
string response = "{\"type\":\"page\",\"title\":\"new page\",\"ancestors\":[{\"id\":40635756}],\"space\":{\"key\":\"VG\"},\"body\":{\"storage\":{\"value\":\"
This is a new page
\",\"representation\":\"storage\"}}}"

var content = new StringContent(lol, Encoding.UTF8, "application/json");
var result = _webRequest.PostAsync("http://jirasite/confluence/rest/api/content/", content).Result;
```

答:
Your auth header looks incorrect... You are missing the whitespace after "Basic" it should be like this "Basic xxx".

Please take a look at the following document:

https://developer.atlassian.com/confdev/confluence-server-rest-api/confluence-rest-api-examples?_ga=2.72183699.1804458933.1496916716-1816616270.1496916716#ConfluenceRESTAPIExamples-Createanewpage

Regards

Craig

Title: Posting Json string to web api c#

Body:
I'm quite new to handling json data and web apis but I'm currently creating an application to further my knowledge on them.

At the moment I can do get requests and these work fine however I'm having issues with posts. I'm trying to post json data to Jira Confluence to create a new page.

On https://developer.atlassian.com/confdev/confluence-server-rest-api/confluence-rest-api-examples it gives the below code to make a curl request

curl -u admin:admin -X POST -H 'Content-Type: application/json' -d'{"type":"page","title":"new page",
"ancestors":[{"id":456}], "space":{"key":"TST"},"body":{"storage":{"value":
"
This is a new page
","representation":"storage"}}}'
http://localhost:8080/confluence/rest/api/content/ | python -mjson.tool

I am currently using the below code and it comes back with a status 200 but I don't see the created page on confluence. I was wondering if anyone could help me out

HttpClient _webRequest = new HttpClient();
byte[] cred = UTF8Encoding.UTF8.GetBytes(credentials);
_webRequest.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
_webRequest.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
string response = "{\"type\":\"page\",\"title\":\"new page\",\"ancestors\":[{\"id\":40635756}],\"space\":{\"key\":\"VG\"},\"body\":{\"storage\":{\"value\":\"
This is a new page
\",\"representation\":\"storage\"}}}"

var content = new StringContent(lol, Encoding.UTF8, "application/json");
var result = _webRequest.PostAsync("http://jirasite/confluence/rest/api/content/", content).Result;