问:
Javadoc Exclude causing errors on import
I'm looking to tweak the javadocs for the library my company produces. We're looking to exclude javadocs from classes that aren't really meant for public consumption (mostly classes used internally).

The project uses gradle as the build system, and I've marked the packages/classes that we want to exclude in the build.gradle file. However, this is causing errors to happen. I expect to get a warning, or error if there's @link to a class which is excluded, but it's also throwing errors when those excluded classes are simply imported. Is there a way to "include" the classes/packages, but NOT export the javadoc for them?

Edit: Here's the relevant javadoc task:

```<code>task gendocs(type: Javadoc) {
    options.stylesheetFile = new File("./assets/doc_style.css")
    String v = "${SEMVER}"
    version = v.replace("_", '.')
    title = "SweetBlue ${version} API"
    options.windowTitle = "SweetBlue"
    options.memberLevel = JavadocMemberLevel.PROTECTED
    options.author = true
    options.linksOffline('http://d.android.com/reference', System.getenv("ANDROID_HOME") + '/docs/reference')
    destinationDir = new File("${BUNDLE_FOLDER}/docs/api")
    source = sourceSets.main.allJava
    classpath += configurations.compile
    exclude "com/idevicesinc/sweetblue/backend"
    exclude "com/idevicesinc/sweetblue/utils/Utils**.java"
    exclude "com/idevicesinc/sweetblue/utils/UpdateLoop.java"
    exclude "com/idevicesinc/sweetblue/utils/Pointer.java"
    exclude "com/idevicesinc/sweetblue/utils/HistoricalDataQuery.java"
}
</code>```

Edit 2: Here's the error I'm talking about:

```<code>SweetBlue/src/com/idevicesinc/sweetblue/BleCharacteristic.java:5: error: cannot find symbol
import com.idevicesinc.sweetblue.utils.Utils;
symbol:   class Utils
location: package com.idevicesinc.sweetblue.utils
</code>```

Edit 3:

It appears that exclude in a gradle javadoc task is NOT the same thing as using -exclude on the command line with javadoc. I ran a test using CLI javadoc generation, and I did NOT get the not found errors that I do when using Gradle.

I have also posted this on the Gradle forum but did not receive an answer there.

答:
So the problem is you have to tell the Javadoc task where the external imports are located, so it can creates (Hyper)-links to it in the Javadoc HTML. If you don't care about links to external classes you could ignore theses issues with:

```<code>task gendocs(type: Javadoc) {
    failOnError false
    ...
}
</code>```

According to the Gradle Doc:

Specifies whether this task should fail when errors are encountered during Javadoc generation. When true, this task will fail on Javadoc error. When false, this task will ignore Javadoc errors

ContentLicense: CC BY-SA 4.0

Body:
I'm looking to tweak the javadocs for the library my company produces. We're looking to exclude javadocs from classes that aren't really meant for public consumption (mostly classes used internally).

The project uses gradle as the build system, and I've marked the packages/classes that we want to exclude in the build.gradle file. However, this is causing errors to happen. I expect to get a warning, or error if there's @link to a class which is excluded, but it's also throwing errors when those excluded classes are simply imported. Is there a way to "include" the classes/packages, but NOT export the javadoc for them?

Edit: Here's the relevant javadoc task:

task gendocs(type: Javadoc) {
    options.stylesheetFile = new File("./assets/doc_style.css")
    String v = "${SEMVER}"
    version = v.replace("_", '.')
    title = "SweetBlue ${version} API"
    options.windowTitle = "SweetBlue"
    options.memberLevel = JavadocMemberLevel.PROTECTED
    options.author = true
    options.linksOffline('http://d.android.com/reference', System.getenv("ANDROID_HOME") + '/docs/reference')
    destinationDir = new File("${BUNDLE_FOLDER}/docs/api")
    source = sourceSets.main.allJava
    classpath += configurations.compile
    exclude "com/idevicesinc/sweetblue/backend"
    exclude "com/idevicesinc/sweetblue/utils/Utils**.java"
    exclude "com/idevicesinc/sweetblue/utils/UpdateLoop.java"
    exclude "com/idevicesinc/sweetblue/utils/Pointer.java"
    exclude "com/idevicesinc/sweetblue/utils/HistoricalDataQuery.java"
}

Edit 2: Here's the error I'm talking about:

SweetBlue/src/com/idevicesinc/sweetblue/BleCharacteristic.java:5: error: cannot find symbol
import com.idevicesinc.sweetblue.utils.Utils;
symbol:   class Utils
location: package com.idevicesinc.sweetblue.utils

Edit 3:

It appears that exclude in a gradle javadoc task is NOT the same thing as using -exclude on the command line with javadoc. I ran a test using CLI javadoc generation, and I did NOT get the not found errors that I do when using Gradle.

I have also posted this on the Gradle forum but did not receive an answer there.

Body:
So the problem is you have to tell the Javadoc task where the external imports are located, so it can creates (Hyper)-links to it in the Javadoc HTML. If you don't care about links to external classes you could ignore theses issues with:

task gendocs(type: Javadoc) {
    failOnError false
    ...
}

According to the Gradle Doc:

Specifies whether this task should fail when errors are encountered during Javadoc generation. When true, this task will fail on Javadoc error. When false, this task will ignore Javadoc errors


来源: stackexchange

问:
how to connection establish with both database from different database oracle and mysql in yii2
Actually i create a application and
please someone say me. how to establish connection with mysql and different oracle server.
and how to update if update my mysql field so automatic update my oracle erp system.</p>

答:
Use Paritosh Mahale link. Assume you have OracleModel with getDb() returning oracle connection and MySql model with getDb() returning mysql connection. Then in MySql model define afterSave event hendler:</p>

```<code>public function afterSave()
{
    $oracleModel = OracleModel::findOne(/* condition */);
    $oracleModel->someField = 123;
    $oracleModel->save();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Use Paritosh Mahale link. Assume you have OracleModel with getDb() returning oracle connection and MySql model with getDb() returning mysql connection. Then in MySql model define afterSave event hendler:

public function afterSave()
{
    $oracleModel = OracleModel::findOne(/* condition */);
    $oracleModel->someField = 123;
    $oracleModel->save();
}


问:
Table for a little quantity of registers... I don´t would like to do that
I'm a Brazilian, sorry for my English.

I have a Pet and Pet_Model models. Both have Colors.

I don´t would like to make a table with 4, 5 colors (registers).

Firstly, I did a Color model (without database table) with an array attribute colors with hashes of name color and his code:

```<code> class Color
        def colors
            [{:name => 'blue', :cod => '#FF9'}, {...}, ...]
        end
 end
</code>```

And I used a 'fields_for :colors' in the form Pet erb.

But I had problems to rescue these data from database. Then I doing think make a table for Colors. But this table will contain only 4, 5 registers... Understand me?

What is the best solution? Create or not create a table for these colors?

Thanks

[EDIT]

Are relevant...

VIEW

```<code><% for color in Color::COLORS.keys %>
  <%= check_box_tag 'pet[colors][]', color %>
  <%= color %><br/>
<% end -%>
</code>```

MODEL

```<code>class Pet < ActiveRecord::Base
    serialize :colors
end
</code>```

答:
I'm really not sure if I understand your question, but assuming that you have a predefined hash of colors and you want to be able to use this hash to set a color for your pets and pet models.

If this selection of colors doesn't change, you could maybe use a constant containing the colors and a bitmask to store the selected color with your models — then you wouldn't need a colors table.
Ryan Bates has a nice screencast which uses this technique: http://railscasts.com/episodes/189-embedded-association

In your case you'd need probably redefine the hash to look something like this

```<code>{ "red" => "#f00", "blue" => "#ff9", … }
</code>```

And then only deal the keys

```<code>{ "red" => "#f00", "blue" => "#ff9", … }.keys # -> ["red", "blue", …]
</code>```

Am I anywhere close to what you need?

ContentLicense: CC BY-SA 2.5

Body:
I'm a Brazilian, sorry for my English.

I have a Pet and Pet_Model models. Both have Colors.

I don´t would like to make a table with 4, 5 colors (registers).

Firstly, I did a Color model (without database table) with an array attribute colors with hashes of name color and his code:

 class Color
        def colors
            [{:name => 'blue', :cod => '#FF9'}, {...}, ...]
        end
 end

And I used a 'fields_for :colors' in the form Pet erb.

But I had problems to rescue these data from database. Then I doing think make a table for Colors. But this table will contain only 4, 5 registers... Understand me?

What is the best solution? Create or not create a table for these colors?

Thanks

[EDIT]

Are relevant...

VIEW

<% for color in Color::COLORS.keys %>
  <%= check_box_tag 'pet[colors][]', color %>
  <%= color %>

<% end -%>

MODEL

class Pet < ActiveRecord::Base
    serialize :colors
end

Body:
I'm really not sure if I understand your question, but assuming that you have a predefined hash of colors and you want to be able to use this hash to set a color for your pets and pet models.

If this selection of colors doesn't change, you could maybe use a constant containing the colors and a bitmask to store the selected color with your models — then you wouldn't need a colors table.
Ryan Bates has a nice screencast which uses this technique: http://railscasts.com/episodes/189-embedded-association

In your case you'd need probably redefine the hash to look something like this

{ "red" => "#f00", "blue" => "#ff9", … }

And then only deal the keys

{ "red" => "#f00", "blue" => "#ff9", … }.keys # -> ["red", "blue", …]

Am I anywhere close to what you need?


问:
dialog.setCanceledOnTouchOutside(true) not working when click outside the dialog
I use DialogFragment to create/show the dialog.

Additionally, I want to dismiss the dialogue when I click outside of the dialogue.

I tried calling dialog.setCanceledOnTouchOutside(true) method after a dialogue is created but it is not working.

I tried some solutions from other posts, but still not working.

Where is the problem?

Here is my code DialogSelectCategory.java

```<code><!-- language: java -->
public class DialogSelectCategory extends DialogFragment {
    static final String tag = "DialogSelectCategory";
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Activity act = getActivity();
        AlertDialog.Builder builder = new AlertDialog.Builder(act);
        String title = getResources().getString(R.string.select_category);
        View view = LayoutInflater.from(act).inflate(R.layout.dialog_category, null, false);
        builder.setView(view);
        builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                dialog.dismiss();
            }
        });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                dialog.dismiss();
            }
        });

        Dialog dialog = builder.create();
        setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);

        return dialog;
    }

    public void showDialog(FragmentManager fragmentManager) {
        FragmentTransaction ft = fragmentManager.beginTransaction();
        Fragment prev = fragmentManager.findFragmentByTag(tag);
        if (prev != null) {
            ft.remove(prev);
        }
        ft.addToBackStack(null);
        this.show(fragmentManager, tag);
    }
}
</code>```

答:
The problem is occurring when you are using DialogFragment to display Dialog

According to http://developer.android.com/reference/android/app/DialogFragment.html, the solution is to override onCancel in DialogFragment

```<code>// DialogFragment, not Dialog
@Override
public void onCancel(DialogInterface dialog) {
}
</code>```

Body:
I use DialogFragment to create/show the dialog.

Additionally, I want to dismiss the dialogue when I click outside of the dialogue.

I tried calling dialog.setCanceledOnTouchOutside(true) method after a dialogue is created but it is not working.

I tried some solutions from other posts, but still not working.

Where is the problem?

Here is my code DialogSelectCategory.java

public class DialogSelectCategory extends DialogFragment {
    static final String tag = "DialogSelectCategory";
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Activity act = getActivity();
        AlertDialog.Builder builder = new AlertDialog.Builder(act);
        String title = getResources().getString(R.string.select_category);
        View view = LayoutInflater.from(act).inflate(R.layout.dialog_category, null, false);
        builder.setView(view);
        builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                dialog.dismiss();
            }
        });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                dialog.dismiss();
            }
        });

        Dialog dialog = builder.create();
        setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);

        return dialog;
    }

    public void showDialog(FragmentManager fragmentManager) {
        FragmentTransaction ft = fragmentManager.beginTransaction();
        Fragment prev = fragmentManager.findFragmentByTag(tag);
        if (prev != null) {
            ft.remove(prev);
        }
        ft.addToBackStack(null);
        this.show(fragmentManager, tag);
    }
}

Body:
The problem is occurring when you are using DialogFragment to display Dialog

According to http://developer.android.com/reference/android/app/DialogFragment.html, the solution is to override onCancel in DialogFragment

// DialogFragment, not Dialog
@Override
public void onCancel(DialogInterface dialog) {
}


问:
Adding csv columns with cmd
I have 2 CSV files containing below data. I want to add the 3rd and 4th columns in a new CSV file using .cmd batch file. Is it possible to do it with .cmd batch file. If yes please help me with code.

File1.csv

```<code>SL,Name,Score,Result
1,Saquib,10,100
2,Tanzil,10,100
3,Hasib,10,100
4,Sharek,10,100
</code>```

and

File2.csv

```<code>SL,Name,Score,Result
1,Saquib,20,200
2,Tanzil,30,300
3,Hasib,40,400
4,Sharek,50,500
</code>```

The output should look like below.
Combine.csv

```<code>SL,Name,Score,Result
1,Saquib,30,300
2,Tanzil,40,400
3,Hasib,50,500
4,Sharek,60,600
</code>```

I have a code that combines the 2 files but do not add the fields.

```<code>@echo off
ECHO Set working directory
pushd %~dp0`enter code here`
ECHO Deleting existing combined file
del combined.csv
setlocal ENABLEDELAYEDEXPANSION
set cnt=1
for %%i in (*.csv) do (
  if !cnt!==1 (
    for /f "delims=" %%j in ('type "%%i"') do echo %%j >> combined.csv
  ) else if %%i NEQ combined.csv (
    for /f "skip=1 delims=" %%j in ('type "%%i"') do echo %%j >> combined.csv
  )
  set /a cnt+=1
</code>```

答:
batch is not the scripting language for this type of operation, it would be faster and easier to use a language like powershell.

example assuming the first two columns of the two files are identical

```<code>$table1 = import-csv file1.csv
$table2 = import-csv file2.csv

# convert Score Result columns to type int
$table1 |% { $_.Score = [int]$_.Score; $_.Result = [int]$_.Result }
$table2 |% { $_.Score = [int]$_.Score; $_.Result = [int]$_.Result }

# add score and result for each row respectively
for ($i=0;$i -lt $table1.count;$i++) {
    $table1[$i].Score  += $table2[$i].Score
    $table1[$i].Result += $table2[$i].Result
}

# export
$table1 | export-csv output.txt
</code>```

or, for example, using hashtables if first columns are not identical

```<code>$table1=import-csv file1.csv
$htable=@{}

foreach($r in $table1) {
    $r.Score = [int]$r.Score;
    $r.Result = [int]$r.Result;
    $htable[$r.SL] = $r;
}

$table2=import-csv file2.csv
foreach($r in $table2) {
    $r.Score = [int]$r.Score + $htable[$r.SL].Score;
    $r.Result = [int]$r.Result + $htable[$r.SL].Result;
    $htable[$r.SL] = $r;
}

$htable.Values | export-csv output.txt
</code>```

Title: Adding csv columns with cmd

Body:
I have 2 CSV files containing below data. I want to add the 3rd and 4th columns in a new CSV file using .cmd batch file. Is it possible to do it with .cmd batch file. If yes please help me with code.

File1.csv

SL,Name,Score,Result
1,Saquib,10,100
2,Tanzil,10,100
3,Hasib,10,100
4,Sharek,10,100

and

File2.csv

SL,Name,Score,Result
1,Saquib,20,200
2,Tanzil,30,300
3,Hasib,40,400
4,Sharek,50,500

The output should look like below.
Combine.csv

SL,Name,Score,Result
1,Saquib,30,300
2,Tanzil,40,400
3,Hasib,50,500
4,Sharek,60,600

I have a code that combines the 2 files but do not add the fields.

@echo off
ECHO Set working directory
pushd %~dp0`enter code here`
ECHO Deleting existing combined file
del combined.csv
setlocal ENABLEDELAYEDEXPANSION
set cnt=1
for %%i in (*.csv) do (
  if !cnt!==1 (
    for /f "delims=" %%j in ('type "%%i"') do echo %%j >> combined.csv
  ) else if %%i NEQ combined.csv (
    for /f "skip=1 delims=" %%j in ('type "%%i"') do echo %%j >> combined.csv
  )
  set /a cnt+=1

Body:
batch is not the scripting language for this type of operation, it would be faster and easier to use a language like powershell.

example assuming the first two columns of the two files are identical

$table1 = import-csv file1.csv
$table2 = import-csv file2.csv

# convert Score Result columns to type int
$table1 |% { $_.Score = [int]$_.Score; $_.Result = [int]$_.Result }
$table2 |% { $_.Score = [int]$_.Score; $_.Result = [int]$_.Result }

# add score and result for each row respectively
for ($i=0;$i -lt $table1.count;$i++) {
    $table1[$i].Score  += $table2[$i].Score
    $table1[$i].Result += $table2[$i].Result
}

# export
$table1 | export-csv output.txt

or, for example, using hashtables if first columns are not identical

$table1=import-csv file1.csv
$htable=@{}

foreach($r in $table1) {
    $r.Score = [int]$r.Score;
    $r.Result = [int]$r.Result;
    $htable[$r.SL] = $r;
}

$table2=import-csv file2.csv
foreach($r in $table2) {
    $r.Score = [int]$r.Score + $htable[$r.SL].Score;
    $r.Result = [int]$r.Result + $htable[$r.SL].Result;
    $htable[$r.SL] = $r;
}

$htable.Values | export-csv output.txt


问:
Oracle Relational Division Query
I am trying to write a Relational Division query (I am required to use Relational Division for this)
Given the following tables:

Guest:

```<code>   GID      PHNUM FNAME           LNAME                CCNUM RESDATE
  1654 3132565356 Tyrone          Biggums               8420 2016-11-04
  1743 2484352574 Noah            Colon                 3345 2016-11-03
  1501 2487615478 Brennan         Luttrell              6426 2016-11-05
</code>```

Room:

```<code>ROOMNUM ROOMTYPE          GID

   101 Suite            1654
   103 Suite
   105 Suite            1743
   107 Suite
   108 Double           1501
   115 Double           1654
   117 Double
   130 Single           1501
   135 Single           1501
</code>```

Employee:

```<code>SSN       SUPERSSN  FNAME           LNAME                PHNUM       WAGE
123456789           Jim             Lahey           2464572367         40
532674246 123456789 Geno            Bianco          2463601456         15
837264268 123456789 Randy           Bobandy         2463603678         10
738643653 837264268 Corey           Trevor          2464326734          7
648753674 837264268 Joshua          Trussler        2464327535          8
</code>```

Maintains:

```<code>EMPLOYEES    ROOMNUM
648753674        101
648753674        115
738643653        101
738643653        105
738643653        108
738643653        130
738643653        135
837264268        107
</code>```

I am trying to write a query that would use relational division to select every employee who cleans every room reserved by a guest whose GID = 1654

The query I have written is as follows:

```<code>SELECT E.ssn, E.lname, E.fname
FROM employee E
WHERE NOT EXISTS((SELECT G.gid
                  FROM guest G
                  WHERE G.gid = 1654)
                  MINUS
                  (SELECT G.gid
                   FROM maintains M, room R, guest G
                   WHERE G.gid = R.gid
                   AND R.roomnum = M.roomnum
                   AND E.ssn = M.employeessn
                   AND G.gid = 1654));
</code>```

However, in it's current form it returns the following, which is incorrect:

```<code>SSN       LNAME           FNAME
738643653 Trevor          Corey
648753674 Trussler        Joshua
</code>```

Any and all help is appreciated, thank you.

答:
You could count all rooms and rooms maintained by employee and take only rows with equal values:

```<code>select distinct ssn, fname, lname
  from (select e.ssn, e.fname, e.lname,
               count(distinct r.roomnum) over () cnt_room,
               count(1) over (partition by e.ssn) cnt_ssn
          from room r
          join maintains m on m.roomnum = r.roomnum
          join employee e  on e.ssn = m.employeessn
          where gid = 1654)
  where cnt_room = cnt_ssn
</code>```

SQL Fiddle Demo

Result:

```<code>       SSN FNAME  LNAME
---------- ------ --------
 648753674 Joshua Trussler
</code>```

Title: Oracle Relational Division Query

Body:
I am trying to write a Relational Division query (I am required to use Relational Division for this)
Given the following tables:

Guest:

   GID      PHNUM FNAME           LNAME                CCNUM RESDATE
  1654 3132565356 Tyrone          Biggums               8420 2016-11-04
  1743 2484352574 Noah            Colon                 3345 2016-11-03
  1501 2487615478 Brennan         Luttrell              6426 2016-11-05

Room:

ROOMNUM ROOMTYPE          GID

   101 Suite            1654
   103 Suite
   105 Suite            1743
   107 Suite
   108 Double           1501
   115 Double           1654
   117 Double
   130 Single           1501
   135 Single           1501

Employee:

SSN       SUPERSSN  FNAME           LNAME                PHNUM       WAGE
123456789           Jim             Lahey           2464572367         40
532674246 123456789 Geno            Bianco          2463601456         15
837264268 123456789 Randy           Bobandy         2463603678         10
738643653 837264268 Corey           Trevor          2464326734          7
648753674 837264268 Joshua          Trussler        2464327535          8

Maintains:

EMPLOYEES    ROOMNUM
648753674        101
648753674        115
738643653        101
738643653        105
738643653        108
738643653        130
738643653        135
837264268        107

I am trying to write a query that would use relational division to select every employee who cleans every room reserved by a guest whose GID = 1654

The query I have written is as follows:

SELECT E.ssn, E.lname, E.fname
FROM employee E
WHERE NOT EXISTS((SELECT G.gid
                  FROM guest G
                  WHERE G.gid = 1654)
                  MINUS
                  (SELECT G.gid
                   FROM maintains M, room R, guest G
                   WHERE G.gid = R.gid
                   AND R.roomnum = M.roomnum
                   AND E.ssn = M.employeessn
                   AND G.gid = 1654));

However, in it's current form it returns the following, which is incorrect:

SSN       LNAME           FNAME
738643653 Trevor          Corey
648753674 Trussler        Joshua

Any and all help is appreciated, thank you.

Body:
You could count all rooms and rooms maintained by employee and take only rows with equal values:

select distinct ssn, fname, lname
  from (select e.ssn, e.fname, e.lname,
               count(distinct r.roomnum) over () cnt_room,
               count(1) over (partition by e.ssn) cnt_ssn
          from room r
          join maintains m on m.roomnum = r.roomnum
          join employee e  on e.ssn = m.employeessn
          where gid = 1654)
  where cnt_room = cnt_ssn

SQL Fiddle Demo

Result:

       SSN FNAME  LNAME
---------- ------ --------
 648753674 Joshua Trussler


问:
Calling an external API causes Bad Request if request contains JSON as a request parameter
I'm trying to integrate an external API to my Spring MVC application using RestTemplate.

It works perfectly fine unless I don't have to pass JSON as request parameter to API call. Such an attempt causes 400 Bad Request every time, and as far as I checked in the API logs, my JSON parameter isn't decoded by the API (it still looks like encoded String).

I think it might be related somehow to the headers in my request, but once I added Accept and Content-Type, the error is still the same. Could someone give me an advice what might be wrong with my implementation?

```<code>RestTemplate template = new RestTemplate();
MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
body.add("Content-Type", "application/json");
body.add("Accept", "application/json");

UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromHttpUrl(url);

String encodedParamValue = URLEncoder.encode(paramValue, "UTF-8");
urlBuilder.queryParam(requestParam, encodedParamValue);

HttpEntity<?> getRequest = new HttpEntity<>(body);

String response = template.exchange(urlBuilder.build().toString(), HttpMethod.GET, getRequest, String.class).getBody();
</code>```

Fact 1 I'm pretty sure that the URL my code produces after concatenating the API endpoint and request parameter is OK, because the documentation shows exactly the same URL for same parameters.

Fact 2 If I call a different endpoint that doesn't requires any parameters (just plain endpoint) then it works fine, so I assume that the way I call the API is OK.

Fact 3 Like I mentioned, the API logs show that the API "can't" translate (decode) the parameter to JSON once I encoded it URLEncoder.encode(paramValue, "UTF-8").

答:
You can folow this:</p>

```<code> try {
        .......
        .......
        HttpHeaders headers = new HttpHeaders();
        headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
        // Set more header params as required ....
        HttpEntity entity = new HttpEntity<>(headers);

        RestTemplate restTemplate = new RestTemplate();
        response = restTemplate.exchange(url, HttpMethod.GET, entity, type);

        if(response.getStatusCode() == HttpStatus.OK) {
             //TODO: Need to modify response according to the demand
            if(response.getBody().getOk().equals("true") && response.getBody().getMessage() == null) {
                response.getBody().setMessage(successMessage);
            }

        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    .......
    .......
</code>```

Body:
I'm trying to integrate an external API to my Spring MVC application using RestTemplate.

It works perfectly fine unless I don't have to pass JSON as request parameter to API call. Such an attempt causes 400 Bad Request every time, and as far as I checked in the API logs, my JSON parameter isn't decoded by the API (it still looks like encoded String).

I think it might be related somehow to the headers in my request, but once I added Accept and Content-Type, the error is still the same. Could someone give me an advice what might be wrong with my implementation?

RestTemplate template = new RestTemplate();
MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
body.add("Content-Type", "application/json");
body.add("Accept", "application/json");

UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromHttpUrl(url);

String encodedParamValue = URLEncoder.encode(paramValue, "UTF-8");
urlBuilder.queryParam(requestParam, encodedParamValue);

HttpEntity<?> getRequest = new HttpEntity<>(body);

String response = template.exchange(urlBuilder.build().toString(), HttpMethod.GET, getRequest, String.class).getBody();

Fact 1 I'm pretty sure that the URL my code produces after concatenating the API endpoint and request parameter is OK, because the documentation shows exactly the same URL for same parameters.

Fact 2 If I call a different endpoint that doesn't requires any parameters (just plain endpoint) then it works fine, so I assume that the way I call the API is OK.

Fact 3 Like I mentioned, the API logs show that the API "can't" translate (decode) the parameter to JSON once I encoded it URLEncoder.encode(paramValue, "UTF-8").

Body:
You can folow this:

 try {
        .......
        .......
        HttpHeaders headers = new HttpHeaders();
        headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
        // Set more header params as required ....
        HttpEntity entity = new HttpEntity<>(headers);

        RestTemplate restTemplate = new RestTemplate();
        response = restTemplate.exchange(url, HttpMethod.GET, entity, type);

        if(response.getStatusCode() == HttpStatus.OK) {
             //TODO: Need to modify response according to the demand
            if(response.getBody().getOk().equals("true") && response.getBody().getMessage() == null) {
                response.getBody().setMessage(successMessage);
            }

        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    .......
    .......


问:
Build containers for dev and production environment
How do you build images for development and for production(swarm):

I am trying to have one Dockerfile for both to keep "Dockerfile implementation in one place" like inheritance:

```<code>FROM golang AS gobase
ENV APP_ENV "pro"
COPY ./app /go/src/github.com/user/myProject/app
WORKDIR /go/src/github.com/user/myProject/app

RUN go get ./
RUN go build
EXPOSE 8080

FROM gobase AS godev

ENV APP_ENV "dev"

RUN go get github.com/pilu/fresh
RUN go-wrapper download
RUN go-wrapper install

CMD [ "fresh" ]
</code>```

And then use docker-compose.dev.yml & docker-compose.pro.yml

Like for docker-compose.dev.yml:

```<code>version: '2'

services:
  godev:
    environment:
      - APP_ENV="dev"
    image: godev
</code>```

So first of all, the naming is not working.

Bonus question: how to you build an image for production - do you just compile in one container(docker run) and then copy the binary to a new container?

答:
Don't use dev as a name, but as a tag:

```<code>go:dev
go:prod
</code>```

and your compose.yml:

```<code>services:
  go:
    image: go:dev
</code>```

Bonus: Have a look at this answer under "Edit 29/06/17" and use this build step for both (dev and prod)

Body:
How do you build images for development and for production(swarm):

I am trying to have one Dockerfile for both to keep "Dockerfile implementation in one place" like inheritance:

FROM golang AS gobase
ENV APP_ENV "pro"
COPY ./app /go/src/github.com/user/myProject/app
WORKDIR /go/src/github.com/user/myProject/app

RUN go get ./
RUN go build
EXPOSE 8080

FROM gobase AS godev

ENV APP_ENV "dev"

RUN go get github.com/pilu/fresh
RUN go-wrapper download
RUN go-wrapper install

CMD [ "fresh" ]

And then use docker-compose.dev.yml & docker-compose.pro.yml

Like for docker-compose.dev.yml:

version: '2'

services:
  godev:
    environment:
      - APP_ENV="dev"
    image: godev

So first of all, the naming is not working.

Bonus question: how to you build an image for production - do you just compile in one container(docker run) and then copy the binary to a new container?

Body:
Don't use dev as a name, but as a tag:

go:dev
go:prod

and your compose.yml:

services:
  go:
    image: go:dev

Bonus: Have a look at this answer under "Edit 29/06/17" and use this build step for both (dev and prod)


问:
scanf: "%[^\n]" skips the 2nd input but " %[^\n]" does not. why?
Consider the following code:

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

int main (void)
{
  char str1[128], str2[128], str3[128];

  printf ("\nEnter str1: ");
  scanf ("%[^\n]", str1);
  printf ("\nstr1 = %s", str1);

  printf ("\nEnter str2: ");
  scanf ("%[^\n]", str2);
  printf ("\nstr2 = %s", str2);

  printf ("\nEnter str3: ");
  scanf ("%[^\n]", str3);
  printf ("\nstr3 = %s", str3);

  printf ("\n");
  return 0;
}
</code>```

When it is executed only the first scanf stops for the prompt. The program does not stop for the next scanf s. But if the format string is changed from "%[^\n]" to " %[^\n]" (note the blank space before %), then it works okay. Does some existing newline character from the previous input buffer is automatically accepted ? But flushing stdin does not solve this.

What is the cause of this.

答: Just use a getchar() after the scanf() function. </p>

Body:
Consider the following code:

#include <stdio.h>

int main (void)
{
  char str1[128], str2[128], str3[128];

  printf ("\nEnter str1: ");
  scanf ("%[^\n]", str1);
  printf ("\nstr1 = %s", str1);

  printf ("\nEnter str2: ");
  scanf ("%[^\n]", str2);
  printf ("\nstr2 = %s", str2);

  printf ("\nEnter str3: ");
  scanf ("%[^\n]", str3);
  printf ("\nstr3 = %s", str3);

  printf ("\n");
  return 0;
}

When it is executed only the first scanf stops for the prompt. The program does not stop for the next scanf s. But if the format string is changed from "%[^\n]" to " %[^\n]" (note the blank space before %), then it works okay. Does some existing newline character from the previous input buffer is automatically accepted ? But flushing stdin does not solve this.

What is the cause of this.


问:
kotlin delegate property ,In a get() method how i can access the value?
Kotlin has delegated properties which is a very nice feature. But I am figuring out how to get and set the values. Let's say I want to get value of the property which is delegated.  In a get() method how i can access the value?

Here's an example of how I have implemented:

```<code>class Example() {
    var p: String by DelegateExample()
}
class DelegateExample {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        return "${property.name} "
    }

  operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
    println("${value.trim()} '${property.name.toUpperCase()} '")
   }
}
fun delegate(): String {
    val e = Example()
    e.p = "NEW"
    return e.p
}
</code>```

The main question I am unable to understand is, How can I set the value to the actual property on which the delegation class is assigned. When I assign "NEW" to property p, how can I store that value to the variable p or read that new value passed on to p with get? Am I missing something basic here? Any help will be much appreciated. Thanks in advance.

答:
Just create property in delegate which will hold the value

```<code>class DelegateExample {

    private var value: String? = null

    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        return value ?: throw IllegalStateException("Initalize me!")
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
        this.value = value
    }
}
</code>```

To clarify - delegates aren't values holder, they are handlers of get/set operations. You can take a look how it works under the hood if you decompile your Example class (Tools -> Kotlin -> Show Kotlin bytecode -> Decompile).

```<code>public final class Example {
   // $FF: synthetic field
   static final KProperty[] $$delegatedProperties = ...

   @NotNull
   private final DelegateExample p$delegate = new DelegateExample();

   @NotNull
   public final String getP() {
       return (String)this.p$delegate.getValue(this, $$delegatedProperties[0]);
   }

   public final void setP(@NotNull String var1) {
       Intrinsics.checkParameterIsNotNull(var1, "<set-?>");
       this.p$delegate.setValue(this, $$delegatedProperties[0], var1);
   }
}
</code>```

No magic here, just creating instance of the DelegateExample and its get/set method invoking

Body:
Kotlin has delegated properties which is a very nice feature. But I am figuring out how to get and set the values. Let's say I want to get value of the property which is delegated.  In a get() method how i can access the value?

Here's an example of how I have implemented:

class Example() {
    var p: String by DelegateExample()
}
class DelegateExample {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        return "${property.name} "
    }

  operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
    println("${value.trim()} '${property.name.toUpperCase()} '")
   }
}
fun delegate(): String {
    val e = Example()
    e.p = "NEW"
    return e.p
}

The main question I am unable to understand is, How can I set the value to the actual property on which the delegation class is assigned. When I assign "NEW" to property p, how can I store that value to the variable p or read that new value passed on to p with get? Am I missing something basic here? Any help will be much appreciated. Thanks in advance.

Body:
Just create property in delegate which will hold the value

class DelegateExample {

    private var value: String? = null

    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        return value ?: throw IllegalStateException("Initalize me!")
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
        this.value = value
    }
}

To clarify - delegates aren't values holder, they are handlers of get/set operations. You can take a look how it works under the hood if you decompile your Example class (Tools -> Kotlin -> Show Kotlin bytecode -> Decompile).

public final class Example {
   // $FF: synthetic field
   static final KProperty[] $$delegatedProperties = ...

   @NotNull
   private final DelegateExample p$delegate = new DelegateExample();

   @NotNull
   public final String getP() {
       return (String)this.p$delegate.getValue(this, $$delegatedProperties[0]);
   }

   public final void setP(@NotNull String var1) {
       Intrinsics.checkParameterIsNotNull(var1, "<set-?>");
       this.p$delegate.setValue(this, $$delegatedProperties[0], var1);
   }
}

No magic here, just creating instance of the DelegateExample and its get/set method invoking


问:
How do i get the url (window.location) of the current request in Angular 5?
How do i get the url of the current request in Angular 5?

I tried a couple of solutions i found online but nothing seems to work.
- $window
- Wrapping native window in WindowRef example

I've been looking for this all morning, but kinda new to Angular and get lost in the different examples online targeting different versions of Angular.

UPDATE: I'm using TypeScript

Thanks

答:
If you want the angular solution you could use this.

```<code>import { Router } from '@angular/router';

constructor(private router:Router) {}

someMethod(){
  console.log(this.router.url)
}
</code>```

else you could use the standard window solution

window.location.href returns the href (URL) of the current page.

Body:
If you want the angular solution you could use this.

import { Router } from '@angular/router';

constructor(private router:Router) {}

someMethod(){
  console.log(this.router.url)
}

else you could use the standard window solution

window.location.href returns the href (URL) of the current page.


问:
Picasso doesn't tolerate empty String URL?
I have a viewHolder that loads up an image using Picasso. The DB will return a path of URL as String. So I have my code as below (Using Kotlin)

```<code>  Picasso.with(context).load(url).error(placeholder).transform(transformation)
            .placeholder(placeholder).into(this)
</code>```

It loads fine. However, sometimes the URL is empty. I'm expecting it to load the placeholder instead. But it crash out as below

```<code>java.lang.IllegalArgumentException: Path must not be empty.
    at com.squareup.picasso.Picasso.load(Picasso.java:297)
</code>```

This would force me to explicitly do a check, which is not ideal

```<code>if (url == null || url.isEmpty()) {
    Picasso.with(context).load(placeholder).transform(transformation).into(this)
} else {
    Picasso.with(context).load(url).error(placeholder).transform(transformation)
            .placeholder(placeholder).into(this)
}
</code>```

Is this expected that Picasso will crash when a URL String is empty instead of loading the placeholder?

答:
This might be too late but i encountered this error today and after read the documentation of Picasso#load method it states that passing empty or blank string will cause the method to throw IllegalArgumentException and passing a null will not throw an exception but trigger RequestCreator#error which will load error image if one is provided otherwise the target will display nothing.

if you have no control over the image url (say its coming from server) you can try the following:

```<code> mPicasso.load(photo.isEmpty() ? null : photo)
                .placeholder(placeholder)
                .error(error_placeholder)
                .into(target);
</code>```

Body:
I have a viewHolder that loads up an image using Picasso. The DB will return a path of URL as String. So I have my code as below (Using Kotlin)

  Picasso.with(context).load(url).error(placeholder).transform(transformation)
            .placeholder(placeholder).into(this)

It loads fine. However, sometimes the URL is empty. I'm expecting it to load the placeholder instead. But it crash out as below

java.lang.IllegalArgumentException: Path must not be empty.
    at com.squareup.picasso.Picasso.load(Picasso.java:297)

This would force me to explicitly do a check, which is not ideal

if (url == null || url.isEmpty()) {
    Picasso.with(context).load(placeholder).transform(transformation).into(this)
} else {
    Picasso.with(context).load(url).error(placeholder).transform(transformation)
            .placeholder(placeholder).into(this)
}

Is this expected that Picasso will crash when a URL String is empty instead of loading the placeholder?

Body:
This might be too late but i encountered this error today and after read the documentation of Picasso#load method it states that passing empty or blank string will cause the method to throw IllegalArgumentException and passing a null will not throw an exception but trigger RequestCreator#error which will load error image if one is provided otherwise the target will display nothing.

if you have no control over the image url (say its coming from server) you can try the following:

 mPicasso.load(photo.isEmpty() ? null : photo)
                .placeholder(placeholder)
                .error(error_placeholder)
                .into(target);


问:
How to reset CSS animations in Vue
I have a list like this:

var v = new Vue({
  'el' : '#app',
  'data' : {
    'list' : [1,2,3,4,5,6,7,8,9,10]
  },

  methods: {
    activateClass($event){
      $event.target.classList.remove('animate');
      void $event.target.offsetWidth;
      $event.target.classList.add('animate');
    },
    changeRandomValue(){
      var randomAmount = Math.round(Math.random() * 12);
      var randomIndex = Math.floor(Math.random() * this.list.length);
      Vue.set(this.list, randomIndex, randomAmount)
    }
  },

  mounted(){
    var vm = this;
    setInterval(function(){
      vm.changeRandomValue();
    }, 500);
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.animate{
  animation: fade 0.5s;
}

@keyframes fade{
  0% { background:blue; }
  100% { background:white; }
}</code>```

```
</div>
</div>
</p>
<p>If you run the above snippet, you'll see that if you click an li it will use this code:</p>
```activateClass($event){
  $event.target.classList.remove('animate');
  void $event.target.offsetWidth;
  $event.target.classList.add('animate');
}
```
<p>To add a class to it once and play an animation (https://css-tricks.com/restart-css-animation/). Awesome!</p>
<p>Now, I also have a <code>changeRandomValue()</code> function that selects one element from the list array and change its value.</p>
<h3>How would I use the <code>activateClass</code> method from inside of the <code>changeRandomValue</code> method?</h3>
<p>I've had a few thoughts about using events on the element, so it would be something like:</p>
```

```

But I don't think anything like that exists. I have also been looking into watchers but I don't think this is really what they are for.

I have no problem taking the element that has been clicked and finding the data that it is referencing, but I can't work out how to take the data that has been changed and then find its dom reference.

The reason I'm not using class bindings is that I need to trigger a reflow. Maybe there is a really easy way to do that with vue, but I'm not aware of it.

答:
One easy solution would be to use class bindings and the animationend event.

You can also trigger the same solution programmatically, as shown in the mounted event.

new Vue({
  el: '#app',
  data: {
    items: [{
      id: 1,
      highlight: false
    }, {
      id: 2,
      highlight: false
    }]
  },
  mounted() {
    // Demonstrate programmatic highlighting
    setTimeout(() => {
      this.items[1].highlight = true
      setTimeout(() => {
        this.items[1].highlight = true
      }, 1000)
    }, 1000)
  },
  methods: {
    addClass(item) {
      item.highlight = true
    },
    removeClass(item) {
      item.highlight = false
    }
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p {
  cursor: pointer;
}

.animate {
  animation: fade 0.5s;
}

@keyframes fade {
  0% {
    background: blue;
  }
  100% {
    background: white;
  }
}</code>```

{{ item.id }}

```

Title: How to reset CSS animations in Vue

Body:
I have a list like this:

var v = new Vue({
  'el' : '#app',
  'data' : {
    'list' : [1,2,3,4,5,6,7,8,9,10]
  },

  methods: {
    activateClass($event){
      $event.target.classList.remove('animate');
      void $event.target.offsetWidth;
      $event.target.classList.add('animate');
    },
    changeRandomValue(){
      var randomAmount = Math.round(Math.random() * 12);
      var randomIndex = Math.floor(Math.random() * this.list.length);
      Vue.set(this.list, randomIndex, randomAmount)
    }
  },

  mounted(){
    var vm = this;
    setInterval(function(){
      vm.changeRandomValue();
    }, 500);
  }
})

.animate{
  animation: fade 0.5s;
}

@keyframes fade{
  0% { background:blue; }
  100% { background:white; }
}

If you run the above snippet, you'll see that if you click an li it will use this code:

activateClass($event){
  $event.target.classList.remove('animate');
  void $event.target.offsetWidth;
  $event.target.classList.add('animate');
}

To add a class to it once and play an animation (https://css-tricks.com/restart-css-animation/). Awesome!

Now, I also have a changeRandomValue() function that selects one element from the list array and change its value.

How would I use the activateClass method from inside of the changeRandomValue method?

I've had a few thoughts about using events on the element, so it would be something like:

But I don't think anything like that exists. I have also been looking into watchers but I don't think this is really what they are for.

I have no problem taking the element that has been clicked and finding the data that it is referencing, but I can't work out how to take the data that has been changed and then find its dom reference.

The reason I'm not using class bindings is that I need to trigger a reflow. Maybe there is a really easy way to do that with vue, but I'm not aware of it.

Body:
One easy solution would be to use class bindings and the animationend event.

You can also trigger the same solution programmatically, as shown in the mounted event.

new Vue({
  el: '#app',
  data: {
    items: [{
      id: 1,
      highlight: false
    }, {
      id: 2,
      highlight: false
    }]
  },
  mounted() {
    // Demonstrate programmatic highlighting
    setTimeout(() => {
      this.items[1].highlight = true
      setTimeout(() => {
        this.items[1].highlight = true
      }, 1000)
    }, 1000)
  },
  methods: {
    addClass(item) {
      item.highlight = true
    },
    removeClass(item) {
      item.highlight = false
    }
  }
})

p {
  cursor: pointer;
}

.animate {
  animation: fade 0.5s;
}

@keyframes fade {
  0% {
    background: blue;
  }
  100% {
    background: white;
  }
}

<script src="https://unpkg.com/vue@2"></script>

<div id="app">
  <p v-for="item in items" v-bind:class="{ animate: item.highlight }" v-on:click="addClass(item)" v-on:animationend="removeClass(item)">{{ item.id }}</p>
</div>


问:
phpdoc on a mvc project with codeigniter
i developed a project in Codeigniter following the MVC pattern.

That means that , for example, i have a controller called Items , which call a model called Items_model ,which get files from database and finally those those file are passed to a view called Item_view.

Now i need to document it, and im trying to use phpdoc.

My main question is about how to , inside the explanation of a function  in a controller, link the behaviour of that function with a model and the view in a functional way, not just write the names in plain text.
i was reading about packages, but dont know how to use it properly

i hope you can help, im very noob with phpdoc.

thanks in advance and sorry for my english.

Sverd.

答:
I think that PHPDoc doesn't support this type of integration with CodeIgniter. Probably you should use PHPDoc and modify manually the documentation created.

Anyways, using CodeIgniter and renaming correctly all the files, you shouldn't have any problem:

```<code>Controller -> controllers/home.php
Model -> models/home.php
View -> home.php
</code>```

If you specify that you're using CodeIgniter (which uses MVC pattern), the documentation explains by itself.

PS:

One 'googled' link (I haven't read it completely):

http://codeigniter.com/forums/viewthread/58302/

Body:
I think that PHPDoc doesn't support this type of integration with CodeIgniter. Probably you should use PHPDoc and modify manually the documentation created.

Anyways, using CodeIgniter and renaming correctly all the files, you shouldn't have any problem:

Controller -> controllers/home.php
Model -> models/home.php
View -> home.php

If you specify that you're using CodeIgniter (which uses MVC pattern), the documentation explains by itself.

PS:

One 'googled' link (I haven't read it completely):

http://codeigniter.com/forums/viewthread/58302/


问:
For-loop in R to create a new file (but gives incorrect/unexpected output)
I'm currently busy with some data and I need to check their validity.
Therefore, I would like to use a for-loop to go through all my data files.
In this for-loop, I would like to calculate some things (like mean, min,max...).

My code below works but produced an incorrectly written csv file. The problem occurs after the calculations (and their values) are done during csv file creation. CSV:

```<code>"c.1..1..1004.89081855716..630.174466667434..461.738905906677.." "c.1..1..950.990843858612..479.98560814955..517.955102920532.."
1 1
1 1
1004.89081855716 950.990843858612
630.174466667434 479.98560814955
461.738905906677 517.955102920532
1535.86795806885 1452.30199813843
-13.3948961645365 3.72026950120926
1259.26423788071 1159.17089223862
</code>```

Approach/What I'm expecting:
So I start from some data files with eye tracking data in it.
As you can see at the beginning of the code, I try to get some values out of this eye tracking data (validity, new file with only validity == 1 data...). Once I created the filtered_data dataframe, I want to calculate some extra values out of it (mean, sd, min/max).
My plan is to create a new csv file (validity_loop.csv) in which I can find all my calculations (validity_left, validity_right,mean_eye_x, mean_eye_y, min_eye_x,max_eye_x,min_eye_y,max_eye_y). All in a row. One row for each data set (file_list[i]).

Can someone help me in how to tackle and solve this issue?

Here is my code:

```<code>set <- setwd("/Users/Sarah/Documents")

file_list <- list.files(set, pattern = ".csv", all.files = TRUE)
validity_list <- data_list <- vector("list", "length" = length(file_list))

for(i in seq_along(file_list)){

  filename = file_list[i]

  #read files

  data_frame = read.csv(filename, sep = ",", dec = ".",
                        header = TRUE,
                        stringsAsFactors = FALSE)

  #what has to be done
  #validity

  validity_left <- mean(is.numeric(data_frame$left_gaze_point_validity))
  validity_right <-mean(is.numeric(data_frame$right_gaze_point_validity))

  #Zuiver dataframe (validity ==1)

  to_keep = which(data_frame$left_gaze_point_validity == 1 &
                  data_frame$right_gaze_point_validity==1)

  filtered_data = data_frame[to_keep,]
  filtered_data$left_eye_x = as.numeric(filtered_data$left_eye_x)
  filtered_data$left_eye_y = as.numeric(filtered_data$left_eye_y)
  filtered_data$right_eye_x = as.numeric(filtered_data$right_eye_x)
  filtered_data$right_eye_y = as.numeric(filtered_data$right_eye_y)

  #1 eye-data

  filtered_data$eye_x <- (filtered_data$left_eye_x+filtered_data$right_eye_x)/2
  filtered_data$eye_y <- (filtered_data$left_eye_y+filtered_data$right_eye_y)/2

  #Pixels

  filtered_data$eye_x <- (filtered_data$eye_x)*1920
  filtered_data$eye_y <- (filtered_data$eye_y)*1080

  #SD and Mean + min-max

  mean_eye_x<- mean(filtered_data$eye_x)
  mean_eye_y <- mean(filtered_data$eye_y)

  sd_eye_x <- sd(filtered_data$eye_x)
  sd_eye_y <- sd(filtered_data$eye_y)

  min_eye_x <- min(filtered_data$eye_x)
  min_eye_y <- min(filtered_data$eye_y)
  max_eye_x <- max(filtered_data$eye_x)
  max_eye_y <- max(filtered_data$eye_y)

  #add everything to new file

  validity_list[[i]] <- c(validity_left, validity_right,
                          mean_eye_x, mean_eye_y,
                          min_eye_x, min_eye_y,
                          max_eye_x, max_eye_y)

}

#new document
write.table(validity_list,
            file = "Master T&O/Thesis /Loop/Validity/validity_loop.csv",
            col.names = TRUE, row.names = FALSE)
</code>```

答:
I managed to get a new data frame in R, which contains the value of my validity_list as a matrix form.

```<code>#FOR LOOP poging 2
set <- setwd("/Users/Sarah/Documents/Master T&O/Thesis /Loop")

file_list <- list.files(set, pattern = ".csv", all.files = TRUE)
validity_list <- vector("list", "length" = length(file_list))

for(i in seq_along(file_list)){
  filename = file_list[i]
  #read files
  data_frame = read.csv(filename, sep = ",", dec = ".", header = TRUE, stringsAsFactors = FALSE)
  #what has to be done
  #validity
  validity_left <- mean(is.numeric(data_frame$left_gaze_point_validity))
  validity_right <-mean(is.numeric(data_frame$right_gaze_point_validity))
  #Zuiver dataframe (validity ==1)
  to_keep = which(data_frame$left_gaze_point_validity == 1 & data_frame$right_gaze_point_validity==1)

  filtered_data = data_frame[to_keep,]
  filtered_data$left_eye_x = as.numeric(filtered_data$left_eye_x)
  filtered_data$left_eye_y = as.numeric(filtered_data$left_eye_y)
  filtered_data$right_eye_x = as.numeric(filtered_data$right_eye_x)
  filtered_data$right_eye_y = as.numeric(filtered_data$right_eye_y)
  #1 eye-data
  filtered_data$eye_x <- (filtered_data$left_eye_x+filtered_data$right_eye_x)/2
  filtered_data$eye_y <- (filtered_data$left_eye_y+filtered_data$right_eye_y)/2
  #Pixels
  filtered_data$eye_x <- (filtered_data$eye_x)*1920
  filtered_data$eye_y <- (filtered_data$eye_y)*1080
  #SD and Mean + min-max
  mean_eye_x<- mean(filtered_data$eye_x)
  mean_eye_y <- mean(filtered_data$eye_y)

  sd_eye_x <- sd(filtered_data$eye_x)
  sd_eye_y <- sd(filtered_data$eye_y)

  min_eye_x <- min(filtered_data$eye_x)
  min_eye_y <- min(filtered_data$eye_y)
  max_eye_x <- max(filtered_data$eye_x)
  max_eye_y <- max(filtered_data$eye_y)

  #add everything to new file
  validity_list[[i]] <- c(validity_left, validity_right,mean_eye_x, mean_eye_y, min_eye_x,max_eye_x,min_eye_y,max_eye_y)
  validity_matrix <- matrix(unlist(validity_list), ncol = 8, byrow = TRUE)
}

#new document
write.table(validity_matrix, file = "/Users/Sarah/Documents/Master T&O/Thesis /Loop/Validity/validity_loop.csv", dec = ".")
</code>```

The only problem I have now, is the fact that my values for the validity_list items are wrong, but that's another problem and I'm trying to fix it!

Body:
I'm currently busy with some data and I need to check their validity.
Therefore, I would like to use a for-loop to go through all my data files.
In this for-loop, I would like to calculate some things (like mean, min,max...).

My code below works but produced an incorrectly written csv file. The problem occurs after the calculations (and their values) are done during csv file creation. CSV:

"c.1..1..1004.89081855716..630.174466667434..461.738905906677.." "c.1..1..950.990843858612..479.98560814955..517.955102920532.."
1 1
1 1
1004.89081855716 950.990843858612
630.174466667434 479.98560814955
461.738905906677 517.955102920532
1535.86795806885 1452.30199813843
-13.3948961645365 3.72026950120926
1259.26423788071 1159.17089223862

Approach/What I'm expecting:
So I start from some data files with eye tracking data in it.
As you can see at the beginning of the code, I try to get some values out of this eye tracking data (validity, new file with only validity == 1 data...). Once I created the filtered_data dataframe, I want to calculate some extra values out of it (mean, sd, min/max).
My plan is to create a new csv file (validity_loop.csv) in which I can find all my calculations (validity_left, validity_right,mean_eye_x, mean_eye_y, min_eye_x,max_eye_x,min_eye_y,max_eye_y). All in a row. One row for each data set (file_list[i]).

Can someone help me in how to tackle and solve this issue?

Here is my code:

set <- setwd("/Users/Sarah/Documents")

file_list <- list.files(set, pattern = ".csv", all.files = TRUE)
validity_list <- data_list <- vector("list", "length" = length(file_list))

for(i in seq_along(file_list)){

  filename = file_list[i]

  #read files

  data_frame = read.csv(filename, sep = ",", dec = ".",
                        header = TRUE,
                        stringsAsFactors = FALSE)

  #what has to be done
  #validity

  validity_left <- mean(is.numeric(data_frame$left_gaze_point_validity))
  validity_right <-mean(is.numeric(data_frame$right_gaze_point_validity))

  #Zuiver dataframe (validity ==1)

  to_keep = which(data_frame$left_gaze_point_validity == 1 &
                  data_frame$right_gaze_point_validity==1)

  filtered_data = data_frame[to_keep,]
  filtered_data$left_eye_x = as.numeric(filtered_data$left_eye_x)
  filtered_data$left_eye_y = as.numeric(filtered_data$left_eye_y)
  filtered_data$right_eye_x = as.numeric(filtered_data$right_eye_x)
  filtered_data$right_eye_y = as.numeric(filtered_data$right_eye_y)

  #1 eye-data

  filtered_data$eye_x <- (filtered_data$left_eye_x+filtered_data$right_eye_x)/2
  filtered_data$eye_y <- (filtered_data$left_eye_y+filtered_data$right_eye_y)/2

  #Pixels

  filtered_data$eye_x <- (filtered_data$eye_x)*1920
  filtered_data$eye_y <- (filtered_data$eye_y)*1080

  #SD and Mean + min-max

  mean_eye_x<- mean(filtered_data$eye_x)
  mean_eye_y <- mean(filtered_data$eye_y)

  sd_eye_x <- sd(filtered_data$eye_x)
  sd_eye_y <- sd(filtered_data$eye_y)

  min_eye_x <- min(filtered_data$eye_x)
  min_eye_y <- min(filtered_data$eye_y)
  max_eye_x <- max(filtered_data$eye_x)
  max_eye_y <- max(filtered_data$eye_y)

  #add everything to new file

  validity_list[[i]] <- c(validity_left, validity_right,
                          mean_eye_x, mean_eye_y,
                          min_eye_x, min_eye_y,
                          max_eye_x, max_eye_y)

}

#new document
write.table(validity_list,
            file = "Master T&O/Thesis /Loop/Validity/validity_loop.csv",
            col.names = TRUE, row.names = FALSE)

Body:
I managed to get a new data frame in R, which contains the value of my validity_list as a matrix form.

#FOR LOOP poging 2
set <- setwd("/Users/Sarah/Documents/Master T&O/Thesis /Loop")

file_list <- list.files(set, pattern = ".csv", all.files = TRUE)
validity_list <- vector("list", "length" = length(file_list))

for(i in seq_along(file_list)){
  filename = file_list[i]
  #read files
  data_frame = read.csv(filename, sep = ",", dec = ".", header = TRUE, stringsAsFactors = FALSE)
  #what has to be done
  #validity
  validity_left <- mean(is.numeric(data_frame$left_gaze_point_validity))
  validity_right <-mean(is.numeric(data_frame$right_gaze_point_validity))
  #Zuiver dataframe (validity ==1)
  to_keep = which(data_frame$left_gaze_point_validity == 1 & data_frame$right_gaze_point_validity==1)

  filtered_data = data_frame[to_keep,]
  filtered_data$left_eye_x = as.numeric(filtered_data$left_eye_x)
  filtered_data$left_eye_y = as.numeric(filtered_data$left_eye_y)
  filtered_data$right_eye_x = as.numeric(filtered_data$right_eye_x)
  filtered_data$right_eye_y = as.numeric(filtered_data$right_eye_y)
  #1 eye-data
  filtered_data$eye_x <- (filtered_data$left_eye_x+filtered_data$right_eye_x)/2
  filtered_data$eye_y <- (filtered_data$left_eye_y+filtered_data$right_eye_y)/2
  #Pixels
  filtered_data$eye_x <- (filtered_data$eye_x)*1920
  filtered_data$eye_y <- (filtered_data$eye_y)*1080
  #SD and Mean + min-max
  mean_eye_x<- mean(filtered_data$eye_x)
  mean_eye_y <- mean(filtered_data$eye_y)

  sd_eye_x <- sd(filtered_data$eye_x)
  sd_eye_y <- sd(filtered_data$eye_y)

  min_eye_x <- min(filtered_data$eye_x)
  min_eye_y <- min(filtered_data$eye_y)
  max_eye_x <- max(filtered_data$eye_x)
  max_eye_y <- max(filtered_data$eye_y)

  #add everything to new file
  validity_list[[i]] <- c(validity_left, validity_right,mean_eye_x, mean_eye_y, min_eye_x,max_eye_x,min_eye_y,max_eye_y)
  validity_matrix <- matrix(unlist(validity_list), ncol = 8, byrow = TRUE)
}

#new document
write.table(validity_matrix, file = "/Users/Sarah/Documents/Master T&O/Thesis /Loop/Validity/validity_loop.csv", dec = ".")

The only problem I have now, is the fact that my values for the validity_list items are wrong, but that's another problem and I'm trying to fix it!


问:
Adding reference of another external project in a solution
Using: .net core mvc c#

I have a solution which has a .net mvc core web app & one class library. There is a shared project (class library) that I want to this solution
which is a part of different project (different solution as well).

All of these projects are stored in our local GIT repository.

If I add the external project as project dependency in my existing project then there would be 2 copies of the external project that we have to
maintain. If some developer updates external project how does the change propogates to other projects using it.
And there could be that some developer updates the external project when under its local solution which we want to prevent. Since all are in GIT
is it possible somehow to make dependency related so that any change in external is known to others.

So basically how can we prevent anyone to make local updates to the external project but also make sure any updates to external project are available to
any other project using them.

答:
There are several approaches that you can use to achieve this.

Quick: Reference project in two solutions

The quickest is to reference the shared project from both solutions. This way, you can use it in both projects and the changes are propagated to the other solution because you are basically working on the same files. However, a huge drawback of this approach is that if you make changes in solution A that are not compatible with solution B (e.g. removing a method that is used in solution B), you will only find out when working on solution B.

Easy: Single solution

To fix this, you could merge the solutions into a single one that contains the shared proect and also the other projects from solutions A & B. This way, you still get the convenience of project references in a solution. In addition, you are notified about breaking changes immediately if you build the complete solution. If this approach is viable for you in terms of solution size and team structure, I'd favor this approach. As you already share a single Git repository, I think this approach is well worth considering.

Nuget Package

If you want to keep the solutions strictly separated, you'd need to follow a more complex procedure. You could for instance move the shared project into a solution of its own and create a Nuget package with a clear build and versioning strategy. You can host the Nuget package on a package feed (e.g. on Visual Studio Team Services). Solutions A and B can then reference the Nuget package from the feed and also update it if a new version becomes available.

Here the official documentation to create nuget package with nuspec or csproj

Create .NET Standard 2.0 packages with Visual Studio 2017 [CSPROJ]

Creating NuGet packages [NUSPEC]


问:
Getting Uncaught TypeError: Cannot read property 'substring' of undefined
```<code>   (function( $ ) {
     $(document).ready( function(){
       $('form.wpcf7-form input').each(function(){
         //or you could also do this which is even less maintenance
         var name = $(this).attr('name').substring(0, 10);
         var type = $(this).attr('type');
         switch(type){
           case 'radio':
            case 'checkbox':
             name += '-'+$(this).attr('value');
         }
         $(this).attr('class',name);
       });
     });
   })( jQuery );
</code>```

I try to cut the class name but I am getting Uncaught TypeError: Cannot read property 'substring' of undefined error.

Can some one help me get this error fixed?

Thanks!

答:
As several people have commented, you get the error of undefined, because one of the input elements on you page doesn't have a name attribute. This breaks the script and prevents it from running.

You have to do a conditional check to see if the name attribute is present. Something like this would work:

```<code>$('form.wpcf7-form input[type="checkbox"]').each(function() {
    $(this).addClass( ( ( $(this).attr('name') ) ? $(this).attr('name').substring(0, 10) + '-' + $(this).val() : null ) );
});
</code>```

Body:
   (function( $ ) {
     $(document).ready( function(){
       $('form.wpcf7-form input').each(function(){
         //or you could also do this which is even less maintenance
         var name = $(this).attr('name').substring(0, 10);
         var type = $(this).attr('type');
         switch(type){
           case 'radio':
            case 'checkbox':
             name += '-'+$(this).attr('value');
         }
         $(this).attr('class',name);
       });
     });
   })( jQuery );

I try to cut the class name but I am getting Uncaught TypeError: Cannot read property 'substring' of undefined error.

Can some one help me get this error fixed?

Thanks!

Body:
As several people have commented, you get the error of undefined, because one of the input elements on you page doesn't have a name attribute. This breaks the script and prevents it from running.

You have to do a conditional check to see if the name attribute is present. Something like this would work:

$('form.wpcf7-form input[type="checkbox"]').each(function() {
    $(this).addClass( ( ( $(this).attr('name') ) ? $(this).attr('name').substring(0, 10) + '-' + $(this).val() : null ) );
});


问:
Insert Path of a file with \\ in mysql using java
I am making a standalone application using java,and in that i need to insert the path of the image that user chooses from file chooser.
I am getting the path of the file but when i store it in the database(mysql) it doesn't stores the \,so when i retrieve that path,the file doesn't show up.

How to store the path of file with \\ so that one gets escaped using java code?

i tried using replaceall method but its giving an error of illegal character set.

```<code>filename.replaceall("\","\\");
</code>```

But this didn't work out.

答:
With respect to Your posts BalusC but I think I cannot agree with you in one thing. Indeed Strings are immutable but filename.replace("a","b") return new instance of string.

So I think assigning to new variable is not necessary?

Body:
I am making a standalone application using java,and in that i need to insert the path of the image that user chooses from file chooser.
I am getting the path of the file but when i store it in the database(mysql) it doesn't stores the \,so when i retrieve that path,the file doesn't show up.

How to store the path of file with \\ so that one gets escaped using java code?

i tried using replaceall method but its giving an error of illegal character set.

filename.replaceall("\","\\");

But this didn't work out.


问:
Javascript Temporal Dead Zone
I don't really understand what's happening with the snippet below.

I would expect an error because of the Temporal Dead Zone, but it looks like const baz = '123123'; gets hoisted.

What's the reason why everything works?

class Foo {
  constructor() {
    console.log('Foo baz is:', baz)
  }
}

function log() {
  console.log('log baz is:', baz);
}

const baz = '123123';

log();
new Foo();```

答:
The const declaration is (sort-of) hoisted, so it's as if your code looked like this:

```<code>const baz; // hoisted, sort-of
class Foo {
  constructor() {
    console.log('Foo baz is:', baz)
  }
}

function log() {
  console.log('log baz is:', baz);
}

baz = '123123'; // not really possible because it's const

log();
new Foo();
</code>```

So there's a dead zone, but nothing actually happens in the dead zone; you don't make the function calls until after the dead zone so it's all good. It's fine to mention a symbol in its dead zone in nested function contexts. The dead zone is all about actively "touching" a hoisted symbol before its actual point of declaration.

Actually, because of the "temporal dead zone" concept, it's not really meaningful to think of const and let declarations as being "hoisted" the way var declarations are. This particular example is a good illustration of how the declarations can seem to be hoisted however, as the references in the nested lexical contexts do actually work because the symbol is defined by the time the code in those functions actually runs.

Title: Javascript Temporal Dead Zone

Body:
The const declaration is (sort-of) hoisted, so it's as if your code looked like this:

const baz; // hoisted, sort-of
class Foo {
  constructor() {
    console.log('Foo baz is:', baz)
  }
}

function log() {
  console.log('log baz is:', baz);
}

baz = '123123'; // not really possible because it's const

log();
new Foo();

So there's a dead zone, but nothing actually happens in the dead zone; you don't make the function calls until after the dead zone so it's all good. It's fine to mention a symbol in its dead zone in nested function contexts. The dead zone is all about actively "touching" a hoisted symbol before its actual point of declaration.

Actually, because of the "temporal dead zone" concept, it's not really meaningful to think of const and let declarations as being "hoisted" the way var declarations are. This particular example is a good illustration of how the declarations can seem to be hoisted however, as the references in the nested lexical contexts do actually work because the symbol is defined by the time the code in those functions actually runs.


问:
Can floor-ing a rounded number gives a different answer than the rounded number?
Am I correct that floor(round($number)) is not necessarily equal to round($number) assuming that "round" returns a double?

As an example, imagine that $number = 123456.9999999999999999.  I'm guessing that "round" will be a no-op, since $number is already as close as possible to 123457.
 "floor" would then yield 123456.

Is this correct or is there something about "floor" or "round" that prevents this?

答:
Due to the way that IEEE-754 floating-point representation works,1 it's not possible for a non-integer value (e.g. 123456.9999999999999999) to be representable and the nearest integer value (e.g. 123457) to be unrepresentable.

Thus in a sane implementation, the result of round should always be an integer value.  Indeed, in the case of C, the language standard mandates this.2

Thus in such a sane language, floor(round(x)) and round(x) are always the same.

1. IEEE-754 is overwhelmingly common now.  Technically, it may be possible to construct a floating-point system where this isn't true, but I doubt such a system exists in practice.

2. Your other example, PHP, has a sketchy "decimal precision" feature which makes me skeptical that the same guarantee applies!  Indeed, the implementation involves all sorts of mad stuff, including converting to a string and back.


问:
How to override services coupling caused by IdentityServer3.accesstokenvalidation
I have an identityserver4 which validates tokens sent along with the requests my APIs receive.

To do that I am using identityserver3.accesstokenvalidation.

In startup:

```<code> JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
 app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
    {
       Authority = Configurations.AuthorizationAuthority,
    });
</code>```

Now I might face cases where server running identityserver4  is shortly (multiple seconds) unavailable.

If this happens the service containing my APIs will not be able to run saying that:

No connection could be made because the target machine actively
  refused it

I want my API service to start even if IdentityServer server is not running, is there some kind of configuration Identityserver3.accesstokenvalidation provides to overcome this issue?

答: Set DelayLoadMetadata to true.

Body:
I have an identityserver4 which validates tokens sent along with the requests my APIs receive.

To do that I am using identityserver3.accesstokenvalidation.

In startup:

 JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
 app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
    {
       Authority = Configurations.AuthorizationAuthority,
    });

Now I might face cases where server running identityserver4  is shortly (multiple seconds) unavailable.

If this happens the service containing my APIs will not be able to run saying that:

No connection could be made because the target machine actively
  refused it

I want my API service to start even if IdentityServer server is not running, is there some kind of configuration Identityserver3.accesstokenvalidation provides to overcome this issue?

Body: Set DelayLoadMetadata to true.


问:
Failed to resolve: com.google.firebase:firebase-core:9.0.0
I get the following  error while upgrading a firebase project from old domain to new google firebase domain.

Failed to resolve: com.google.firebase:firebase-core:9.0.0

I followed the steps mentioned on the Firebase documentation, in the section Add Firebase to your Android Project, topic Available libraries.

What are my options to resolve this error?

答:
Tried all the above, use the Firebase Assistant! It is the simplest way to solve this. First remove all the dependencies you added to the build.gradle (using the manual method) and then in Android Studio:

```<code>Click Tools > Firebase to open the Assistant window.
</code>```

It really is as easy as that.

Body:
Tried all the above, use the Firebase Assistant! It is the simplest way to solve this. First remove all the dependencies you added to the build.gradle (using the manual method) and then in Android Studio:

Click Tools > Firebase to open the Assistant window.

It really is as easy as that.


问:
With Amazon S3, can I prevent trolls/grievers from making millions of GET-requests with bots?
I'm working on a website that contains photo galleries, and these images are stored on Amazon S3. Since Amazon charges like $0.01 per 10k GET-requests, it seems that a potential troll could seriously drive up my costs with a bot that makes millions of page requests per day.

Is there an easy way to protect myself from this?

答:
Add aws Cloudfront service for your S3 object images. So it will retrieve the cached data from the edge location.

http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/MigrateS3ToCloudFront.html


问:
query Object from Realm List
enter image description herei'm trying to query object from realm

```<code>class MessageRealm: Object {
dynamic var fromId = String()
dynamic var messageID = String()
dynamic var textDownloadded = String()
override class func primaryKey() -> String? {
    return "messageID"
  }
}

class UsersRealm: Object {
dynamic var sender = String()
let msgs = List<MessageRealm>()
override class func primaryKey() -> String? {
        return "sender"
    }
}
</code>```

i have two class one for messages and the other for users, every users have a list of messages and i need to query thats message based on (UserRealm.sender)
This is the realm DB

答:
I solve the issue by this way if anyone face the same</p>

```<code>var messageIndex: Results<MessageRealm>!
let realm = try! Realm()
let mssagesRealm = realm.objects(UsersRealm.self).filter("sender = %@", userTitleName)

   for sub in mssagesRealm {
       messageIndex = sub.msgs.sorted(byKeyPath: "timeStamp")
      }
</code>```

Title: query Object from Realm List

Body:
enter image description herei'm trying to query object from realm

class MessageRealm: Object {
dynamic var fromId = String()
dynamic var messageID = String()
dynamic var textDownloadded = String()
override class func primaryKey() -> String? {
    return "messageID"
  }
}

class UsersRealm: Object {
dynamic var sender = String()
let msgs = List<MessageRealm>()
override class func primaryKey() -> String? {
        return "sender"
    }
}

i have two class one for messages and the other for users, every users have a list of messages and i need to query thats message based on (UserRealm.sender)
This is the realm DB

Body:
I solve the issue by this way if anyone face the same

var messageIndex: Results<MessageRealm>!
let realm = try! Realm()
let mssagesRealm = realm.objects(UsersRealm.self).filter("sender = %@", userTitleName)

   for sub in mssagesRealm {
       messageIndex = sub.msgs.sorted(byKeyPath: "timeStamp")
      }


问:
How to read content of apk file programmatically?
I need read the content of apk file (including AndroidManifest.xml) programmatically. I know there are some tools like apktool, dex2jar, aapt to extract apk content but, I need to do the same through an Android application. By the way my start point is a valid apk file path.

答:
See this answer on another question:
https://stackoverflow.com/a/34850406/55940

Basically you can use this:

```<code>PackageInfo packageInfo = context.getPackageManager().getPackageArchiveInfo(file.getAbsolutePath(), 0);
</code>```

This would only get the meta data though... You would have to use a ZipInputStream etc to read the content of the file.

Body:
See this answer on another question:
https://stackoverflow.com/a/34850406/55940

Basically you can use this:

PackageInfo packageInfo = context.getPackageManager().getPackageArchiveInfo(file.getAbsolutePath(), 0);

This would only get the meta data though... You would have to use a ZipInputStream etc to read the content of the file.


问:
Data table dcast column headings
I have a data table of the form

```<code>ID  REGION  INCOME_BAND RESIDENCY_YEARS
1   SW  Under 5,000 10-15
2   Wales   Over 70,000 1-5
3   Center  15,000-19,999   6-9
4   SE  15,000-19,999   15-19
5   North   15,000-19,999   10-15
6   North   15,000-19,999   6-9
</code>```

created by

```<code>exp = data.table(
  ID = c(1,2,3,4,5,6),
  REGION=c("SW", "Wales", "Center", "SE", "North", "North"),
  INCOME_BAND = c("Under ?5,000", "Over ?70,000", "?15,000-?19,999", "?15,000-?19,999", "?15,000-?19,999","?15,000-?19,999"),
  RESIDENCY_YEARS = c("10-15","1-5","6-9","15-19","10-15", "6-9"))
</code>```

I would like to transform this to

I've managed to perform the majority of the work with dcast:

```<code>exp.dcast = dcast(exp,ID~REGION+INCOME_BAND+RESIDENCY_YEARS, fun=length,
  value.var=c('REGION', 'INCOME_BAND', 'RESIDENCY_YEARS'))
</code>```

However I need some help creating sensible column headings.
Currently I have

["ID"

  "REGION.1_Center_?15,000-?19,999_6-9"

  "REGION.1_North_?15,000-?19,999_10-15"

  "REGION.1_North_?15,000-?19,999_6-9"

  "REGION.1_SE_?15,000-?19,999_15-19"             "REGION.1_SW_Under
  ?5,000_10-15"                "REGION.1_Wales_Over ?70,000_1-5"

  "INCOME_BAND.1_Center_?15,000-?19,999_6-9"

  "INCOME_BAND.1_North_?15,000-?19,999_10-15"

  "INCOME_BAND.1_North_?15,000-?19,999_6-9"

  "INCOME_BAND.1_SE_?15,000-?19,999_15-19"

  "INCOME_BAND.1_SW_Under ?5,000_10-15"

  "INCOME_BAND.1_Wales_Over ?70,000_1-5"

  "RESIDENCY_YEARS.1_Center_?15,000-?19,999_6-9"
  "RESIDENCY_YEARS.1_North_?15,000-?19,999_10-15"
  "RESIDENCY_YEARS.1_North_?15,000-?19,999_6-9"

  "RESIDENCY_YEARS.1_SE_?15,000-?19,999_15-19"

  "RESIDENCY_YEARS.1_SW_Under ?5,000_10-15"

  "RESIDENCY_YEARS.1_Wales_Over ?70,000_1-5"

And I would like the column headings to be

```<code>ID  SW  Wales   Center  SE  North   Under 5,000 Over 70,000 15,000-19,999   1-5 6-9 10-15   15-19
</code>```

Could anybody advise?

答:
This apparently simple question is not easy to answer. So, we will go forward step-by step.

First, the OP has tried to reshape multiple value columns simultaneously which creates an unwanted cross product of all available combinations.

In order to treat all values in the same way, we need to melt() all value columns first before reshaping:

```<code>melt(exp, id.vars = "ID")[, dcast(.SD, ID ~ value, length)]
</code>```

```<code>   ID 1-5 10-15 15-19 6-9 ?15,000-?19,999 Center North Over ?70,000 SE SW Under ?5,000 Wales
1:  1   0     1     0   0               0      0     0            0  0  1            1     0
2:  2   1     0     0   0               0      0     0            1  0  0            0     1
3:  3   0     0     0   1               1      1     0            0  0  0            0     0
4:  4   0     0     1   0               1      0     0            0  1  0            0     0
5:  5   0     1     0   0               1      0     1            0  0  0            0     0
6:  6   0     0     0   1               1      0     1            0  0  0            0     0
</code>```

Now, the result has 13 columns instead of 19 and the columns are named by the respective value as requested.

Unfortunately, the columns appear in the wrong order because they alphabetically ordered. There are two approaches to change the order:

Change order of columns after reshaping

The setcolorder() function reorders the columns of a data.table in place, e.g. without copying:

```<code># define column order = order of values
col_order <- c("North", "Wales", "Center", "SW", "SE", "Under ?5,000", "?15,000-?19,999", "Over ?70,000", "1-5", "6-9", "10-15", "15-19")

melt(exp, id.vars = "ID")[, dcast(.SD, ID ~ value, length)][
  # reorder columns
  , setcolorder(.SD, c("ID", col_order))]
</code>```

```<code>   ID North Wales Center SW SE Under ?5,000 ?15,000-?19,999 Over ?70,000 1-5 6-9 10-15 15-19
1:  1     0     0      0  1  0            1               0            0   0   0     1     0
2:  2     0     1      0  0  0            0               0            1   1   0     0     0
3:  3     0     0      1  0  0            0               1            0   0   1     0     0
4:  4     0     0      0  0  1            0               1            0   0   0     0     1
5:  5     1     0      0  0  0            0               1            0   0   0     1     0
6:  6     1     0      0  0  0            0               1            0   0   1     0     0
</code>```

Now, all REGION columns appear first, followed by INCOME_BAND and RESIDENCY_YEARS columns in the specified order.

Set factor levels before reshaping

If value is turned into a factor with appropriately ordered factor levels dcast() will use the factor levels for ordering the columns:

```<code>melt(exp, id.vars = "ID")[, value := factor(value, col_order)][
  , dcast(.SD, ID ~ value, length)]
</code>```

```<code>   ID North Wales Center SW SE Under ?5,000 ?15,000-?19,999 Over ?70,000 1-5 6-9 10-15 15-19
1:  1     0     0      0  1  0            1               0            0   0   0     1     0
2:  2     0     1      0  0  0            0               0            1   1   0     0     0
3:  3     0     0      1  0  0            0               1            0   0   1     0     0
4:  4     0     0      0  0  1            0               1            0   0   0     0     1
5:  5     1     0      0  0  0            0               1            0   0   0     1     0
6:  6     1     0      0  0  0            0               1            0   0   1     0     0
</code>```

Set factor levels before reshaping - lazy version

If it is sufficient to have the columns grouped by REGION, INCOME_BAND, and RESIDENCY_YEARS then we can use a short cut to avoid specifying each value in col_order. The fct_inorder() function from the forcats package reorders factor levels by their first appearance in a vector:

```<code>melt(exp, id.vars = "ID")[, value := factor(value, col_order)][
  , dcast(.SD, ID ~ value, length)]
</code>```

```<code>   ID SW Wales Center SE North Under ?5,000 Over ?70,000 ?15,000-?19,999 10-15 1-5 6-9 15-19
1:  1  1     0      0  0     0            1            0               0     1   0   0     0
2:  2  0     1      0  0     0            0            1               0     0   1   0     0
3:  3  0     0      1  0     0            0            0               1     0   0   1     0
4:  4  0     0      0  1     0            0            0               1     0   0   0     1
5:  5  0     0      0  0     1            0            0               1     1   0   0     0
6:  6  0     0      0  0     1            0            0               1     0   0   1     0
</code>```

This works because the output of melt() is ordered by variable:

```<code>melt(exp, id.vars = "ID")
</code>```

```<code>    ID        variable           value
 1:  1          REGION              SW
 2:  2          REGION           Wales
 3:  3          REGION          Center
 4:  4          REGION              SE
 5:  5          REGION           North
 6:  6          REGION           North
 7:  1     INCOME_BAND    Under ?5,000
 8:  2     INCOME_BAND    Over ?70,000
 9:  3     INCOME_BAND ?15,000-?19,999
10:  4     INCOME_BAND ?15,000-?19,999
11:  5     INCOME_BAND ?15,000-?19,999
12:  6     INCOME_BAND ?15,000-?19,999
13:  1 RESIDENCY_YEARS           10-15
14:  2 RESIDENCY_YEARS             1-5
15:  3 RESIDENCY_YEARS             6-9
16:  4 RESIDENCY_YEARS           15-19
17:  5 RESIDENCY_YEARS           10-15
18:  6 RESIDENCY_YEARS             6-9
</code>```

Title: Data table dcast column headings

Body:
I have a data table of the form

ID  REGION  INCOME_BAND RESIDENCY_YEARS
1   SW  Under 5,000 10-15
2   Wales   Over 70,000 1-5
3   Center  15,000-19,999   6-9
4   SE  15,000-19,999   15-19
5   North   15,000-19,999   10-15
6   North   15,000-19,999   6-9

created by

exp = data.table(
  ID = c(1,2,3,4,5,6),
  REGION=c("SW", "Wales", "Center", "SE", "North", "North"),
  INCOME_BAND = c("Under ?5,000", "Over ?70,000", "?15,000-?19,999", "?15,000-?19,999", "?15,000-?19,999","?15,000-?19,999"),
  RESIDENCY_YEARS = c("10-15","1-5","6-9","15-19","10-15", "6-9"))

I would like to transform this to

I've managed to perform the majority of the work with dcast:

exp.dcast = dcast(exp,ID~REGION+INCOME_BAND+RESIDENCY_YEARS, fun=length,
  value.var=c('REGION', 'INCOME_BAND', 'RESIDENCY_YEARS'))

However I need some help creating sensible column headings.
Currently I have

["ID"

  "REGION.1_Center_?15,000-?19,999_6-9"

  "REGION.1_North_?15,000-?19,999_10-15"

  "REGION.1_North_?15,000-?19,999_6-9"

  "REGION.1_SE_?15,000-?19,999_15-19"             "REGION.1_SW_Under
  ?5,000_10-15"                "REGION.1_Wales_Over ?70,000_1-5"

  "INCOME_BAND.1_Center_?15,000-?19,999_6-9"

  "INCOME_BAND.1_North_?15,000-?19,999_10-15"

  "INCOME_BAND.1_North_?15,000-?19,999_6-9"

  "INCOME_BAND.1_SE_?15,000-?19,999_15-19"

  "INCOME_BAND.1_SW_Under ?5,000_10-15"

  "INCOME_BAND.1_Wales_Over ?70,000_1-5"

  "RESIDENCY_YEARS.1_Center_?15,000-?19,999_6-9"
  "RESIDENCY_YEARS.1_North_?15,000-?19,999_10-15"
  "RESIDENCY_YEARS.1_North_?15,000-?19,999_6-9"

  "RESIDENCY_YEARS.1_SE_?15,000-?19,999_15-19"

  "RESIDENCY_YEARS.1_SW_Under ?5,000_10-15"

  "RESIDENCY_YEARS.1_Wales_Over ?70,000_1-5"

And I would like the column headings to be

ID  SW  Wales   Center  SE  North   Under 5,000 Over 70,000 15,000-19,999   1-5 6-9 10-15   15-19

Could anybody advise?

Body:
This apparently simple question is not easy to answer. So, we will go forward step-by step.

First, the OP has tried to reshape multiple value columns simultaneously which creates an unwanted cross product of all available combinations.

In order to treat all values in the same way, we need to melt() all value columns first before reshaping:

melt(exp, id.vars = "ID")[, dcast(.SD, ID ~ value, length)]

   ID 1-5 10-15 15-19 6-9 ?15,000-?19,999 Center North Over ?70,000 SE SW Under ?5,000 Wales
1:  1   0     1     0   0               0      0     0            0  0  1            1     0
2:  2   1     0     0   0               0      0     0            1  0  0            0     1
3:  3   0     0     0   1               1      1     0            0  0  0            0     0
4:  4   0     0     1   0               1      0     0            0  1  0            0     0
5:  5   0     1     0   0               1      0     1            0  0  0            0     0
6:  6   0     0     0   1               1      0     1            0  0  0            0     0

Now, the result has 13 columns instead of 19 and the columns are named by the respective value as requested.

Unfortunately, the columns appear in the wrong order because they alphabetically ordered. There are two approaches to change the order:

Change order of columns after reshaping

The setcolorder() function reorders the columns of a data.table in place, e.g. without copying:

# define column order = order of values
col_order <- c("North", "Wales", "Center", "SW", "SE", "Under ?5,000", "?15,000-?19,999", "Over ?70,000", "1-5", "6-9", "10-15", "15-19")

melt(exp, id.vars = "ID")[, dcast(.SD, ID ~ value, length)][
  # reorder columns
  , setcolorder(.SD, c("ID", col_order))]

   ID North Wales Center SW SE Under ?5,000 ?15,000-?19,999 Over ?70,000 1-5 6-9 10-15 15-19
1:  1     0     0      0  1  0            1               0            0   0   0     1     0
2:  2     0     1      0  0  0            0               0            1   1   0     0     0
3:  3     0     0      1  0  0            0               1            0   0   1     0     0
4:  4     0     0      0  0  1            0               1            0   0   0     0     1
5:  5     1     0      0  0  0            0               1            0   0   0     1     0
6:  6     1     0      0  0  0            0               1            0   0   1     0     0

Now, all REGION columns appear first, followed by INCOME_BAND and RESIDENCY_YEARS columns in the specified order.

Set factor levels before reshaping

If value is turned into a factor with appropriately ordered factor levels dcast() will use the factor levels for ordering the columns:

melt(exp, id.vars = "ID")[, value := factor(value, col_order)][
  , dcast(.SD, ID ~ value, length)]

   ID North Wales Center SW SE Under ?5,000 ?15,000-?19,999 Over ?70,000 1-5 6-9 10-15 15-19
1:  1     0     0      0  1  0            1               0            0   0   0     1     0
2:  2     0     1      0  0  0            0               0            1   1   0     0     0
3:  3     0     0      1  0  0            0               1            0   0   1     0     0
4:  4     0     0      0  0  1            0               1            0   0   0     0     1
5:  5     1     0      0  0  0            0               1            0   0   0     1     0
6:  6     1     0      0  0  0            0               1            0   0   1     0     0

Set factor levels before reshaping - lazy version

If it is sufficient to have the columns grouped by REGION, INCOME_BAND, and RESIDENCY_YEARS then we can use a short cut to avoid specifying each value in col_order. The fct_inorder() function from the forcats package reorders factor levels by their first appearance in a vector:

melt(exp, id.vars = "ID")[, value := factor(value, col_order)][
  , dcast(.SD, ID ~ value, length)]

   ID SW Wales Center SE North Under ?5,000 Over ?70,000 ?15,000-?19,999 10-15 1-5 6-9 15-19
1:  1  1     0      0  0     0            1            0               0     1   0   0     0
2:  2  0     1      0  0     0            0            1               0     0   1   0     0
3:  3  0     0      1  0     0            0            0               1     0   0   1     0
4:  4  0     0      0  1     0            0            0               1     0   0   0     1
5:  5  0     0      0  0     1            0            0               1     1   0   0     0
6:  6  0     0      0  0     1            0            0               1     0   0   1     0

This works because the output of melt() is ordered by variable:

melt(exp, id.vars = "ID")

    ID        variable           value
 1:  1          REGION              SW
 2:  2          REGION           Wales
 3:  3          REGION          Center
 4:  4          REGION              SE
 5:  5          REGION           North
 6:  6          REGION           North
 7:  1     INCOME_BAND    Under ?5,000
 8:  2     INCOME_BAND    Over ?70,000
 9:  3     INCOME_BAND ?15,000-?19,999
10:  4     INCOME_BAND ?15,000-?19,999
11:  5     INCOME_BAND ?15,000-?19,999
12:  6     INCOME_BAND ?15,000-?19,999
13:  1 RESIDENCY_YEARS           10-15
14:  2 RESIDENCY_YEARS             1-5
15:  3 RESIDENCY_YEARS             6-9
16:  4 RESIDENCY_YEARS           15-19
17:  5 RESIDENCY_YEARS           10-15
18:  6 RESIDENCY_YEARS             6-9


问:
Does calling await on a no task creation method do anything Asynchronous?
Consider the following:

```<code>public async Task<bool> DoSomethingAsync()
{
  // no creation of a task in these statements
  statement2;
  statement3;
  statement4;
  return Task.FromResult( true );
}

public async Task MyMethod()
{
  statement1;
  await DoSomethingAsync().ConfigureAwait( false );
  statement5;
}
</code>```

Is there any asynchronous behaviour to be run when awaiting DoSomethingAsync?

答:
Is there any asynchronous behaviour to be run when awaiting DoSomethingAsync?

No, there isn't. When DoSomthingAsync is called, it is executed whole and returned Task is already finished. So when await tries to wire-up the callback logic, it finds out the task is already finished and just continues execution without bothering with the callback logic.

But all of those are implementation details and it is possible those details will change. You should not build your code with the assumption this code will run synchronously. Any addition of await inside DoSomthingAsync will make the code completely asynchronous without you noticing.

Also, DoSomthingAsync the way it is right now does not compile. You either remove the async, in which case it is clear that DoSomthingAsync is not asynchronous. Or you just have return true; , in which case the compiler should warn you that method does not contain any await and will complete synchronously.

Considering your question in comment:

```<code>public async Task<bool> DoSomethingAsync()
{
  statement2;
  await statement3; // << Diverges here
  statement4;
  return true;
}

// all code below this line is completely irrelevant
// to whenever or where the code above diverges

public async Task MyMethod()
{
  statement1;
  await DoSomethingAsync().ConfigureAwait( false );
  statement5;
}
</code>```

Body:
Consider the following:

public async Task<bool> DoSomethingAsync()
{
  // no creation of a task in these statements
  statement2;
  statement3;
  statement4;
  return Task.FromResult( true );
}

public async Task MyMethod()
{
  statement1;
  await DoSomethingAsync().ConfigureAwait( false );
  statement5;
}

Is there any asynchronous behaviour to be run when awaiting DoSomethingAsync?

Body:
Is there any asynchronous behaviour to be run when awaiting DoSomethingAsync?

No, there isn't. When DoSomthingAsync is called, it is executed whole and returned Task is already finished. So when await tries to wire-up the callback logic, it finds out the task is already finished and just continues execution without bothering with the callback logic.

But all of those are implementation details and it is possible those details will change. You should not build your code with the assumption this code will run synchronously. Any addition of await inside DoSomthingAsync will make the code completely asynchronous without you noticing.

Also, DoSomthingAsync the way it is right now does not compile. You either remove the async, in which case it is clear that DoSomthingAsync is not asynchronous. Or you just have return true; , in which case the compiler should warn you that method does not contain any await and will complete synchronously.

Considering your question in comment:

public async Task<bool> DoSomethingAsync()
{
  statement2;
  await statement3; // << Diverges here
  statement4;
  return true;
}

// all code below this line is completely irrelevant
// to whenever or where the code above diverges

public async Task MyMethod()
{
  statement1;
  await DoSomethingAsync().ConfigureAwait( false );
  statement5;
}


问:
QLineEdit::text is incomplete with Android virtual keyboard
If I use Android native virtual keyboard, QLineEdit can not get all inputed words. (Qt 5.7,  Android 6)

If I input "Force input" (like on the picture) and call

```<code>QLineEdit::text()
</code>```

I get only "Force ".

How do I get the whole text?

答:
The problem is that "input" is still being typed/inputted (notice the underline) and is not yet committed to the application. You can force to commit everything now using QInputMethod::commit:

Commits the word user is currently composing to the editor. The
  function is mostly needed by the input methods with text prediction
  features and by the methods where the script used for typing
  characters is different from the script that actually gets appended to
  the editor. Any kind of action that interrupts the text composing
  needs to flush the composing state by calling the commit() function,
  for example when the cursor is moved elsewhere.

Afterwards, you should be able to retrieve all the text using QLineEdit::text.

Alternative: QLineEdit::displayText

As discussed here, it may be possible to use QLineEdit::displayText without calling QInputMethod::commit first.

Body:
If I use Android native virtual keyboard, QLineEdit can not get all inputed words. (Qt 5.7,  Android 6)

If I input "Force input" (like on the picture) and call

QLineEdit::text()

I get only "Force ".

How do I get the whole text?