问:
dojo: loading json data from local file (using http) into dijit tree
file snapshot_report_js.js:

```<code>require([
    "dojo/dom",
    "dojo/json",
    "dojo/store/Memory",
    "dijit/tree/ObjectStoreModel",
    "dijit/Tree",
    "dojo/text!http://localhost:8080/dojo/json_data/snapshot.json",
    "dojo/domReady!",
    "dojo/_base/json"
], function(dom, json, Memory, ObjectStoreModel, Tree, small){
    var stringfied_content = JSON.stringify(small)
    var json_parsed_data = JSON.parse(stringfied_content, true)
    var json_data = dojo.toJson(json_parsed_data);
    // set up the store to get the tree data
    var json_store = new Memory({
        data: [ json_data ],
        getChildren: function(object){
            return object.children || [];
        }
    });
    // Create the model
    var snapshot_treeModel = new ObjectStoreModel({
        store: json_store,
        query: {id: 'snapshot'}
    });

    var snapshot_tree = new dijit.Tree({
        model: snapshot_treeModel
    }, 'div_snapshot_tree');
    snapshot_tree.startup();
})

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Snapshot</title>
<link rel="stylesheet" href="dijit/themes/claro/claro.css">
<!-- load Dojo -->
<script src="dojo/dojo.js" data-dojo-config="async: true"></script>
<script src="js/snapshot_report_js.js"></script>
</head>
<body class="claro">
<div id="div_snapshot_tree"></div>
</body>
</html>
</code>```

JSON file:

```<code>{
    "snapshot_metadata": {
            "report_end_at": "2017-10-11 02:03:36",
            "environment_name": "DVINST",
            "report_start_at": "2017-10-11 01:55:42"
    },
    "versions": [
        {
            "id": "version_001",
            "instances": [
                {
                    "instance_name": "instance1",
                    "instance_create_date": "2017-09-18 00:17:52",
                    "connected_site_count": 4,
                    "admin_server": "t3://tserver:18300",
                    "instance_id": 2411,
                    "instance_type": "OSVC",
                    "instance_created_by": "None",
                    "site_capacity": 2,
                    "sites": [
                            {
                            "site_db_id": 395,
                            "site_name": "zzzz_178",
                            "site_users": "uc1,uc2,uc3",
                            "site_id": 89492,
                            "site_owner": "owner1",
                            "site_db_name": "site_server2"
                            },
                            {
                            "site_db_id": 395,
                            "site_name": "site2",
                            "site_users": "u1, u2, u3",
                            "site_id": 90447,
                            "site_owner": "u2",
                            "site_db_name": "site_server3"
                            }
                    ]
                }
            ]
        }
    ],
    "servers": [
        {
            "status": null,
            "server_id": 13,
            "server_name": "db1",
            "server_type": "database",
            "mount_points": [],
            "sites": [],
            "db_connections_count": 6,
            "health": null,
            "admin_servers": null,
            "db_sites_connected_count": null
        }
    ]
}
</code>```

Error on console:

dojo.js:8 Uncaught Error: dijit.tree.ObjectStoreModel: root query
  returned 0 items, but must return exactly one at Object.

  (ObjectStoreModel.js.uncompressed.js:86) at dojo.js:8 at when

  (dojo.js:8) at Object.getRoot

  (ObjectStoreModel.js.uncompressed.js:82) at Object._load

  (Tree.js.uncompressed.js:897) at Object.postCreate

  (Tree.js.uncompressed.js:844) at Object.create

  (_WidgetBase.js.uncompressed.js:453) at Object.postscript

  (_WidgetBase.js.uncompressed.js:366) at new  (dojo.js:8)

  at snapshot_report_js.js:178

I don't see anything wrong here, can anybody help?

答:
At first glance your ObjectStoreModel is trying to find root object for tree and as you specified it should have property id equals to snapshot; nothing in your JSON is matching that query.

Secondly, JSON data should bring tree-structured content while your JSON is unstructured; see ObjectStoreModel example how tree data looks like. If you have custom data structure then you need to transform it to be consumed by tree widget thru its model.

Body:
file snapshot_report_js.js:

require([
    "dojo/dom",
    "dojo/json",
    "dojo/store/Memory",
    "dijit/tree/ObjectStoreModel",
    "dijit/Tree",
    "dojo/text!http://localhost:8080/dojo/json_data/snapshot.json",
    "dojo/domReady!",
    "dojo/_base/json"
], function(dom, json, Memory, ObjectStoreModel, Tree, small){
    var stringfied_content = JSON.stringify(small)
    var json_parsed_data = JSON.parse(stringfied_content, true)
    var json_data = dojo.toJson(json_parsed_data);
    // set up the store to get the tree data
    var json_store = new Memory({
        data: [ json_data ],
        getChildren: function(object){
            return object.children || [];
        }
    });
    // Create the model
    var snapshot_treeModel = new ObjectStoreModel({
        store: json_store,
        query: {id: 'snapshot'}
    });

    var snapshot_tree = new dijit.Tree({
        model: snapshot_treeModel
    }, 'div_snapshot_tree');
    snapshot_tree.startup();
})

<!DOCTYPE html>

<meta charset="utf-8">
<title>Snapshot</title>
<link rel="stylesheet" href="dijit/themes/claro/claro.css">

JSON file:

{
    "snapshot_metadata": {
            "report_end_at": "2017-10-11 02:03:36",
            "environment_name": "DVINST",
            "report_start_at": "2017-10-11 01:55:42"
    },
    "versions": [
        {
            "id": "version_001",
            "instances": [
                {
                    "instance_name": "instance1",
                    "instance_create_date": "2017-09-18 00:17:52",
                    "connected_site_count": 4,
                    "admin_server": "t3://tserver:18300",
                    "instance_id": 2411,
                    "instance_type": "OSVC",
                    "instance_created_by": "None",
                    "site_capacity": 2,
                    "sites": [
                            {
                            "site_db_id": 395,
                            "site_name": "zzzz_178",
                            "site_users": "uc1,uc2,uc3",
                            "site_id": 89492,
                            "site_owner": "owner1",
                            "site_db_name": "site_server2"
                            },
                            {
                            "site_db_id": 395,
                            "site_name": "site2",
                            "site_users": "u1, u2, u3",
                            "site_id": 90447,
                            "site_owner": "u2",
                            "site_db_name": "site_server3"
                            }
                    ]
                }
            ]
        }
    ],
    "servers": [
        {
            "status": null,
            "server_id": 13,
            "server_name": "db1",
            "server_type": "database",
            "mount_points": [],
            "sites": [],
            "db_connections_count": 6,
            "health": null,
            "admin_servers": null,
            "db_sites_connected_count": null
        }
    ]
}

Error on console:

dojo.js:8 Uncaught Error: dijit.tree.ObjectStoreModel: root query
  returned 0 items, but must return exactly one at Object.

  (ObjectStoreModel.js.uncompressed.js:86) at dojo.js:8 at when

  (dojo.js:8) at Object.getRoot

  (ObjectStoreModel.js.uncompressed.js:82) at Object._load

  (Tree.js.uncompressed.js:897) at Object.postCreate

  (Tree.js.uncompressed.js:844) at Object.create

  (_WidgetBase.js.uncompressed.js:453) at Object.postscript

  (_WidgetBase.js.uncompressed.js:366) at new  (dojo.js:8)

  at snapshot_report_js.js:178

I don't see anything wrong here, can anybody help?


来源: stackexchange

问:
How to decide with duplicate values on column VBA
If I have the following table:

```<code>Name  | IP      | OS
------+---------+---------
host1 | 1.1.1.1 | Windows
host1 | N/A     | N/A
host1 | 1.1.1.1 | N/A
host1 | N/A     | Windows
</code>```

How can I remove duplicates, and just keep the row with more values?

Output should be like this:

```<code>Name  | IP      | OS
------+---------+---------
host1 | 1.1.1.1 | Windows
</code>```

I tried ActiveSheet.Range("A:A").RemoveDuplicates Columns:=1 but it removes all duplicates host1 i.e the result is this

```<code>Name  | IP      | OS
------+---------+---------
host1 | 1.1.1.1 | Windows
      | N/A     | N/A
      | 1.1.1.1 | N/A
      | N/A     | Windows
</code>```

答:
In the SQL for the datapull, you could do something like this:</p>

```<code>SELECT Name, MAX(IIF( ip <> "N/A", ip)) AS ip, MAX(IIF( os <> "N/A", os)) AS os
FROM table
GROUP BY Name
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If I have the following table:

Name  | IP      | OS
------+---------+---------
host1 | 1.1.1.1 | Windows
host1 | N/A     | N/A
host1 | 1.1.1.1 | N/A
host1 | N/A     | Windows

How can I remove duplicates, and just keep the row with more values?

Output should be like this:

Name  | IP      | OS
------+---------+---------
host1 | 1.1.1.1 | Windows

I tried ActiveSheet.Range("A:A").RemoveDuplicates Columns:=1 but it removes all duplicates host1 i.e the result is this

Name  | IP      | OS
------+---------+---------
host1 | 1.1.1.1 | Windows
      | N/A     | N/A
      | 1.1.1.1 | N/A
      | N/A     | Windows

Body:
In the SQL for the datapull, you could do something like this:

SELECT Name, MAX(IIF( ip <> "N/A", ip)) AS ip, MAX(IIF( os <> "N/A", os)) AS os
FROM table
GROUP BY Name


问:
Wait for an async callback in a periodic task?
I'd like to check the user's location every 4 hours or so, and I don't want to leave my app running to do this. It looks like using a GcmTaskService with a PeriodicTask will let my service get called (WakefulBroadcastReceiver has restrictions against starting tasks when the app is stopped in Android 6+), and it will be compatible back to Android 4.4 (unlike JobScheduler) - my lowest supported Android version.

The issue is that GcmTaskService's onRunTask method is synchronous, but I want to use that to ask for a location and process the result (LocationManager will call my LocationListener implementation asynchronously).

How should this be handled?

答:
Use a simple wait/notify:</p>

```<code>private interface RunnableLocationListener extends Runnable, LocationListener {}

@Override
public int onRunTask (TaskParams params) {
    final Object monitor = new Object();
    final AtomicBoolean located = new AtomicBoolean();
    new Thread(new RunnableLocationListener() {
        Context context = PeriodicCollector.this;
        public void run() {
            Criteria criteria = new Criteria();
            criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
            LocationManager locationManager = locationManager = (LocationManager)PeriodicCollector.this.getSystemService(Context.LOCATION_SERVICE);
            locationManager.requestSingleUpdate(criteria, this, Looper.getMainLooper());
        }

        @Override
        public void onLocationChanged(Location location) {
            // handle location here

            synchronized (monitor) {
                located.set(true);
                monitor.notifyAll();
            }
        }

        @Override public void onProviderDisabled(String s) {}
        @Override public void onProviderEnabled(String s) {}
        @Override public void onStatusChanged(String s, int i, Bundle b) {}
    }).start();

    int status = GcmNetworkManager.RESULT_FAILURE;
    try {
        synchronized (monitor) {
            if (!located.get()) {
                monitor.wait();
            }
        }
    } catch (InterruptedException e) {
        status = GcmNetworkManager.RESULT_SUCCESS;
    }
    return status;
}
</code>```

Body:
Use a simple wait/notify:

private interface RunnableLocationListener extends Runnable, LocationListener {}

@Override
public int onRunTask (TaskParams params) {
    final Object monitor = new Object();
    final AtomicBoolean located = new AtomicBoolean();
    new Thread(new RunnableLocationListener() {
        Context context = PeriodicCollector.this;
        public void run() {
            Criteria criteria = new Criteria();
            criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
            LocationManager locationManager = locationManager = (LocationManager)PeriodicCollector.this.getSystemService(Context.LOCATION_SERVICE);
            locationManager.requestSingleUpdate(criteria, this, Looper.getMainLooper());
        }

        @Override
        public void onLocationChanged(Location location) {
            // handle location here

            synchronized (monitor) {
                located.set(true);
                monitor.notifyAll();
            }
        }

        @Override public void onProviderDisabled(String s) {}
        @Override public void onProviderEnabled(String s) {}
        @Override public void onStatusChanged(String s, int i, Bundle b) {}
    }).start();

    int status = GcmNetworkManager.RESULT_FAILURE;
    try {
        synchronized (monitor) {
            if (!located.get()) {
                monitor.wait();
            }
        }
    } catch (InterruptedException e) {
        status = GcmNetworkManager.RESULT_SUCCESS;
    }
    return status;
}


问:
"How To" for adding a plugin to Nagios
Is there a "how to" for adding and configuring a plugin to Nagios? (for Ubuntu 14.04 specifically, but any Linux OS would be helpful.)

I've been able to cobble this much so far:

Place the script in /usr/local/nagios/libexec/. (In my case there was already a script I wanted to use: "check_file_age".)

Edit /usr/local/nagios/etc/objects/commands.cfg to add the plugin.

```define command{
    command_name check_file_age
    command_line $USER1$/check_file_age -w $ARG1$ -c $ARG2$ -W $ARG3$ -C $ARG4$ -f $ARG5$
}```

Define the plugin in /usr/local/nagios/etc/objects/localhost.cfg.

```define service{
    use             generic-service     ; Name of service template to use
    host_name           localhost
    service_description     File Age
    check_command           check_file_age
    notifications_enabled       1
}```

Now I can see the plugin under "Configuration -> Object Type: Command" and I can see it listed in "Configuration -> Object Type: Services".

The plugin runs successfully from the command line:

```user@host:/usr/local/nagios/libexec$ perl ./check_file_age -w 3600 -c 5400 -W -1 -C -1 -f somefile.txt
FILE_AGE OK: somefile.txt is 2932 seconds old and 59 bytes | age=2932s;3600;5400 size=59B;-1;-1;0```

Then at this point I'm stumped. I can see this error in Services:

```File Age
CRITICAL
09-09-2015 14:24:21
0d 0h 32m 1s
3/3
(No output on stdout) stderr: Can't locate utils.pm in @INC (you may need to install the utils module) (@INC contains: . /etc/perl /usr/local/lib/perl/5.18.2 /usr/local/share/perl/5.18.2 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.18 /usr/share/perl/5.18 /usr/local/lib/site_perl) at /usr/local/nagios/libexec/check_file_age line 30.
HTTP
Notifications for this service have been disabled
OK  09-09-2015 14:30:53 0d 4h 3m 30s    1/4 ```

How do I specify what arguments to pass? How do I correct the error? What's next? (Is there a single location that describes how to add a plugin that escaped my Google-fu?)

答:
On CentOS 6.9 I could fix the problem by reinstalling the rpm package which provides the file:

yum reinstall /usr/lib64/nagios/plugins/utils.pm

Title: "How To" for adding a plugin to Nagios

Body:
Is there a "how to" for adding and configuring a plugin to Nagios? (for Ubuntu 14.04 specifically, but any Linux OS would be helpful.)

I've been able to cobble this much so far:

Place the script in /usr/local/nagios/libexec/. (In my case there was already a script I wanted to use: "check_file_age".)

Edit /usr/local/nagios/etc/objects/commands.cfg to add the plugin.

define command{
    command_name check_file_age
    command_line $USER1$/check_file_age -w $ARG1$ -c $ARG2$ -W $ARG3$ -C $ARG4$ -f $ARG5$
}

Define the plugin in /usr/local/nagios/etc/objects/localhost.cfg.

define service{
    use             generic-service     ; Name of service template to use
    host_name           localhost
    service_description     File Age
    check_command           check_file_age
    notifications_enabled       1
}

Now I can see the plugin under "Configuration -> Object Type: Command" and I can see it listed in "Configuration -> Object Type: Services".

The plugin runs successfully from the command line:

user@host:/usr/local/nagios/libexec$ perl ./check_file_age -w 3600 -c 5400 -W -1 -C -1 -f somefile.txt
FILE_AGE OK: somefile.txt is 2932 seconds old and 59 bytes | age=2932s;3600;5400 size=59B;-1;-1;0

Then at this point I'm stumped. I can see this error in Services:

File Age
CRITICAL
09-09-2015 14:24:21
0d 0h 32m 1s
3/3
(No output on stdout) stderr: Can't locate utils.pm in @INC (you may need to install the utils module) (@INC contains: . /etc/perl /usr/local/lib/perl/5.18.2 /usr/local/share/perl/5.18.2 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.18 /usr/share/perl/5.18 /usr/local/lib/site_perl) at /usr/local/nagios/libexec/check_file_age line 30.
HTTP
Notifications for this service have been disabled
OK  09-09-2015 14:30:53 0d 4h 3m 30s    1/4

How do I specify what arguments to pass? How do I correct the error? What's next? (Is there a single location that describes how to add a plugin that escaped my Google-fu?)


问:
JQuery to add divs to list of images
Hey I have a list of images that I need to wrap with divs so that every three images is in a new div. The first div has to start at the beginning and continue for the next three images before closing and opening the next div. The final HTML should look like this:

```<code><div>
    <img />
    <img />
    <img />
</div>
<div>
    <img />
    <img />
    <img />
</div>
<div>
    <img />
    <img />
    <img />
</div>
</code>```

I know that this should have to do something with the nth child selector but so far I've only been able to select single elements rather then being able to select three at a time.

答:
well,

```<code>$('img:nth-child(3n)').each(function(){
    $(this).prevAll('img').andSelf().wrapAll('<div/>');
});
</code>```

demo

ContentLicense: CC BY-SA 2.5

Title: JQuery to add divs to list of images

Body:
Hey I have a list of images that I need to wrap with divs so that every three images is in a new div. The first div has to start at the beginning and continue for the next three images before closing and opening the next div. The final HTML should look like this:

I know that this should have to do something with the nth child selector but so far I've only been able to select single elements rather then being able to select three at a time.

Body:
well,

$('img:nth-child(3n)').each(function(){
    $(this).prevAll('img').andSelf().wrapAll('<div/>');
});

demo


问:
JQuery remove backslash with some words in string
my string is "\upload\document\file.txt", i want to remove the "\upload" part in that string with jQuery. I try this one but it does not work:

var filePath = "\upload\document\file.txt";
filePath = filePath.replace('\upload', '');
console.log(filePath);```

答:
You need to escape \

  var filePath = "\\upload\\document\\file.txt";
  filePath= filePath.replace('\\upload', '');

  console.log(filePath)```


问:
How to remove the word ‘api’ from Azure functions url
When you create an Http triggered API, Azure function hosts it on

```<code>https://[function-app-name].azurewebsites.net/api/[Route-configured-in-application]
</code>```

Is there any way of getting rid of the term api from the URL and make it look like:

```<code>https://[function-app-name].azurewebsites.net/[Route-configured-in-application]
</code>```

答:
Edit the host.json file and set routePrefix to empty string:</p>

```<code>{
  "http": {
    "routePrefix": ""
  }
}
</code>```

Body:
When you create an Http triggered API, Azure function hosts it on

https://[function-app-name].azurewebsites.net/api/[Route-configured-in-application]

Is there any way of getting rid of the term api from the URL and make it look like:

https://[function-app-name].azurewebsites.net/[Route-configured-in-application]

Body:
Edit the host.json file and set routePrefix to empty string:

{
  "http": {
    "routePrefix": ""
  }
}

ContentLicense: CC BY-SA 4.0


问:
Replacing values in same column and same dataset in R
I have a dataset like this:

```<code>Name|Material |Project
John|LS       |222
Jack|Limestone|111
Job |LI       |121
</code>```

I want to replace LS and LI with Limestone in Materials column.

I have tried this for LS:

```<code>ds$Material[ds$material %in% grep("^LS^",ds$Material,ignore.case = TRUE)]<-"Limestone"
</code>```

But the column still has a bunch of LS in there. Any ideas?

答:
You could also use gsub() to replace LI and LS with Limestone:

```<code>ds$Material <- gsub("LS|LI", "Limestone", ds$Material)
#   Name Materials Project
# 1 John Limestone     222
# 2 Jack Limestone     111
# 3  Job Limestone     121
</code>```

Body:
I have a dataset like this:

Name|Material |Project
John|LS       |222
Jack|Limestone|111
Job |LI       |121

I want to replace LS and LI with Limestone in Materials column.

I have tried this for LS:

ds$Material[ds$material %in% grep("^LS^",ds$Material,ignore.case = TRUE)]<-"Limestone"

But the column still has a bunch of LS in there. Any ideas?

Body:
You could also use gsub() to replace LI and LS with Limestone:

ds$Material <- gsub("LS|LI", "Limestone", ds$Material)
#   Name Materials Project
# 1 John Limestone     222
# 2 Jack Limestone     111
# 3  Job Limestone     121


问:
Gradle build error styles attributes not found
I was try to upgrade android studio 2.3 to 3.0 but the gradle can't build and shows this message:
Probably one of your libraries is expecting that style to be available and it's not finding it

please help me to fix this error.

screenshot of the error message

this is the build.gradle of the project

```<code>apply plugin: 'com.android.application'

repositories {
    maven {
        url 'https://repo1.maven.org/maven2/'
    }
}

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'

    defaultConfig {
        applicationId "com.skills.inuk"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "0.3.2"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true //important
        vectorDrawables.useSupportLibrary = true
    }

    buildTypes {

        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

    }

    packagingOptions {
        exclude 'LICENSE.txt'
    }
    lintOptions {
        abortOnError false
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    // compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:design:26.0.1'
    compile 'com.jakewharton:butterknife:8.6.0'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.twitter.sdk.android:twitter:3+'
    compile 'com.google.android.gms:play-services:11.4.2'
    compile 'com.makeramen:roundedimageview:2.3.0'
    compile 'com.github.curioustechizen.android-ago:library:1.3.4'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    compile 'com.google.code.gson:gson:2.6.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.android.support:support-v4:26.0.1'
    compile 'com.android.support:support-vector-drawable:26.0.1'
    compile 'com.loopj.android:android-async-http:1.4.9'
    compile 'com.android.support:multidex:1.0.1'
    testCompile 'junit:junit:4.12'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0'
}
apply plugin: 'com.google.gms.google-services'
</code>```

Thx for your reponses guys, i founded the probleme , this happening because :

Consider if you incorrectly include the symbol when accessing a resource from the android namespace, as shown below:

```<code><!-- When referencing resources from the 'android' namespace, omit the '@' symbol. -->
<item name="@android:windowEnterAnimation"/>
</code>```

答: Maybe you want to use ?android:attr/background and ?android:attr/textColor instead of @android:attr/background and @android:attr/textColor

Body:
I was try to upgrade android studio 2.3 to 3.0 but the gradle can't build and shows this message:
Probably one of your libraries is expecting that style to be available and it's not finding it

please help me to fix this error.

screenshot of the error message

this is the build.gradle of the project

apply plugin: 'com.android.application'

repositories {
    maven {
        url 'https://repo1.maven.org/maven2/'
    }
}

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'

    defaultConfig {
        applicationId "com.skills.inuk"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "0.3.2"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true //important
        vectorDrawables.useSupportLibrary = true
    }

    buildTypes {

        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

    }

    packagingOptions {
        exclude 'LICENSE.txt'
    }
    lintOptions {
        abortOnError false
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    // compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:design:26.0.1'
    compile 'com.jakewharton:butterknife:8.6.0'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.twitter.sdk.android:twitter:3+'
    compile 'com.google.android.gms:play-services:11.4.2'
    compile 'com.makeramen:roundedimageview:2.3.0'
    compile 'com.github.curioustechizen.android-ago:library:1.3.4'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    compile 'com.google.code.gson:gson:2.6.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.android.support:support-v4:26.0.1'
    compile 'com.android.support:support-vector-drawable:26.0.1'
    compile 'com.loopj.android:android-async-http:1.4.9'
    compile 'com.android.support:multidex:1.0.1'
    testCompile 'junit:junit:4.12'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0'
}
apply plugin: 'com.google.gms.google-services'

Thx for your reponses guys, i founded the probleme , this happening because :

Consider if you incorrectly include the symbol when accessing a resource from the android namespace, as shown below:

<item name="@android:windowEnterAnimation"/>


问:
order by absolute values of one column while keeping equal values of another column together in R
Example data.frame:

```<code>df <- data.frame(study = c('A', 'A', 'B', 'C', 'D', 'D'),
                 similarity = c(0.61, 0.58, -0.605, 0.4, 0.607, 0.3))

df
   study similarity
1     A      0.610
2     A      0.580
3     B     -0.605
4     C      0.400
5     D      0.607
6     D      0.300
</code>```

I want to order by absolute similarity, but keeping equal values of study together. For the above example the result should be:

```<code>   study similarity
1     A      0.610
2     A      0.580
5     D      0.607
6     D      0.300
3     B     -0.605
4     C      0.400
</code>```

答:
A solution using dplyr. This solution looks more complicated than others, but it aims to generate the expected output even if the study column is not in order, or there are ties in similarity from different study group.

First, Calculate the absolute value of each similarity (df2).

Second, Calcualte the maximum absolute of each study (df3).

Third,  Covert the study column to a factor column based on the order in df3. Arrange the columns based on study and absolute value (df4)

```<code>library(dplyr)

df2 <- df %>% mutate(ABS = abs(similarity))

df3 <- df2 %>%
  group_by(study) %>%
  summarise(Max_ABS = max(ABS)) %>%
  arrange(desc(Max_ABS))

df4 <- df2 %>%
  mutate(study = factor(study, levels = df3$study)) %>%
  arrange(study, desc(ABS)) %>%
  select(-ABS)
df4
#   study similarity
# 1     A      0.610
# 2     A      0.580
# 3     D      0.607
# 4     D      0.300
# 5     B     -0.605
# 6     C      0.400
</code>```

Body:
Example data.frame:

df <- data.frame(study = c('A', 'A', 'B', 'C', 'D', 'D'),
                 similarity = c(0.61, 0.58, -0.605, 0.4, 0.607, 0.3))

df
   study similarity
1     A      0.610
2     A      0.580
3     B     -0.605
4     C      0.400
5     D      0.607
6     D      0.300

I want to order by absolute similarity, but keeping equal values of study together. For the above example the result should be:

   study similarity
1     A      0.610
2     A      0.580
5     D      0.607
6     D      0.300
3     B     -0.605
4     C      0.400

Body:
A solution using dplyr. This solution looks more complicated than others, but it aims to generate the expected output even if the study column is not in order, or there are ties in similarity from different study group.

First, Calculate the absolute value of each similarity (df2).

Second, Calcualte the maximum absolute of each study (df3).

Third,  Covert the study column to a factor column based on the order in df3. Arrange the columns based on study and absolute value (df4)

library(dplyr)

df2 <- df %>% mutate(ABS = abs(similarity))

df3 <- df2 %>%
  group_by(study) %>%
  summarise(Max_ABS = max(ABS)) %>%
  arrange(desc(Max_ABS))

df4 <- df2 %>%
  mutate(study = factor(study, levels = df3$study)) %>%
  arrange(study, desc(ABS)) %>%
  select(-ABS)
df4
#   study similarity
# 1     A      0.610
# 2     A      0.580
# 3     D      0.607
# 4     D      0.300
# 5     B     -0.605
# 6     C      0.400


问:
How to move pseudo-element under its parent block?
I want the green element to be under the text box and also under image.

I tried to set the z-index for each element, but nothing has changed.

Can I reach this through the z-index property?

I can't change html. And I also want the pseudo-element to be a child of the text block for the adaptive height

.item {
  display: flex;
  align-items: flex-start;
  width: 400px;
  height: 250px;
}

.col1 {
  margin-right: 20px;
}

.col2 {
  position: relative;
  z-index: 1;
  width: 200px;
  height: auto;
  padding: 5px;
  background-color: gray;
}

.col2::before {
  content: "";
  position: absolute;
  bottom: -20px;
  left: -60px;
  width: 150px;
  min-height: 100px;
  height: 100%;
  z-index: -1;
  background-color: seagreen;
}

.image {
  position: relative;
  z-index: 2;
  width: 200px;
  height: 150px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="item">
  <div class="col1">
    <img class="image" src="http://satyr.io/200x150/1" />
  </div>
  <div class="col2">
    <p class="title">Lorem ipsum dolor</p>
    <p class="text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima esse ipsam error repudiandae ut amet.</p>
  </div>
</div></code>```

答: Remove z-index: 1 from class .col2. So, the green block will appear under the image as well as the text box.

Body:
I want the green element to be under the text box and also under image.

I tried to set the z-index for each element, but nothing has changed.

Can I reach this through the z-index property?

I can't change html. And I also want the pseudo-element to be a child of the text block for the adaptive height

.item {
  display: flex;
  align-items: flex-start;
  width: 400px;
  height: 250px;
}

.col1 {
  margin-right: 20px;
}

.col2 {
  position: relative;
  z-index: 1;
  width: 200px;
  height: auto;
  padding: 5px;
  background-color: gray;
}

.col2::before {
  content: "";
  position: absolute;
  bottom: -20px;
  left: -60px;
  width: 150px;
  min-height: 100px;
  height: 100%;
  z-index: -1;
  background-color: seagreen;
}

.image {
  position: relative;
  z-index: 2;
  width: 200px;
  height: 150px;
}

Lorem ipsum dolor

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima esse ipsam error repudiandae ut amet.


问:
How can I define props?
I've seen props being define like:

```<code>props: ['message', 'name', 'something']
</code>```

and

```<code>props: {
    imperfectNumber: {
        type: Number,
        required: true
      }
 }
</code>```

Whats the difference and how can I define some props that require no validation and others that do all in the same block?

答:
Once you go down the object definition route, you have to do that with all the props. You can't mix them.

You can find more information about the props here:  https://v2.vuejs.org/v2/guide/components.html#Prop-Validation

Note:

Instead of defining the props as an array of strings, you can use an
object with validation requirements

I've highlighted the part in the manual that explains. This indicates you can do one or the other.

Title: How can I define props?

Body:
I've seen props being define like:

props: ['message', 'name', 'something']

and

props: {
    imperfectNumber: {
        type: Number,
        required: true
      }
 }

Whats the difference and how can I define some props that require no validation and others that do all in the same block?


问:
JPA-Repository read access commits outer transaction
I have a strange behaviour of Springs DB-Transaction handling I fail to wrap my head around.

Given the following code:

```<code>    @Transactional
    public void saveDocumentToDB() {

        dbService.addNewEntity('123', 'helloWorld');
        DbEntity dbEntity = dbService.getEntityByID('someId');

        throw new RuntimeException();
    }
</code>```

Where dbService is some @Service-class with access to a JPA-CrudRepository.

My Problem: the getEntityByID-Method which in turn calls a method on the auto-generated repository-object commits the transaction and thus writes the first 'add'-call to the Database.

Without this call, the transaction is rolled back nicely...

Do you have any advice how to make the auto-generated CRUD-Methods respect the transaction as well?

答:
In my application.properties, I used

spring.jpa.properties.hibernate.dialect: org.hibernate.dialect.MySQL5Dialect

which results in Hibernate generating its tables with MyISAM-Engine, which does not support transactions (and foreign-keys).

I changed it to

```<code>spring.jpa.properties.hibernate.dialect: org.hibernate.dialect.MySQL5InnoDBDialect
</code>```

and rebuilt the db-schema.

I find it quite unintuitive, that the alleged default "MySQL5Dialect" does not use the default Engine but MyISAM.

Maybe it helps someone in the future.

Body:
I have a strange behaviour of Springs DB-Transaction handling I fail to wrap my head around.

Given the following code:

    @Transactional
    public void saveDocumentToDB() {

        dbService.addNewEntity('123', 'helloWorld');
        DbEntity dbEntity = dbService.getEntityByID('someId');

        throw new RuntimeException();
    }

Where dbService is some @Service-class with access to a JPA-CrudRepository.

My Problem: the getEntityByID-Method which in turn calls a method on the auto-generated repository-object commits the transaction and thus writes the first 'add'-call to the Database.

Without this call, the transaction is rolled back nicely...

Do you have any advice how to make the auto-generated CRUD-Methods respect the transaction as well?

Body:
In my application.properties, I used

spring.jpa.properties.hibernate.dialect: org.hibernate.dialect.MySQL5Dialect

which results in Hibernate generating its tables with MyISAM-Engine, which does not support transactions (and foreign-keys).

I changed it to

spring.jpa.properties.hibernate.dialect: org.hibernate.dialect.MySQL5InnoDBDialect

and rebuilt the db-schema.

I find it quite unintuitive, that the alleged default "MySQL5Dialect" does not use the default Engine but MyISAM.

Maybe it helps someone in the future.


问:
How to pass variable from test function to fixture in pytest?
Below is the example code from contest.py

```<code>@pytest.fixture
def required_input(var1): # not sure if i can pass var1 to the fixture.
    return var1+"_test"
</code>```

below is the test case from test_code.py

```<code>def test_case1(required_input):
    x = required_input("tt")  # Not sure if it can be called like this.
    assert 'tt_test' == x
</code>```

How can I pass variable from my test function to a fixture?

答:
A fixture can be a function:</p>

```<code>@pytest.fixture
def required_input(): # not sure if i can pass var1 to the fixture.
    return lambda var1: return var1+"_test"
</code>```

Body:
Below is the example code from contest.py

@pytest.fixture
def required_input(var1): # not sure if i can pass var1 to the fixture.
    return var1+"_test"

below is the test case from test_code.py

def test_case1(required_input):
    x = required_input("tt")  # Not sure if it can be called like this.
    assert 'tt_test' == x

How can I pass variable from my test function to a fixture?

Body:
A fixture can be a function:

@pytest.fixture
def required_input(): # not sure if i can pass var1 to the fixture.
    return lambda var1: return var1+"_test"


问:
Exception in thread "main" java.util.InputMismatchException. Scanner-class
I've looked through some of the questions but I can't seem to find any good solutions.

I have a very simple code that just won't work. It's supposed to get the weight and height of the user, and then compute the BMI.

The values I put in is different everytime.
But lets say 85 for variable vikt and 1.80 for variable langd.
It does work when i use a , instead of a . though.
I get the following error.

```<code>Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextDouble(Scanner.java:2413)
    at Labb2.BMI.main(BMI.java:32)
C:\Users\Danne\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 5 seconds)
</code>```

The code I use is the following;

```<code>package Labb2;

import java.util.Scanner;

public class BMI {

    public static void main(String[] args) {

        Scanner viktObj = new Scanner(System.in);
        Scanner langdObj = new Scanner(System.in);

        double vikt;
        double langd;
        double bmi;

        System.out.print("Ange din vikt: ");
        vikt = viktObj.nextDouble();

        System.out.print("Ange din längd i meter (ex. 1.70): ");
        langd = langdObj.nextDouble();

        bmi = vikt / (langd * langd);
        System.out.printf("Ditt BMI är: %.2f", bmi);
        System.out.println("");

    }

}
</code>```

答:
Reason Why You getting error[Exception]:

When You are required to enter the Double,int and you enter String thn this exception occurs and stops your program.
You can get input with one Scanner only you can reuse one Scanner again and again no need to make another object of Scanner.Like i used

Note
Exception Handling not Explained because of beginner level. I recommend to first learn it yourself if problems feel free to ask.

Example When i getting InputMismatchException

Case when i am getting same error like you.

Body:
I've looked through some of the questions but I can't seem to find any good solutions.

I have a very simple code that just won't work. It's supposed to get the weight and height of the user, and then compute the BMI.

The values I put in is different everytime.
But lets say 85 for variable vikt and 1.80 for variable langd.
It does work when i use a , instead of a . though.
I get the following error.

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextDouble(Scanner.java:2413)
    at Labb2.BMI.main(BMI.java:32)
C:\Users\Danne\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 5 seconds)

The code I use is the following;

package Labb2;

import java.util.Scanner;

public class BMI {

    public static void main(String[] args) {

        Scanner viktObj = new Scanner(System.in);
        Scanner langdObj = new Scanner(System.in);

        double vikt;
        double langd;
        double bmi;

        System.out.print("Ange din vikt: ");
        vikt = viktObj.nextDouble();

        System.out.print("Ange din längd i meter (ex. 1.70): ");
        langd = langdObj.nextDouble();

        bmi = vikt / (langd * langd);
        System.out.printf("Ditt BMI är: %.2f", bmi);
        System.out.println("");

    }

}


问:
'aclocal-1.14' is missing when installing R package in docker container
I am trying to install the package flowDensity when building a docker container using the latest bioconductor image release_core2. I receive the following error:

ERROR: dependencies ‘rgeos’, ‘flowWorkspace’ are not available for
  package ‘flowDensity’

I could fix the first one by adding apt-get install libgeos-dev to the dockerfile. However, the second one is more tricky. It comes down to the package RProtoBufLib, which is a dependency for cytolib and hence for flowWorkspace. I receive the following error when installing RProtoBufLib:

```<code>config.status: error: cannot find input file: `config.h.in'
CDPATH="${ZSH_VERSION+.}:" && cd . && /bin/bash /tmp/Rtmpro4BMN/R.INSTALL65e11754ab1d/RProtoBufLib/src/protobuf-2.6.0/missing aclocal-1.14 -I m4
/tmp/Rtmpro4BMN/R.INSTALL65e11754ab1d/RProtoBufLib/src/protobuf-2.6.0/missing: line 81: aclocal-1.14: command not found
WARNING: 'aclocal-1.14' is missing on your system.
         You should only need it if you modified 'acinclude.m4' or
         'configure.ac' or m4 files included by 'configure.ac'.
         The 'aclocal' program is part of the GNU Automake package:
         <http://www.gnu.org/software/automake>
         It also requires GNU Autoconf, GNU m4 and Perl in order to run:
         <http://www.gnu.org/software/autoconf>
         <http://www.gnu.org/software/m4/>
         <http://www.perl.org/>
make: *** [aclocal.m4] Error 127
Makefile:407: recipe for target 'aclocal.m4' failed
</code>```

I found this question, but I have no idea how to go about this when building a docker container. Any suggestions are welcome. Thanks!

答:
I've recreated your issue on my local environment. The problem is that you don't have automake, autoconf and libtoolize installed.

These are my install.R and Dockerfile script.

install.R:

```<code>install.packages( c('RProtoBufLib', 'flowDensity'), dependencies = TRUE, repos = c('http://bioconductor.org/packages/3.6/bioc', 'https://cloud.r-project.org') )
</code>```

Dockerfile:

```<code>FROM bioconductor/release_core2

RUN apt-get update \
    && apt-get install -y --no-install-recommends \
          libgeos-dev ed \
          automake autoconf libtool \
    && rm -rf /var/lib/apt/lists/*

ADD install.R /tmp

RUN Rscript /tmp/install.R \
    && rm -rf /tmp/downloaded_packages/ /tmp/*.rds \
    && rm -rf /var/lib/apt/lists/* \
    && rm -rf /usr/share/info/* \
    && rm -rf /usr/share/man/* \
    && rm -rf /usr/share/doc/* \
    && rm -rf /var/lib/dpkg/info
</code>```

In order to build the project I've executed this command:

```<code>docker build -t rbiotest .
</code>```

NOTE: Build time will seem eternal.

Body:
I am trying to install the package flowDensity when building a docker container using the latest bioconductor image release_core2. I receive the following error:

ERROR: dependencies ‘rgeos’, ‘flowWorkspace’ are not available for
  package ‘flowDensity’

I could fix the first one by adding apt-get install libgeos-dev to the dockerfile. However, the second one is more tricky. It comes down to the package RProtoBufLib, which is a dependency for cytolib and hence for flowWorkspace. I receive the following error when installing RProtoBufLib:

config.status: error: cannot find input file: `config.h.in'
CDPATH="${ZSH_VERSION+.}:" && cd . && /bin/bash /tmp/Rtmpro4BMN/R.INSTALL65e11754ab1d/RProtoBufLib/src/protobuf-2.6.0/missing aclocal-1.14 -I m4
/tmp/Rtmpro4BMN/R.INSTALL65e11754ab1d/RProtoBufLib/src/protobuf-2.6.0/missing: line 81: aclocal-1.14: command not found
WARNING: 'aclocal-1.14' is missing on your system.
         You should only need it if you modified 'acinclude.m4' or
         'configure.ac' or m4 files included by 'configure.ac'.
         The 'aclocal' program is part of the GNU Automake package:
         <http://www.gnu.org/software/automake>
         It also requires GNU Autoconf, GNU m4 and Perl in order to run:
         <http://www.gnu.org/software/autoconf>
         <http://www.gnu.org/software/m4/>
         <http://www.perl.org/>
make: *** [aclocal.m4] Error 127
Makefile:407: recipe for target 'aclocal.m4' failed

I found this question, but I have no idea how to go about this when building a docker container. Any suggestions are welcome. Thanks!

Body:
I've recreated your issue on my local environment. The problem is that you don't have automake, autoconf and libtoolize installed.

These are my install.R and Dockerfile script.

install.R:

install.packages( c('RProtoBufLib', 'flowDensity'), dependencies = TRUE, repos = c('http://bioconductor.org/packages/3.6/bioc', 'https://cloud.r-project.org') )

Dockerfile:

FROM bioconductor/release_core2

RUN apt-get update \
    && apt-get install -y --no-install-recommends \
          libgeos-dev ed \
          automake autoconf libtool \
    && rm -rf /var/lib/apt/lists/*

ADD install.R /tmp

RUN Rscript /tmp/install.R \
    && rm -rf /tmp/downloaded_packages/ /tmp/*.rds \
    && rm -rf /var/lib/apt/lists/* \
    && rm -rf /usr/share/info/* \
    && rm -rf /usr/share/man/* \
    && rm -rf /usr/share/doc/* \
    && rm -rf /var/lib/dpkg/info

In order to build the project I've executed this command:

docker build -t rbiotest .

NOTE: Build time will seem eternal.


问:
PHP: How to iterate over array to retrieve incremental value (n, n+1, etc)
I have an array like this

```<code>$data = array(51729,49359,47548,8242,8124,8716,19610,18030,15698);
</code>```

And a index number

```<code>$index = 3;
</code>```

Is there a simple way to iterate over $data to get

```<code>$first = array(51729,8242,19610)
$second = array(49359,8124,18030)
$third = array(47548,8716,15698)
</code>```

Is array_chunk() and then foreach the chunks the way to go?

Edit: Here is how I made it with array_chunk()

```<code>$data = array(51729,49359,47548,8242,8124,8716,19610,18030,15698);
$index = 3;
$chunks = array_chunk($data, $index);
$first = array();
$second = array();
$third = array();
foreach($chunks as $out) {
    $first[] = $out[0];
    $second[] = $out[1];
    $third[] = $out[2];
}
</code>```

Edit 2: All of this is part of transforming a unidimensional array to multidimensional, naming will eventually be dynamic, based on values in array $labels. Index number is also going to change ($index is provided in original array).

答:
To do it dynamically, you can create a multidimensional array.

```<code>// Your provided values
$data = array(51729,49359,47548,8242,8124,8716,19610,18030,15698);
$index = 3;

// Initialize your result array
$result = array();

// Loop through the array
foreach ($data as $key => $value) {
    // Assign every nth to the appropriate sub-array
    $result[$key % $index][] = $value;
}

// Print for validation
print_r($result);
</code>```

Provides:

```<code>Array
(
    [0] => Array
        (
            [0] => 51729
            [1] => 8242
            [2] => 19610
        )

    [1] => Array
        (
            [0] => 49359
            [1] => 8124
            [2] => 18030
        )

    [2] => Array
        (
            [0] => 47548
            [1] => 8716
            [2] => 15698
        )

)
</code>```

Body:
I have an array like this

$data = array(51729,49359,47548,8242,8124,8716,19610,18030,15698);

And a index number

$index = 3;

Is there a simple way to iterate over $data to get

$first = array(51729,8242,19610)
$second = array(49359,8124,18030)
$third = array(47548,8716,15698)

Is array_chunk() and then foreach the chunks the way to go?

Edit: Here is how I made it with array_chunk()

$data = array(51729,49359,47548,8242,8124,8716,19610,18030,15698);
$index = 3;
$chunks = array_chunk($data, $index);
$first = array();
$second = array();
$third = array();
foreach($chunks as $out) {
    $first[] = $out[0];
    $second[] = $out[1];
    $third[] = $out[2];
}

Edit 2: All of this is part of transforming a unidimensional array to multidimensional, naming will eventually be dynamic, based on values in array $labels. Index number is also going to change ($index is provided in original array).

Body:
To do it dynamically, you can create a multidimensional array.

// Your provided values
$data = array(51729,49359,47548,8242,8124,8716,19610,18030,15698);
$index = 3;

// Initialize your result array
$result = array();

// Loop through the array
foreach ($data as $key => $value) {
    // Assign every nth to the appropriate sub-array
    $result[$key % $index][] = $value;
}

// Print for validation
print_r($result);

Provides:

Array
(
    [0] => Array
        (
            [0] => 51729
            [1] => 8242
            [2] => 19610
        )

    [1] => Array
        (
            [0] => 49359
            [1] => 8124
            [2] => 18030
        )

    [2] => Array
        (
            [0] => 47548
            [1] => 8716
            [2] => 15698
        )

)


问:
Promise override causes then calls to error
I have the following sample code.

```<code>class test extends Promise {
    constructor(executor) {
        super(executor)
    }

    static getPromise() {
        return new test((res, rej) => {
            res(true)
        })
    }
}

let t = test.getPromise()
t.then(value => {console.log("Works")},
       value => {console.log("Works")})
</code>```

this works just fine, but if I were to put the same function directly into the super function, it throws an error.

```<code>class test extends Promise {
    constructor(executor) {
        super((res, rej) => {
            res(true)
        })
    }

    static getPromise() {
        return new test((res, rej) => {
            res(true)
        })
    }
}

let t = test.getPromise()
t.then(value => {console.log("Works")},
       value => {console.log("Works")})
</code>```

the error is TypeError: Promise resolve or reject function is not callable Why is this happening, aren't these two pieces of code equivalent?

My goal is to simplify use of my library by simply having:

```<code>let t = new test()
t.then(value => {console.log("Works")},
       value => {console.log("Works")})
</code>```

I understand this is not much of a simplification, I am ok with keeping the static function if required, but I am more curious as to why this is not working.

my questions are:

Why are these not equivalent, and why is this erroring?

How can I make this work as I expect?

EDIT:

Thanks to Bergi, I came to the realization that the promise class I am overriding is using the test constructor for the "then" functions. While I was assuming it was using the original constructor. It is obvious in hindsight, but my fix ended up being simply adding this to the constructor.

```<code>if(!executor) executor = (res, rej) => { res(true) }
</code>```

答:
Why are these not equivalent, and why is this erroring?

Your overridden constructor does never call the executor and pass it the promise resolving functions (resolve and reject). They are important! You cannot subclass Promise and change the interface like that.

Why does this throw an error when you call new test() that doesn't use the constructor? It does not. It throws the error when you call t.then(…), which tries to construct a new promise (for its return value) and uses t's constructor for that. It does pass a proper executor callback, and expects it to be called synchronously with resolve and reject - which your code does not do. After the call, it bitches about not having got two functions.

How can I make this work as I expect?

Don't use promise subclassing. There's no reason for it. You just want to have a normal function that returns a promise. Use

```<code>const test = {
    getPromise() {
        return Promise.resolve(true)
    }
};
test.getPromise().then(…);
</code>```

or

```<code>function test() {
    return Promise.resolve(true);
}
test().then(…);
</code>```

Body:
I have the following sample code.

class test extends Promise {
    constructor(executor) {
        super(executor)
    }

    static getPromise() {
        return new test((res, rej) => {
            res(true)
        })
    }
}

let t = test.getPromise()
t.then(value => {console.log("Works")},
       value => {console.log("Works")})

this works just fine, but if I were to put the same function directly into the super function, it throws an error.

class test extends Promise {
    constructor(executor) {
        super((res, rej) => {
            res(true)
        })
    }

    static getPromise() {
        return new test((res, rej) => {
            res(true)
        })
    }
}

let t = test.getPromise()
t.then(value => {console.log("Works")},
       value => {console.log("Works")})

the error is TypeError: Promise resolve or reject function is not callable Why is this happening, aren't these two pieces of code equivalent?

My goal is to simplify use of my library by simply having:

let t = new test()
t.then(value => {console.log("Works")},
       value => {console.log("Works")})

I understand this is not much of a simplification, I am ok with keeping the static function if required, but I am more curious as to why this is not working.

my questions are:

Why are these not equivalent, and why is this erroring?

How can I make this work as I expect?

EDIT:

Thanks to Bergi, I came to the realization that the promise class I am overriding is using the test constructor for the "then" functions. While I was assuming it was using the original constructor. It is obvious in hindsight, but my fix ended up being simply adding this to the constructor.

if(!executor) executor = (res, rej) => { res(true) }

Body:
Why are these not equivalent, and why is this erroring?

Your overridden constructor does never call the executor and pass it the promise resolving functions (resolve and reject). They are important! You cannot subclass Promise and change the interface like that.

Why does this throw an error when you call new test() that doesn't use the constructor? It does not. It throws the error when you call t.then(…), which tries to construct a new promise (for its return value) and uses t's constructor for that. It does pass a proper executor callback, and expects it to be called synchronously with resolve and reject - which your code does not do. After the call, it bitches about not having got two functions.

How can I make this work as I expect?

Don't use promise subclassing. There's no reason for it. You just want to have a normal function that returns a promise. Use

const test = {
    getPromise() {
        return Promise.resolve(true)
    }
};
test.getPromise().then(…);

or

function test() {
    return Promise.resolve(true);
}
test().then(…);


问:
How to read a sequence of integers from Standard-input with Stdin?
I'm using java on command lines, i want to write a programm that could filter and removes the duplicates of a sequence of integers but first of all i don't know how to use StdIn to read a sequnce of Integers.

The Programm should read values from Standard input until it reach the EOF-Sequence with the help of StdIn.

Input and Output example on Command line:

```<code>$ echo 1 1 2 2 1 1 3 4 6 2 1 | java RemoveDuplicates
1 2 1 3 4 6 2 1
</code>```

I've tried to convert the Integers to an array

```<code>int[] n = StdIn.readAllInts();
</code>```

but it doesn't work when tried to print it out.
can anybody give me some tips?

答:
You should be able to catch it as a string with a normal scanner:

```<code>Scanner in = new Scanner(System.in);
String line = in.nextLine();
</code>```

sometimes the second line don't work for some inputs, so you can also try:

```<code>String line = in.next();
</code>```

to get the numbers as integers you can use inputStream, but I'm not sure how will work.

Body:
I'm using java on command lines, i want to write a programm that could filter and removes the duplicates of a sequence of integers but first of all i don't know how to use StdIn to read a sequnce of Integers.

The Programm should read values from Standard input until it reach the EOF-Sequence with the help of StdIn.

Input and Output example on Command line:

$ echo 1 1 2 2 1 1 3 4 6 2 1 | java RemoveDuplicates
1 2 1 3 4 6 2 1

I've tried to convert the Integers to an array

int[] n = StdIn.readAllInts();

but it doesn't work when tried to print it out.
can anybody give me some tips?

Body:
You should be able to catch it as a string with a normal scanner:

Scanner in = new Scanner(System.in);
String line = in.nextLine();

sometimes the second line don't work for some inputs, so you can also try:

String line = in.next();

to get the numbers as integers you can use inputStream, but I'm not sure how will work.


答:
The issue is because the \u at the start of the string is being interpreted as Unicode. Hence the error you see in the console.

To avoid this problem you need to use \\ to escape the single slashes in the string:

var filePath = "\\upload\\document\\file.txt";
filePath = filePath.replace('\\upload', '');
console.log(filePath);```

Title: JQuery remove backslash with some words in string

Body:
my string is "\upload\document\file.txt", i want to remove the "\upload" part in that string with jQuery. I try this one but it does not work:

var filePath = "\upload\document\file.txt";
filePath = filePath.replace('\upload', '');
console.log(filePath);


问:
Prevent Component reloading - AEM
I have 2 pages in my web application. Lets say an home page and news feed page. When user clicks a hyperlink on home page then she/ he gets redirected to News feed page. I have 2 separate components in each page like

Home Page --- Header Component & Home Page Details Component.
News Feed Page --- Header Component & News Feed Details Component.

Both the pages has a common component Header. Can I prevent component reloading for the header component when users reaches the second page by clicking link on the first page.

By component reloading I mean the HTML code (HTL) code in the component should not be updated again with updated data instead for the second page, I just want to show the same data associated with header component in the first page.

答:
This is a very common HTML pattern and possible duplicate of related questions such as: How to auto refresh a section of a page

There are two general approaches, the first being far preferred and supported in various frameworks, all based on JavaScript (AJAX):

Break page into different DIV tags that are independently updated (header separate from body sections, each loaded via AJAX such that only part of the page that has changed is updated).

Use iFrames such that effectively there are different pages - each loaded separately from the other.

Title: Prevent Component reloading - AEM


问:
Angular Component error in the console: ERROR TypeError: Cannot read property '1' of undefined
Currently I’m getting this strange error in my Chrome console. I don’t understand how to approach in solving it.

```<code>PractiseLayoutComponent.html:10 ERROR TypeError: Cannot read property '1' of undefined
    at Object.eval [as updateRenderer] (PractiseLayoutComponent.html:10)
    at Object.debugUpdateRenderer [as updateRenderer] (core.es5.js:13105)
    at checkAndUpdateView (core.es5.js:12256)
    at callViewAction (core.es5.js:12599)
    at execComponentViewsAction (core.es5.js:12531)
    at checkAndUpdateView (core.es5.js:12257)
    at callViewAction (core.es5.js:12599)
    at execComponentViewsAction (core.es5.js:12531)
    at checkAndUpdateView (core.es5.js:12257)
    at callWithDebugContext (core.es5.js:13467)
</code>```

Probably I’ve done something wrong. Unfortunately, it is very costly to revert changes.
Anyway I definitely should get know how to cope with such a situation.
Could anyone give some advice where to dig?

There is no error from ng serve in the terminal.

答: You should look into your PractiseLayoutComponent.html at line 10. There might be something missing there.</p>

Body:
Currently I’m getting this strange error in my Chrome console. I don’t understand how to approach in solving it.

PractiseLayoutComponent.html:10 ERROR TypeError: Cannot read property '1' of undefined
    at Object.eval [as updateRenderer] (PractiseLayoutComponent.html:10)
    at Object.debugUpdateRenderer [as updateRenderer] (core.es5.js:13105)
    at checkAndUpdateView (core.es5.js:12256)
    at callViewAction (core.es5.js:12599)
    at execComponentViewsAction (core.es5.js:12531)
    at checkAndUpdateView (core.es5.js:12257)
    at callViewAction (core.es5.js:12599)
    at execComponentViewsAction (core.es5.js:12531)
    at checkAndUpdateView (core.es5.js:12257)
    at callWithDebugContext (core.es5.js:13467)

Probably I’ve done something wrong. Unfortunately, it is very costly to revert changes.
Anyway I definitely should get know how to cope with such a situation.
Could anyone give some advice where to dig?

There is no error from ng serve in the terminal.


问:
Texel data in case of GL_LUMINANCE when glTexImage2D is called
Usually a texel is an RGBA value. What data does a texel represent in the following code:</p>

```<code>const int TEXELS_W = 2, TEXELS_H = 2;
GLubyte texels[] = {
    100, 200,  0,  0,
    200,  250,  0,  0
};
glBindTexture(GL_TEXTURE_2D, textureId);
glTexImage2D(
    GL_TEXTURE_2D,
    0,                  // mipmap reduction level
    GL_LUMINANCE,
    TEXELS_W,
    TEXELS_H,
    0,                  // border (must be 0)
    GL_LUMINANCE,
    GL_UNSIGNED_BYTE,
    texels);
</code>```

答:
GL_LUMINANCE:

Each element is a single luminance value.  The GL converts it to floating point, then assembles it into an RGBA element by replicating the luminance value three times for red, green, and blue and attaching 1 for alpha.  Each component is then multiplied by the signed scale factor GL_c_SCALE, added to the signed bias GL_c_BIAS, and clamped to the range [0,1] (see glPixelTransfer).

Body:
Usually a texel is an RGBA value. What data does a texel represent in the following code:

const int TEXELS_W = 2, TEXELS_H = 2;
GLubyte texels[] = {
    100, 200,  0,  0,
    200,  250,  0,  0
};
glBindTexture(GL_TEXTURE_2D, textureId);
glTexImage2D(
    GL_TEXTURE_2D,
    0,                  // mipmap reduction level
    GL_LUMINANCE,
    TEXELS_W,
    TEXELS_H,
    0,                  // border (must be 0)
    GL_LUMINANCE,
    GL_UNSIGNED_BYTE,
    texels);


问:
Crash validating related model created using inline admin
I'm creating a one-to-one model to extend the functionality of an existing model type, but I want it to only allow creating the extension model in certain cases. I enforce this constraint by throwing a ValidationError in the full_clean on the new Extended model. This works great when I create Extended models using Extended's ModelAdmin directly (it highlights the a field if it's the wrong type), but when I use StackedInline to inline Extended creation in As ModelAdmin, and A is the wrong type, the form fails to catch the ValidationError and I get the message A server error occurred.  Please contact the administrator.

This is how I have the models set up:

```<code># models.py
from django.db import models

class A(models.Model):
    type = models.IntegerField(...)

class Extended(models.Model)
    a = models.OneToOneField(A)

    def clean_fields(self, **kwargs):
        if self.a.type != 3:
            raise ValidationError({'a': ["a must be of type 3"]})
        super(Extended, self).clean_fields(**kwargs)

    def save(self, *args, **kwargs):
        self.full_clean()
        super(Extended, self).save(*args, **kwargs)

# admin.py
from django.contrib import admin

class ExtendedInline(admin.StackedInline):
    model = Extended

@admin.register(A)
class AAdmin(admin.ModelAdmin):
    inlines = (ExtendedInline,)
</code>```

The full traceback:

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python2.7/wsgiref/handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__
    return self.application(environ, start_response)
  File "/usr/local/lib/python2.7/site-packages/whitenoise/base.py", line 66, in __call__
    return self.application(environ, start_response)
  File "/usr/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 189, in __call__
    response = self.get_response(request)
  File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 218, in get_response
    response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
  File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 618, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 110, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 233, in inner
    return view(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1521, in change_view
    return self.changeform_view(request, object_id, form_url, extra_context)
  File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 34, in _wrapper
    return bound_func(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 110, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 30, in bound_func
    return func.__get__(self, type(self))(*args2, **kwargs2)
  File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 145, in inner
    return func(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1470, in changeform_view
    self.save_related(request, form, formsets, not add)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1104, in save_related
    self.save_formset(request, form, formset, change=change)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1092, in save_formset
    formset.save()
  File "/usr/local/lib/python2.7/site-packages/django/forms/models.py", line 636, in save
    return self.save_existing_objects(commit) + self.save_new_objects(commit)
  File "/usr/local/lib/python2.7/site-packages/django/forms/models.py", line 767, in save_new_objects
    self.new_objects.append(self.save_new(form, commit=commit))
  File "/usr/local/lib/python2.7/site-packages/django/forms/models.py", line 900, in save_new
    obj.save()
  File "/code/app/models.py", line 162, in save
    self.full_clean()
  File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py", line 1171, in full_clean
    raise ValidationError(errors)
ValidationError: {'a': [u'a must be of type 3']}
</code>```

I'm currently using Django version 1.8

答:
Inline foreignkeys are excluded on the calls to full_clean() that happen in modelform validators, so your ValidationError is not being caught by the form's is_valid() call.

From django/forms/models.py:

```<code>def _post_clean(self):
    opts = self._meta

    exclude = self._get_validation_exclusions()

    try:
        self.instance = construct_instance(self, self.instance, opts.fields, exclude)
    except ValidationError as e:
        self._update_errors(e)

    # Foreign Keys being used to represent inline relationships
    # are excluded from basic field value validation. This is for two
    # reasons: firstly, the value may not be supplied (#12507; the
    # case of providing new values to the admin); secondly the
    # object being referred to may not yet fully exist (#12749).
    # However, these fields *must* be included in uniqueness checks,
    # so this can't be part of _get_validation_exclusions().
    for name, field in self.fields.items():
        if isinstance(field, InlineForeignKeyField):
            exclude.append(name)

    try:
        self.instance.full_clean(exclude=exclude, validate_unique=False)
    except ValidationError as e:
        self._update_errors(e)

    # Validate uniqueness if needed.
    if self._validate_unique:
        self.validate_unique()
</code>```

They're being caught in save() instead (where you call full_clean without the exclusion), which is too late.

Move your validation to clean() instead:

```<code>def clean(self):
    if self.a.type != 3:
        raise ValidationError({'a': ["a must be of type 3"]})
</code>```

Then there will be no need to call full_clean from your save method. This method is where any validation of this sort should go as per the docs.

Body:
I'm creating a one-to-one model to extend the functionality of an existing model type, but I want it to only allow creating the extension model in certain cases. I enforce this constraint by throwing a ValidationError in the full_clean on the new Extended model. This works great when I create Extended models using Extended's ModelAdmin directly (it highlights the a field if it's the wrong type), but when I use StackedInline to inline Extended creation in As ModelAdmin, and A is the wrong type, the form fails to catch the ValidationError and I get the message A server error occurred.  Please contact the administrator.

This is how I have the models set up:

# models.py
from django.db import models

class A(models.Model):
    type = models.IntegerField(...)

class Extended(models.Model)
    a = models.OneToOneField(A)

    def clean_fields(self, **kwargs):
        if self.a.type != 3:
            raise ValidationError({'a': ["a must be of type 3"]})
        super(Extended, self).clean_fields(**kwargs)

    def save(self, *args, **kwargs):
        self.full_clean()
        super(Extended, self).save(*args, **kwargs)

# admin.py
from django.contrib import admin

class ExtendedInline(admin.StackedInline):
    model = Extended

@admin.register(A)
class AAdmin(admin.ModelAdmin):
    inlines = (ExtendedInline,)

The full traceback:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/wsgiref/handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__
    return self.application(environ, start_response)
  File "/usr/local/lib/python2.7/site-packages/whitenoise/base.py", line 66, in __call__
    return self.application(environ, start_response)
  File "/usr/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 189, in __call__
    response = self.get_response(request)
  File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 218, in get_response
    response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
  File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 618, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 110, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 233, in inner
    return view(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1521, in change_view
    return self.changeform_view(request, object_id, form_url, extra_context)
  File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 34, in _wrapper
    return bound_func(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 110, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 30, in bound_func
    return func.__get__(self, type(self))(*args2, **kwargs2)
  File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 145, in inner
    return func(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1470, in changeform_view
    self.save_related(request, form, formsets, not add)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1104, in save_related
    self.save_formset(request, form, formset, change=change)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1092, in save_formset
    formset.save()
  File "/usr/local/lib/python2.7/site-packages/django/forms/models.py", line 636, in save
    return self.save_existing_objects(commit) + self.save_new_objects(commit)
  File "/usr/local/lib/python2.7/site-packages/django/forms/models.py", line 767, in save_new_objects
    self.new_objects.append(self.save_new(form, commit=commit))
  File "/usr/local/lib/python2.7/site-packages/django/forms/models.py", line 900, in save_new
    obj.save()
  File "/code/app/models.py", line 162, in save
    self.full_clean()
  File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py", line 1171, in full_clean
    raise ValidationError(errors)
ValidationError: {'a': [u'a must be of type 3']}

I'm currently using Django version 1.8

Body:
Inline foreignkeys are excluded on the calls to full_clean() that happen in modelform validators, so your ValidationError is not being caught by the form's is_valid() call.

From django/forms/models.py:

def _post_clean(self):
    opts = self._meta

    exclude = self._get_validation_exclusions()

    try:
        self.instance = construct_instance(self, self.instance, opts.fields, exclude)
    except ValidationError as e:
        self._update_errors(e)

    # Foreign Keys being used to represent inline relationships
    # are excluded from basic field value validation. This is for two
    # reasons: firstly, the value may not be supplied (#12507; the
    # case of providing new values to the admin); secondly the
    # object being referred to may not yet fully exist (#12749).
    # However, these fields *must* be included in uniqueness checks,
    # so this can't be part of _get_validation_exclusions().
    for name, field in self.fields.items():
        if isinstance(field, InlineForeignKeyField):
            exclude.append(name)

    try:
        self.instance.full_clean(exclude=exclude, validate_unique=False)
    except ValidationError as e:
        self._update_errors(e)

    # Validate uniqueness if needed.
    if self._validate_unique:
        self.validate_unique()

They're being caught in save() instead (where you call full_clean without the exclusion), which is too late.

Move your validation to clean() instead:

def clean(self):
    if self.a.type != 3:
        raise ValidationError({'a': ["a must be of type 3"]})

Then there will be no need to call full_clean from your save method. This method is where any validation of this sort should go as per the docs.


问:
Why can't I pass a const object in a const argument function/method?
EDIT:

Sorry, I'm trying to understand a sample of code, which uses QList::indexOf method, declared as in here.

Actually I'm trying to figure out why I need to use const_cast in this specific case:

```<code>int ProjTreeItem::row() const
{
    if (parentItem) {
            // instance of const object to test
        const ProjTreeItem *item = new ProjTreeItem(QList<QVariant>(), NULL);
            // Called indexOf here to test
        parentItem->childItems.indexOf(item);
            // This works fine
        return parentItem->childItems.indexOf(const_cast<ProjTreeItem*>(this));
    }
    return 0;
}
</code>```

EDIT2:

I was looking at the wrong places, then I started to suspect that the issue had to do with the use of templates and the const modifier. I found this thread here. Please, look at Jon 's answer, which I think clarifies the point I reached. Sorry for the misleadings on my question.

答:
Hmmmm works for me with this code:</p>

```<code>class MyClass
{
};

class SomeClass
{
public:
    void f(const MyClass *t) const
    {
    }
};

int main()
{
    SomeClass s;

    const MyClass *myClass = new MyClass;
    MyClass *myClass2 = new MyClass;

    s.f(myClass);
    s.f(myClass2);

    return 0;
}
</code>```

Body:
EDIT:

Sorry, I'm trying to understand a sample of code, which uses QList::indexOf method, declared as in here.

Actually I'm trying to figure out why I need to use const_cast in this specific case:

int ProjTreeItem::row() const
{
    if (parentItem) {
            // instance of const object to test
        const ProjTreeItem *item = new ProjTreeItem(QList<QVariant>(), NULL);
            // Called indexOf here to test
        parentItem->childItems.indexOf(item);
            // This works fine
        return parentItem->childItems.indexOf(const_cast<ProjTreeItem*>(this));
    }
    return 0;
}

EDIT2:

I was looking at the wrong places, then I started to suspect that the issue had to do with the use of templates and the const modifier. I found this thread here. Please, look at Jon 's answer, which I think clarifies the point I reached. Sorry for the misleadings on my question.

Body:
Hmmmm works for me with this code:

class MyClass
{
};

class SomeClass
{
public:
    void f(const MyClass *t) const
    {
    }
};

int main()
{
    SomeClass s;

    const MyClass *myClass = new MyClass;
    MyClass *myClass2 = new MyClass;

    s.f(myClass);
    s.f(myClass2);

    return 0;
}


问:
Expressjs Error: Headers ServerResponse.OutgoingMessage.setHeader
On my signup user account Express 4 app, I get this error:

```<code>Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
</code>```

Error occurs only when trying to sign up, with an existing email, then an existing username. (I get the flash messages as expected).

Signups using  unique emails and unique usernames work perfectly.

I learned that the error can be:
* error usually happens when people treat an async response inside an express route as a synchronous response and they end up sending data twice.*

I don't see where I'm sending the "data twice"

Thanks for help - Rob

CODE

```<code>/**
 * GET /signup
 * Signup page.
 */
exports.getSignup = (req, res) => {
  if (req.user) {
    return res.redirect('/account');
  }
  res.render('account/signup', {
    title: 'Create Account'
  });
};

/**
 * POST /signup
 * Create a new local account.
 */

exports.postSignup = (req, res, next) => {
  req.assert('email', 'Email is not valid').isEmail();
  req.check('username', 'username must be 6-50 lower case characters, only letters and numbers, no spaces allowed.').isAlphanumeric().isLowercase().len(6);
  req.sanitize('email').normalizeEmail({
    gmail_remove_dots: false
  });

  const errors = req.validationErrors();

  if (errors) {
    req.flash('errors', errors);
    return res.redirect('/signup');
  }

  const user = new User({
    email: req.body.email,
    username: req.body.username,
    // password: req.body.password
  });

  User.findOne({
    email: req.body.email
  }, (err, existingUser) => {
    if (err) {
      return next(err);
    }
    if (existingUser) {
      req.flash('errors', {
        msg: 'Account with that email address already exists.'
      });
      return res.redirect('/signup');
    }
  });

  User.findOne({
    username: req.body.username
  }, (err, existingUser) => {
    if (err) {
      return next(err);
    }
    if (existingUser) {
      req.flash('errors', {
        msg: 'Account with that username name already exists.'
      });
      return res.redirect('/signup');
    }

  });

  user.save((err) => {
    if (err) {
      return next(err);
    }
    req.logIn(user, (err) => {
      if (err) {
        return next(err);
      }
      // doesn't wokr either res.redirect('/account');
      return res.redirect('/account');
    });
  });
};
</code>```

** NOTE **
- my code started with
- https://github.com/sahat/hackathon-starter/blob/731ec259c3d17fbee8171f2d280cbdf283177b76/controllers/user.js
- I added the username to the signup form

答:
I  have it working, using $or: in the findOne statement. (my Gist, "nested" solution didn't seem to always work)

```<code>User.findOne({$or: [
      {email: req.body.email},
      {username: req.body.username}
      ]
      }).exec(function(err, existingUser){
</code>```

but I do wonder if I should be using a promise with this solution?

Full code here.

```<code>/**
 * POST /signup
 * Create a new local account.
 */

exports.postSignup = (req, res, next) => {
  req.assert('email', 'Email is not valid').isEmail();
  req.check('username', 'username must be 6-50 lower case characters, only letters and numbers, no spaces allowed.').isAlphanumeric().isLowercase().len(6);
  req.sanitize('email').normalizeEmail({
    gmail_remove_dots: false
  });

  const errors = req.validationErrors();

  if (errors) {
    req.flash('errors', errors);
    return res.redirect('/signup');
  }

  const user = new User({
    email: req.body.email,
    username: req.body.username,
    // password: req.body.password
  });

  User.findOne({$or: [
      {email: req.body.email},
      {username: req.body.username}
      ]
      }).exec(function(err, existingUser){

    // console.log('existingUser.email ' + existingUser.email)
    // console.log('existingUser.email ' + existingUser.username)

    if (!existingUser){
      console.log('now existing user was found');
      console.log('no users with that email NOR phone exist');
      user.save((err) => {
        if (err) { return next(err); }
        req.logIn(user, (err) => {
          if (err) {
            return next(err);
          }
          res.redirect('/account');
        });
      });
    } else if (existingUser.email == req.body.email) {
        console.log('user already exists with EMAIL ');
        req.flash('errors', { msg: 'Account with that EMAIL  already exists.' });
        return res.redirect('/signup');
      }
      else if (existingUser.username = req.body.username){
        console.log('user already exists with USERNAME.');
        req.flash('errors', { msg: 'Account with that USERNAME  already exists.' });
        return res.redirect('/signup');

      }
      else {
      // nothing
        return res.redirect('/signup');
      }

  });

}; // END exports.postSignup {}
</code>```

Body:
On my signup user account Express 4 app, I get this error:

Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)

Error occurs only when trying to sign up, with an existing email, then an existing username. (I get the flash messages as expected).

Signups using  unique emails and unique usernames work perfectly.

I learned that the error can be:
* error usually happens when people treat an async response inside an express route as a synchronous response and they end up sending data twice.*

I don't see where I'm sending the "data twice"

Thanks for help - Rob

CODE

/**
 * GET /signup
 * Signup page.
 */
exports.getSignup = (req, res) => {
  if (req.user) {
    return res.redirect('/account');
  }
  res.render('account/signup', {
    title: 'Create Account'
  });
};

/**
 * POST /signup
 * Create a new local account.
 */

exports.postSignup = (req, res, next) => {
  req.assert('email', 'Email is not valid').isEmail();
  req.check('username', 'username must be 6-50 lower case characters, only letters and numbers, no spaces allowed.').isAlphanumeric().isLowercase().len(6);
  req.sanitize('email').normalizeEmail({
    gmail_remove_dots: false
  });

  const errors = req.validationErrors();

  if (errors) {
    req.flash('errors', errors);
    return res.redirect('/signup');
  }

  const user = new User({
    email: req.body.email,
    username: req.body.username,
    // password: req.body.password
  });

  User.findOne({
    email: req.body.email
  }, (err, existingUser) => {
    if (err) {
      return next(err);
    }
    if (existingUser) {
      req.flash('errors', {
        msg: 'Account with that email address already exists.'
      });
      return res.redirect('/signup');
    }
  });

  User.findOne({
    username: req.body.username
  }, (err, existingUser) => {
    if (err) {
      return next(err);
    }
    if (existingUser) {
      req.flash('errors', {
        msg: 'Account with that username name already exists.'
      });
      return res.redirect('/signup');
    }

  });

  user.save((err) => {
    if (err) {
      return next(err);
    }
    req.logIn(user, (err) => {
      if (err) {
        return next(err);
      }
      // doesn't wokr either res.redirect('/account');
      return res.redirect('/account');
    });
  });
};

** NOTE **
- my code started with
- https://github.com/sahat/hackathon-starter/blob/731ec259c3d17fbee8171f2d280cbdf283177b76/controllers/user.js
- I added the username to the signup form

Body:
I  have it working, using $or: in the findOne statement. (my Gist, "nested" solution didn't seem to always work)

User.findOne({$or: [
      {email: req.body.email},
      {username: req.body.username}
      ]
      }).exec(function(err, existingUser){

but I do wonder if I should be using a promise with this solution?

Full code here.

/**
 * POST /signup
 * Create a new local account.
 */

exports.postSignup = (req, res, next) => {
  req.assert('email', 'Email is not valid').isEmail();
  req.check('username', 'username must be 6-50 lower case characters, only letters and numbers, no spaces allowed.').isAlphanumeric().isLowercase().len(6);
  req.sanitize('email').normalizeEmail({
    gmail_remove_dots: false
  });

  const errors = req.validationErrors();

  if (errors) {
    req.flash('errors', errors);
    return res.redirect('/signup');
  }

  const user = new User({
    email: req.body.email,
    username: req.body.username,
    // password: req.body.password
  });

  User.findOne({$or: [
      {email: req.body.email},
      {username: req.body.username}
      ]
      }).exec(function(err, existingUser){

    // console.log('existingUser.email ' + existingUser.email)
    // console.log('existingUser.email ' + existingUser.username)

    if (!existingUser){
      console.log('now existing user was found');
      console.log('no users with that email NOR phone exist');
      user.save((err) => {
        if (err) { return next(err); }
        req.logIn(user, (err) => {
          if (err) {
            return next(err);
          }
          res.redirect('/account');
        });
      });
    } else if (existingUser.email == req.body.email) {
        console.log('user already exists with EMAIL ');
        req.flash('errors', { msg: 'Account with that EMAIL  already exists.' });
        return res.redirect('/signup');
      }
      else if (existingUser.username = req.body.username){
        console.log('user already exists with USERNAME.');
        req.flash('errors', { msg: 'Account with that USERNAME  already exists.' });
        return res.redirect('/signup');

      }
      else {
      // nothing
        return res.redirect('/signup');
      }

  });

}; // END exports.postSignup {}


问:
FPDF/FPDI Error: Fatal error: Class 'setasign\Fpdi\FpdfTpl' not found in
I am attempting to watermark an existing PDF document, and this error has been tripping me up for the past two days...

I have the FPDI library in fpdi/src/, and the fpdf library in /fpdf/

The file throwing the error is Fpdi.php (line 27).  Here are the first 30 lines:

<?php
/**
 * This file is part of FPDI
 *
 * @package   setasign\Fpdi
 * @copyright Copyright (c) 2017 Setasign - Jan Slabon (https://www.setasign.com)
 * @license   http://opensource.org/licenses/mit-license The MIT License
 * @version   2.0.0
 */

namespace setasign\Fpdi;

use setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException;
use setasign\Fpdi\PdfParser\Type\PdfIndirectObject;
use setasign\Fpdi\PdfParser\Type\PdfNull;
//use setasign\Fpdi\FpdfTpl;

/**
 * Class Fpdi
 *
 * This class let you import pages of existing PDF documents into a reusable structure for FPDF.
 *
 * @package setasign\Fpdi
 */
class Fpdi extends FpdfTpl
{
    use FpdiTrait;```
</div>
</div>
</p>

<p>Here is my file that I am using to watermark the .pdf document on the fly:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
 $fullPathToFile = $_GET['fileToWaterMark'];

 require('rotation.php');

    require_once('fpdf/fpdf.php');
 require_once 'fpdi/src/fpdi.php';
 require_once('fpdi/src/FpdfTpl.php');

 class PDF_Rotate extends FPDI {

 var $angle = 0;

 function Rotate($angle, $x = -1, $y = -1) {
  if ($x == -1)
   $x = $this->x;
  if ($y == -1)
   $y = $this->y;
  if ($this->angle != 0)
   $this->_out('Q');
  $this->angle = $angle;
  if ($angle != 0) {
   $angle*=M_PI / 180;
   $c = cos($angle);
   $s = sin($angle);
   $cx = $x * $this->k;
   $cy = ($this->h - $y) * $this->k;
   $this->_out(sprintf('q %.5F %.5F %.5F %.5F %.2F %.2F cm 1 0 0 1 %.2F %.2F cm', $c, $s, -$s, $c, $cx, $cy, -$cx, -$cy));
  }
 }

 function _endpage() {
  if ($this->angle != 0) {
   $this->angle = 0;
   $this->_out('Q');
  }
  parent::_endpage();
 }

 }

 //$fullPathToFile = "chinmay235.pdf";

 class PDF extends PDF_Rotate {

 var $_tplIdx;

 function Header() {
  global $fullPathToFile;

  //Put the watermark
  $this->Image('http://chart.googleapis.com/chart?cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World', 40, 100, 100, 0, 'PNG');
  $this->SetFont('Arial', 'B', 50);
  $this->SetTextColor(255, 192, 203);
  $this->RotatedText(20, 230, 'Raddyx Technologies Pvt. Ltd.', 45);

  if (is_null($this->_tplIdx)) {

   // THIS IS WHERE YOU GET THE NUMBER OF PAGES
   $this->numPages = $this->setSourceFile($fullPathToFile);
   $this->_tplIdx = $this->importPage(1);
  }
  $this->useTemplate($this->_tplIdx, 0, 0, 200);

 }

 function RotatedText($x, $y, $txt, $angle) {
  //Text rotated around its origin
  $this->Rotate($angle, $x, $y);
  $this->Text($x, $y, $txt);
  $this->Rotate(0);
 }

 }

 $pdf = new PDF();
 $pdf->AddPage();
 $pdf->SetFont('Arial', '', 12);
 $pdf->Output();
 ?></code>```

I am fairly competent with PHP, but this error has really thrown me for a loop.  If any more information is needed, let me know and I will provide it.

答:
Require the classes this way:

```<code>require_once('fpdf/fpdf.php');
require_once('fpdi/src/autoload.php');
</code>```

Then add use \setasign\Fpdi\Fpdi; to your watermark and not only use \setasign\Fpdi; or use the correct class name (including the full namespace) in your class declaration.

Body:
I am attempting to watermark an existing PDF document, and this error has been tripping me up for the past two days...

I have the FPDI library in fpdi/src/, and the fpdf library in /fpdf/

The file throwing the error is Fpdi.php (line 27).  Here are the first 30 lines:

<?php
/**
 * This file is part of FPDI
 *
 * @package   setasign\Fpdi
 * @copyright Copyright (c) 2017 Setasign - Jan Slabon (https://www.setasign.com)
 * @license   http://opensource.org/licenses/mit-license The MIT License
 * @version   2.0.0
 */

namespace setasign\Fpdi;

use setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException;
use setasign\Fpdi\PdfParser\Type\PdfIndirectObject;
use setasign\Fpdi\PdfParser\Type\PdfNull;
//use setasign\Fpdi\FpdfTpl;

/**
 * Class Fpdi
 *
 * This class let you import pages of existing PDF documents into a reusable structure for FPDF.
 *
 * @package setasign\Fpdi
 */
class Fpdi extends FpdfTpl
{
    use FpdiTrait;

Here is my file that I am using to watermark the .pdf document on the fly:

<?php
 $fullPathToFile = $_GET['fileToWaterMark'];

 require('rotation.php');

    require_once('fpdf/fpdf.php');
 require_once 'fpdi/src/fpdi.php';
 require_once('fpdi/src/FpdfTpl.php');

 class PDF_Rotate extends FPDI {

 var $angle = 0;

 function Rotate($angle, $x = -1, $y = -1) {
  if ($x == -1)
   $x = $this->x;
  if ($y == -1)
   $y = $this->y;
  if ($this->angle != 0)
   $this->_out('Q');
  $this->angle = $angle;
  if ($angle != 0) {
   $angle*=M_PI / 180;
   $c = cos($angle);
   $s = sin($angle);
   $cx = $x * $this->k;
   $cy = ($this->h - $y) * $this->k;
   $this->_out(sprintf('q %.5F %.5F %.5F %.5F %.2F %.2F cm 1 0 0 1 %.2F %.2F cm', $c, $s, -$s, $c, $cx, $cy, -$cx, -$cy));
  }
 }

 function _endpage() {
  if ($this->angle != 0) {
   $this->angle = 0;
   $this->_out('Q');
  }
  parent::_endpage();
 }

 }

 //$fullPathToFile = "chinmay235.pdf";

 class PDF extends PDF_Rotate {

 var $_tplIdx;

 function Header() {
  global $fullPathToFile;

  //Put the watermark
  $this->Image('http://chart.googleapis.com/chart?cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World', 40, 100, 100, 0, 'PNG');
  $this->SetFont('Arial', 'B', 50);
  $this->SetTextColor(255, 192, 203);
  $this->RotatedText(20, 230, 'Raddyx Technologies Pvt. Ltd.', 45);

  if (is_null($this->_tplIdx)) {

   // THIS IS WHERE YOU GET THE NUMBER OF PAGES
   $this->numPages = $this->setSourceFile($fullPathToFile);
   $this->_tplIdx = $this->importPage(1);
  }
  $this->useTemplate($this->_tplIdx, 0, 0, 200);

 }

 function RotatedText($x, $y, $txt, $angle) {
  //Text rotated around its origin
  $this->Rotate($angle, $x, $y);
  $this->Text($x, $y, $txt);
  $this->Rotate(0);
 }

 }

 $pdf = new PDF();
 $pdf->AddPage();
 $pdf->SetFont('Arial', '', 12);
 $pdf->Output();
 ?>

I am fairly competent with PHP, but this error has really thrown me for a loop.  If any more information is needed, let me know and I will provide it.

Body:
Require the classes this way:

require_once('fpdf/fpdf.php');
require_once('fpdi/src/autoload.php');

Then add use \setasign\Fpdi\Fpdi; to your watermark and not only use \setasign\Fpdi; or use the correct class name (including the full namespace) in your class declaration.