问:
Value [] at count of type org.json.JSONArray cannot be converted to double
I am working on achartengine pie chart to get the value from my database server. I want to show the average marks of the student in each segment. But I am getting error in my logcat stated:

```<code>W/System.err: org.json.JSONException: Value [] at count of type org.json.JSONArray cannot be converted to double
</code>```

This is part of my java code:

```<code>public class c_marks extends AppCompatActivity {
    private GraphicalView mChart;
    private String[] code;
    double value1, value2, value3, value4, value5, value6;
    ProgressDialog progressDialog;
    JSONParser jsonParser = new JSONParser();
    String COUNT_URL_1 = "http://fypesystem.com/marks_test1.php";
    String COUNT_URL_2 = "http://fypesystem.com/marks_test2.php";
    String COUNT_URL_3 = "http://fypesystem.com/marks_test3.php";
    private static final String TAG_COUNT = "count";
    JSONObject json;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_c_marks);

        new Count().execute();
    }

    class Count extends AsyncTask<String,String ,String>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... args) {
            try {
                json = jsonParser.getJSONFromUrl(COUNT_URL_1);
                value1 = json.getDouble(TAG_COUNT);
                json = jsonParser.getJSONFromUrl(COUNT_URL_2);
                value2 = json.getDouble(TAG_COUNT);
                json = jsonParser.getJSONFromUrl(COUNT_URL_3);
                value3 = json.getDouble(TAG_COUNT);

            }catch (JSONException e){
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String file_url) {
            progressDialog.dismiss();
            openChart();
        }
    }
</code>```

The problem may because of my PHP coding because I believe there is problem, but I do not know how to solve it.

marks_test3.php

```<code>require("config1.php");

$query="SELECT totalmarks, COUNT(*) FROM marks WHERE totalmarks <=30";

try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute();
}catch (PDOException $ex) {
    $response["success"] = 0;
    $response["message"] = "Database Error!";
    die(json_encode($response));
}

$rows = $stmt->fetchAll();

if ($rows){
    $response["success"]=1;
    $response["message"]=" Available";
    $response["count"]= array();

        array_push($response["count"]);
        echo json_encode($response);

        }else {
        $response["success"] = 0;
        $response["message"] = "No Available!";
        die(json_encode($response));
}

?>
</code>```

Really appreciate if you can tell me the problem.

答:
This is not right way to access JSON data
May be your data is in JSONArray format and you are directly assigning it to float so please use following method</p>

```<code>try(){
JSONArray jarray=new JSONArray(your_data_from_url);

for(int i =0; i<jarray. length();i++){

JSONObject jobject=jarray.getJSONObject(i);
 value1 = jobject.getDouble(TAG_COUNT);
}
}catch(Exception e){
e.printStackTrace();
}
</code>```

Body:
I am working on achartengine pie chart to get the value from my database server. I want to show the average marks of the student in each segment. But I am getting error in my logcat stated:

W/System.err: org.json.JSONException: Value [] at count of type org.json.JSONArray cannot be converted to double

This is part of my java code:

public class c_marks extends AppCompatActivity {
    private GraphicalView mChart;
    private String[] code;
    double value1, value2, value3, value4, value5, value6;
    ProgressDialog progressDialog;
    JSONParser jsonParser = new JSONParser();
    String COUNT_URL_1 = "http://fypesystem.com/marks_test1.php";
    String COUNT_URL_2 = "http://fypesystem.com/marks_test2.php";
    String COUNT_URL_3 = "http://fypesystem.com/marks_test3.php";
    private static final String TAG_COUNT = "count";
    JSONObject json;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_c_marks);

        new Count().execute();
    }

    class Count extends AsyncTask<String,String ,String>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... args) {
            try {
                json = jsonParser.getJSONFromUrl(COUNT_URL_1);
                value1 = json.getDouble(TAG_COUNT);
                json = jsonParser.getJSONFromUrl(COUNT_URL_2);
                value2 = json.getDouble(TAG_COUNT);
                json = jsonParser.getJSONFromUrl(COUNT_URL_3);
                value3 = json.getDouble(TAG_COUNT);

            }catch (JSONException e){
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String file_url) {
            progressDialog.dismiss();
            openChart();
        }
    }

The problem may because of my PHP coding because I believe there is problem, but I do not know how to solve it.

marks_test3.php

require("config1.php");

$query="SELECT totalmarks, COUNT(*) FROM marks WHERE totalmarks <=30";

try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute();
}catch (PDOException $ex) {
    $response["success"] = 0;
    $response["message"] = "Database Error!";
    die(json_encode($response));
}

$rows = $stmt->fetchAll();

if ($rows){
    $response["success"]=1;
    $response["message"]=" Available";
    $response["count"]= array();

        array_push($response["count"]);
        echo json_encode($response);

        }else {
        $response["success"] = 0;
        $response["message"] = "No Available!";
        die(json_encode($response));
}

?>

Really appreciate if you can tell me the problem.

Body:
This is not right way to access JSON data
May be your data is in JSONArray format and you are directly assigning it to float so please use following method

try(){
JSONArray jarray=new JSONArray(your_data_from_url);

for(int i =0; i<jarray. length();i++){

JSONObject jobject=jarray.getJSONObject(i);
 value1 = jobject.getDouble(TAG_COUNT);
}
}catch(Exception e){
e.printStackTrace();
}


来源: stackexchange

问:
usage of hugepages for text and data segments
I am exploring the possibility to back the text and data segment with hugepages following the guide in https://github.com/libhugetlbfs/libhugetlbfs/blob/master/HOWTO.

I have relinked the application as suggested by adding "-B/usr/share/libhugetlbfs -Wl,--hugetlbfs-align" and started the application with "hugectl --text --data --heap --bss /path/to/my/application".

But I am not very sure how to verify whether the data and text segments are indeed copied to the files on the hugetlbfs filesystem.

Checking the /proc/{pid}/maps, it could be seen that the hugepages are used for heap but not for text and data segments as the first two address ranges are mapped to the application but not the hugepage file system.

Is my understanding correct? Actually I suspect my conclusion that hugepages are used for heap from /proc/{pid}/maps is also incorrect.

How should I verify whether the data and text segments are backed in the hugepages? I know that data and text segments will be copied to hugetlbfs filesystem if successful but how to verify it?

Thanks!

output of /proc/{pid}/maps

```<code>00400000-00d2c000 r-xp 00000000 fd:02 46153351 /path/to/my/application

00f2b000-00fa3000 rw-p 0092b000 fd:02 46153351 /path/to/my/application

00fa3000-00fbb000 rw-p 00000000 00:00 0

02a0c000-02a2d000 rw-p 00000000 00:00 0  [heap]

40000000-80000000 rw-p 00000000 00:15 2476090 /dev/hugepages-1G/libhugetlbfs.tmp.nS7exn (deleted)
</code>```

答:
If you set HUGETLB_DEBUG=1 variable, it will tell you whole lot of useful information. One of them is this:

INFO: Segment 2's aligned memsz is too small: 0x864 < 0xffffffffffffffff

If it is successful it looks like:

libhugetlbfs [zupa:154297]: INFO: Segment 0 (phdr 2): 0x400000-0x400864  (filesz=0x864) (prot = 0x5)

libhugetlbfs [zupa:154297]: INFO: Segment 1 (phdr 3): 0x600868-0x600af8  (filesz=0x27c) (prot = 0x3)

libhugetlbfs [zupa:154297]: DEBUG: Total memsz = 0xaf4, memsz of largest segment = 0x864

libhugetlbfs [zupa:154297]: INFO: libhugetlbfs version: 2.16 (modified)

libhugetlbfs [zupa:154951]: INFO: Mapped hugeseg at 0x2aaaaac00000. Copying 0x864 bytes and 0 extra bytes from 0x400000...done

libhugetlbfs [zupa:154297]: INFO: Prepare succeeded

libhugetlbfs [zupa:154952]: INFO: Mapped hugeseg at 0x2aaaaac00000. Copying 0x27c bytes and 0 extra bytes from 0x600868...done

libhugetlbfs [zupa:154297]: INFO: Prepare succeeded

ContentLicense: CC BY-SA 3.0

Body:
I am exploring the possibility to back the text and data segment with hugepages following the guide in https://github.com/libhugetlbfs/libhugetlbfs/blob/master/HOWTO.

I have relinked the application as suggested by adding "-B/usr/share/libhugetlbfs -Wl,--hugetlbfs-align" and started the application with "hugectl --text --data --heap --bss /path/to/my/application".

But I am not very sure how to verify whether the data and text segments are indeed copied to the files on the hugetlbfs filesystem.

Checking the /proc/{pid}/maps, it could be seen that the hugepages are used for heap but not for text and data segments as the first two address ranges are mapped to the application but not the hugepage file system.

Is my understanding correct? Actually I suspect my conclusion that hugepages are used for heap from /proc/{pid}/maps is also incorrect.

How should I verify whether the data and text segments are backed in the hugepages? I know that data and text segments will be copied to hugetlbfs filesystem if successful but how to verify it?

Thanks!

output of /proc/{pid}/maps

00400000-00d2c000 r-xp 00000000 fd:02 46153351 /path/to/my/application

00f2b000-00fa3000 rw-p 0092b000 fd:02 46153351 /path/to/my/application

00fa3000-00fbb000 rw-p 00000000 00:00 0

02a0c000-02a2d000 rw-p 00000000 00:00 0  [heap]

40000000-80000000 rw-p 00000000 00:15 2476090 /dev/hugepages-1G/libhugetlbfs.tmp.nS7exn (deleted)


问:
Writing iPhone filesystem in background mode
I am writing an app that logs GPS locations to a file on the iPhone and has to continue updating the locations in background mode. Now I am wondering what is the best way of doing this. Is it good practice to open the file and keep it open when my app goes in to background mode or should I close it and re-open it whenever the app needs to write a new location?</p>

答:
Why keeping open/re-opening the file?

You can let it "write" the location data to an NSMutableArray and write it to a file before your App gets killed or if the user manually saves it by pressing a button.

As drachenstern already mentioned, it will suck the battery dry to have location services on all the time...might lead to a bad UX

ContentLicense: CC BY-SA 2.5


问:
Network connectivity should come only when changed
I am using Alamofire NetworkReachabilityManager for managing my connections like below.

```<code>    let reachabilityManager = NetworkReachabilityManager()
   reachabilityManager?.listener = { [weak self] status in
            switch status {
            case .notReachable:
                self?.connectionType = .notReachable
                break
            case .unknown:
                self?.connectionType = .notReachable
                break
            case .reachable(.ethernetOrWiFi):
                self?.connectionType = .wifi
                break
            case .reachable(.wwan):
                self?.connectionType = .cellular

                break
            }

public enum ReachabilityStatus {
    case unknown
    case notReachable
    case wifi
    case cellular
}
</code>```

I am getting this callback when i am launching the application itself but I don't want this callback I need callback only when there is a change in network connection.

How can I solve this?

答:
You can add listener after some delay. so listener should be nil when NetworkReachabilityManager gets instantiated on app launch

```<code>    let reachabilityManager = NetworkReachabilityManager()
    var previousStatus: ReachabilityStatus? = nil

    DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
    reachabilityManager?.listener = { [weak self] status in

    if let p = self.previousStatus, p == status {
        return // status hasn't changed
    } else {
        // status is nil
        self.previousStatus = status
        return
    }

    switch status {
    case .notReachable:
        self?.connectionType = .notReachable
        break
    case .unknown:
        self?.connectionType = .notReachable
        break
    case .reachable(.ethernetOrWiFi):
        self?.connectionType = .wifi
        break
    case .reachable(.wwan):
        self?.connectionType = .cellular

        break
 }
})
</code>```

Edit: i have tested this code. it works.

Body:
I am using Alamofire NetworkReachabilityManager for managing my connections like below.

    let reachabilityManager = NetworkReachabilityManager()
   reachabilityManager?.listener = { [weak self] status in
            switch status {
            case .notReachable:
                self?.connectionType = .notReachable
                break
            case .unknown:
                self?.connectionType = .notReachable
                break
            case .reachable(.ethernetOrWiFi):
                self?.connectionType = .wifi
                break
            case .reachable(.wwan):
                self?.connectionType = .cellular

                break
            }

public enum ReachabilityStatus {
    case unknown
    case notReachable
    case wifi
    case cellular
}

I am getting this callback when i am launching the application itself but I don't want this callback I need callback only when there is a change in network connection.

How can I solve this?

Body:
You can add listener after some delay. so listener should be nil when NetworkReachabilityManager gets instantiated on app launch

    let reachabilityManager = NetworkReachabilityManager()
    var previousStatus: ReachabilityStatus? = nil

    DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
    reachabilityManager?.listener = { [weak self] status in

    if let p = self.previousStatus, p == status {
        return // status hasn't changed
    } else {
        // status is nil
        self.previousStatus = status
        return
    }

    switch status {
    case .notReachable:
        self?.connectionType = .notReachable
        break
    case .unknown:
        self?.connectionType = .notReachable
        break
    case .reachable(.ethernetOrWiFi):
        self?.connectionType = .wifi
        break
    case .reachable(.wwan):
        self?.connectionType = .cellular

        break
 }
})

Edit: i have tested this code. it works.


问:
WHEN MAKE .bat file and run do not work WINDOWS 7
```<code>D:\> set "today=%date:~10,4%-%date:~7,2%-%date:~4,2%"

D:\> mkdir SVN_BACKUP_DUMP_TEST\%today%

D:\> CD SVN_BACKUP_DUMP_TEST\%today%
</code>```

<p>when we are make bat file this command not work </p>

答:
Format of date of referenced environment variable DATE depends on region setting, i.e. which country and derived from country which date format is configured for the current account. So which string is assigned to environment variable today and if that string is valid for a directory or file name depends on account specific date format.

On my computer with German set as country for my account output of echo %DATE% is 13.11.2017. So the date format is dd.MM.yyyy with point as separator, no weekday and always two digits for date and month even for a date or month less than 10.

The command line

```<code>echo %DATE:~10,4%-%DATE:~7,2%-%DATE:~4,2%
</code>```

produces on my machine with my account and my region settings the output:

```<code>-01-1.
</code>```

That is definitely not the current date in format yyyy-MM-dd.

The solution is using following batch code:

```<code>@echo off
for /F "tokens=2 delims==." %%I in ('%SystemRoot%\System32\wbem\wmic.exe OS GET LocalDateTime /VALUE') do set "Today=%%I"
set "Today=%Today:~0,4%-%Today:~4,2%-%Today:~6,2%"
mkdir "SVN_BACKUP_DUMP_TEST\%Today%" 2>nul
cd "SVN_BACKUP_DUMP_TEST\%Today%"
</code>```

This is a region independent solution. The batch code is completely explained in answer on

Why does %date% produce a different result in batch file executed as scheduled task?

What does %date:~-4,4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2% mean? is one more question on which answer should be read to understand the string substitutions. And run in a command prompt window set /? to get displayed the help for command SET explaining string substitution, too.

Body:
D:\> set "today=%date:~10,4%-%date:~7,2%-%date:~4,2%"

D:\> mkdir SVN_BACKUP_DUMP_TEST\%today%

D:\> CD SVN_BACKUP_DUMP_TEST\%today%

when we are make bat file this command not work

Body:
Format of date of referenced environment variable DATE depends on region setting, i.e. which country and derived from country which date format is configured for the current account. So which string is assigned to environment variable today and if that string is valid for a directory or file name depends on account specific date format.

On my computer with German set as country for my account output of echo %DATE% is 13.11.2017. So the date format is dd.MM.yyyy with point as separator, no weekday and always two digits for date and month even for a date or month less than 10.

The command line

echo %DATE:~10,4%-%DATE:~7,2%-%DATE:~4,2%

produces on my machine with my account and my region settings the output:

-01-1.

That is definitely not the current date in format yyyy-MM-dd.

The solution is using following batch code:

@echo off
for /F "tokens=2 delims==." %%I in ('%SystemRoot%\System32\wbem\wmic.exe OS GET LocalDateTime /VALUE') do set "Today=%%I"
set "Today=%Today:~0,4%-%Today:~4,2%-%Today:~6,2%"
mkdir "SVN_BACKUP_DUMP_TEST\%Today%" 2>nul
cd "SVN_BACKUP_DUMP_TEST\%Today%"

This is a region independent solution. The batch code is completely explained in answer on

Why does %date% produce a different result in batch file executed as scheduled task?

What does %date:~-4,4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2% mean? is one more question on which answer should be read to understand the string substitutions. And run in a command prompt window set /? to get displayed the help for command SET explaining string substitution, too.

ContentLicense: CC BY-SA 4.0


问:
Google maps not showing on Ionic when the plugin is used
I want to display maps in my application but Google map isn't showing up. I have made my application on Ionic and I have used the Cordova Google Maps plugin. Here is the link to my code. Please help me. </p>

答: Have you registered in Google Maps and added API KEY do your app?</p>


答:
count is a JSON array, but you are trying to reference it as if it were a floating-point number.

You need to either:

1. set it as a number when creating the JSON object in PHP and set the value to the number of rows found:

```<code>$response["count"] = count($rows);
</code>```

In this case, it's probably more correct to use json.getInt() than json.getDouble(), or

2. get count as a JSONArray, and then check its size:

```<code>json.getJSONArray("count").length()
</code>```

Title: Value [] at count of type org.json.JSONArray cannot be converted to double

Body:
count is a JSON array, but you are trying to reference it as if it were a floating-point number.

You need to either:

1. set it as a number when creating the JSON object in PHP and set the value to the number of rows found:

$response["count"] = count($rows);

In this case, it's probably more correct to use json.getInt() than json.getDouble(), or

2. get count as a JSONArray, and then check its size:

json.getJSONArray("count").length()


问:
Running Windows Docker Images on Kubernetes Cluster, installed on Windows 10
I have installed Kubernetes Cluster (minikube) on my Windows 10 machine and seems to be running (ie: I can browse the minikube dashboard, etc).

I also have a Windows Image (has an Asp.Net Web API .Net framework 4.6 Application in it) on Azure Container Registry that I would like to pull and deploy to my local Kubernetes Cluster.

I have built the following yaml file to create the Kubernetes deployment:

```<code>apiVersion: v1
kind: Pod
metadata:
  name: hubapi
spec:
  containers:
  - name: hubapi
    image: lgmimages.azurecr.io/hubapi/hubapi
  imagePullSecrets:
  - name: azurepasswordsecret
</code>```

When I run this command:

```<code>kubectl create -f hubapi.yaml
</code>```

and I see:

```<code>pod "hubapi" created
</code>```

Then when I go to the dashboard or get Pod Description I see the following error:

```<code>kubelet, minikube  Failed to pull image "lgmimages.azurecr.io/hubapi/hubapi": rpc error: code = Unknown desc = image operating system "windows" cannot be used on this platform
</code>```

I was wondering what I am missing here and is what I am trying to do is even possible?

Note: It works when I use this command and pull nginx image from dockerhub:

```<code>kubectl run kubernetes-nginx --image=nginx:latest --port=80
</code>```

Then I expose this service and I can browse the nginx web page on my local Cluster.

答:
rpc error: code = Unknown desc = image operating system "windows"
  cannot be used on this platform

Actually, we install kubernetes on windows 10 bash on Ubuntu, in this way, the bash on ubuntu works as a master, base on Linux, we can't run windows docker image on it.

As we know, kubernetes master should be a Linux, you have not other nodes, so we can't run windows docker image on it.

For test, you can use Azure container service and deploy kubernetes with windows nodes, in this way, we can run Windows docker image on the k8s windows nodes.

Hope this helps:)

Body:
I have installed Kubernetes Cluster (minikube) on my Windows 10 machine and seems to be running (ie: I can browse the minikube dashboard, etc).

I also have a Windows Image (has an Asp.Net Web API .Net framework 4.6 Application in it) on Azure Container Registry that I would like to pull and deploy to my local Kubernetes Cluster.

I have built the following yaml file to create the Kubernetes deployment:

apiVersion: v1
kind: Pod
metadata:
  name: hubapi
spec:
  containers:
  - name: hubapi
    image: lgmimages.azurecr.io/hubapi/hubapi
  imagePullSecrets:
  - name: azurepasswordsecret

When I run this command:

kubectl create -f hubapi.yaml

and I see:

pod "hubapi" created

Then when I go to the dashboard or get Pod Description I see the following error:

kubelet, minikube  Failed to pull image "lgmimages.azurecr.io/hubapi/hubapi": rpc error: code = Unknown desc = image operating system "windows" cannot be used on this platform

I was wondering what I am missing here and is what I am trying to do is even possible?

Note: It works when I use this command and pull nginx image from dockerhub:

kubectl run kubernetes-nginx --image=nginx:latest --port=80

Then I expose this service and I can browse the nginx web page on my local Cluster.


问:
Array Filter in Angular
i have json array get from http web api, i want to filter this array:

```<code>    [
{
"bulan": "4",
"tahun": "2017",
"id_program": 4,
"id_segmen": 1,
"segmen": "ppu",
"jumlah": 3953,
"target": 900000
},
{
"bulan": "4",
"tahun": "2017",
"id_program": 3,
"id_segmen": 2,
"segmen": "bpu",
"jumlah": 45,
"target": 500000
},
{
"bulan": "4",
"tahun": "2017",
"id_program": 3,
"id_segmen": 1,
"segmen": "ppu",
"jumlah": 8752,
"target": 900000
}]
</code>```

i need to filter or select for get all where id_segmen=1.
this is my expectation :

```<code> [
{
"bulan": "4",
"tahun": "2017",
"id_program": 4,
"id_segmen": 1,
"segmen": "ppu",
"jumlah": 3953,
"target": 900000
}]
</code>```

my current http.get is as below:

```<code>this.http.get<JuResponse>(environment.url + '/cps/' + year + '/' + month + '/' + kanwil + '/' + cabang).
   subscribe(data => {
       let filteredValues = data.filter((data) => value.id_segmen == 1);
       console.log(filteredValues);
});
</code>```

答:
You can use Javascript Filters for this purpose

var a = [
{
"bulan": "4",
"tahun": "2017",
"id_program": 4,
"id_segmen": 1,
"segmen": "ppu",
"jumlah": 3953,
"target": 900000
},
{
"bulan": "4",
"tahun": "2017",
"id_program": 3,
"id_segmen": 2,
"segmen": "bpu",
"jumlah": 45,
"target": 500000
},
{
"bulan": "4",
"tahun": "2017",
"id_program": 3,
"id_segmen": 1,
"segmen": "ppu",
"jumlah": 8752,
"target": 900000
}];

var c = a.filter(function(val){
  return val.id_segmen == 1 ;
});
alert(JSON.stringify(c))```

Title: Array Filter in Angular

Body:
i have json array get from http web api, i want to filter this array:

    [
{
"bulan": "4",
"tahun": "2017",
"id_program": 4,
"id_segmen": 1,
"segmen": "ppu",
"jumlah": 3953,
"target": 900000
},
{
"bulan": "4",
"tahun": "2017",
"id_program": 3,
"id_segmen": 2,
"segmen": "bpu",
"jumlah": 45,
"target": 500000
},
{
"bulan": "4",
"tahun": "2017",
"id_program": 3,
"id_segmen": 1,
"segmen": "ppu",
"jumlah": 8752,
"target": 900000
}]

i need to filter or select for get all where id_segmen=1.
this is my expectation :

 [
{
"bulan": "4",
"tahun": "2017",
"id_program": 4,
"id_segmen": 1,
"segmen": "ppu",
"jumlah": 3953,
"target": 900000
}]

my current http.get is as below:

this.http.get<JuResponse>(environment.url + '/cps/' + year + '/' + month + '/' + kanwil + '/' + cabang).
   subscribe(data => {
       let filteredValues = data.filter((data) => value.id_segmen == 1);
       console.log(filteredValues);
});


问:
How to get the My Documents folder paths from all users of a machine
I am looking for a way to get the paths of the My Documents folders from all users (each user) of a local machine.
I found several articles, but they show how to do this for the current user.

I tested the code below, using SHGetKnownFolderPath, but it works only for the logged user. In the class ctor that receives a WindowsIdentity object, I create it with tokens of other users, but the paths returned were of the logged-in user.

Does anyone know how I could get the folders paths?

Thanks.

```<code>using Syroot.Windows.IO;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace ConsoleApplication2
{
class Program
{
    private static Dictionary<KnownFolderType, KnownFolder> _knownFolderInstances;
    static void Main(string[] args)
    {
        KnownFolderType type = KnownFolderType.Documents;
        KnownFolder knownFolder = new KnownFolder(type);

    //Ctor with WindowsIdentity parameter
    //public KnownFolder(KnownFolderType type, WindowsIdentity identity)
    //{
    //    Type = type;
    //    Identity = identity;
    //}

    // Write down the current and default path.
    Console.WriteLine(knownFolder.Type.ToString());
        try
        {
            Console.Write("Current Path: ");
            Console.WriteLine(knownFolder.Path);
            Console.Write("Default Path: ");
            Console.WriteLine(knownFolder.DefaultPath);
        }
        catch (ExternalException ex)
        {
            // While uncommon with personal folders, other KnownFolders don't exist on every system, and trying
            // to query those returns an error which we catch here.
            Console.WriteLine("<Exception> " + ex.ErrorCode);
        }

        Console.ReadLine();
    }

    private static KnownFolder GetInstance(KnownFolderType type)
    {
        // Check if the caching directory exists yet.
        if (_knownFolderInstances == null)
        {
            _knownFolderInstances = new Dictionary<KnownFolderType, KnownFolder>();
        }

        // Get a KnownFolder instance out of the cache dictionary or create it when not cached yet.
        KnownFolder knownFolder;
        if (!_knownFolderInstances.TryGetValue(type, out knownFolder))
        {
            knownFolder = new KnownFolder(type);
            _knownFolderInstances.Add(type, knownFolder);
        }
        return knownFolder;
    }

    /// <summary>
    /// The per-user Documents folder.
    /// Defaults to "%USERPROFILE%\Documents".
    /// </summary>
    public static KnownFolder Documents
    {
        get { return GetInstance(KnownFolderType.Documents); }
    }
}
}
</code>```

KnownFolder.cs

```<code>using System;
using System.Runtime.InteropServices;
using System.Security.Principal;

namespace Syroot.Windows.IO
{
/// <summary>
/// Represents a special Windows directory and provides methods to retrieve information about it.
/// </summary>
public sealed class KnownFolder
{
    // ---- CONSTRUCTORS & DESTRUCTOR ------------------------------------------------------------------------------

    /// <summary>
    /// Initializes a new instance of the <see cref="KnownFolder"/> class for the folder of the given type. It
    /// provides the values for the current user.
    /// </summary>
    /// <param name="type">The <see cref="KnownFolderType"/> of the known folder to represent.</param>
    public KnownFolder(KnownFolderType type)
        : this(type, WindowsIdentity.GetCurrent())
    {
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="KnownFolder"/> class for the folder of the given type. It
    /// provides the values for the given impersonated user.
    /// </summary>
    /// <param name="type">The <see cref="KnownFolderType"/> of the known folder to represent.</param>
    /// <param name="identity">The <see cref="WindowsIdentity"/> of the impersonated user which values will be
    /// provided.</param>
    public KnownFolder(KnownFolderType type, WindowsIdentity identity)
    {
        Type = type;
        Identity = identity;
    }

    // ---- PROPERTIES ---------------------------------------------------------------------------------------------

    /// <summary>
    /// Gets the type of the known folder which is represented.
    /// </summary>
    public KnownFolderType Type
    {
        get;
        private set;
    }

    /// <summary>
    /// Gets the <see cref="WindowsIdentity"/> of the user whose folder values are provided.
    /// </summary>
    public WindowsIdentity Identity
    {
        get;
        private set;
    }

    /// <summary>
    /// Gets or sets the default path of the folder.
    /// This does not require the folder to be existent.
    /// </summary>
    /// <exception cref="ExternalException">The known folder could not be retrieved.</exception>
    public string DefaultPath
    {
        get
        {
            return GetPath(KnownFolderFlags.DontVerify | KnownFolderFlags.DefaultPath);
        }
        set
        {

        }
    }

    /// <summary>
    /// Gets or sets the path as currently configured.
    /// This does not require the folder to be existent.
    /// </summary>
    /// <exception cref="ExternalException">The known folder could not be retrieved.</exception>
    public string Path
    {
        get
        {
            return GetPath(KnownFolderFlags.DontVerify);
        }
        set
        {
            SetPath(KnownFolderFlags.None, value);
        }
    }

    /// <summary>
    /// Gets or sets the path as currently configured, with all environment variables expanded.
    /// This does not require the folder to be existent.
    /// </summary>
    /// <exception cref="ExternalException">The known folder could not be retrieved.</exception>
    public string ExpandedPath
    {
        get
        {
            return GetPath(KnownFolderFlags.DontVerify | KnownFolderFlags.NoAlias);
        }
        set
        {
            SetPath(KnownFolderFlags.DontUnexpand, value);
        }
    }

    // ---- METHODS (PUBLIC) ---------------------------------------------------------------------------------------

    /// <summary>
    /// Creates the folder using its Desktop.ini settings.
    /// </summary>
    /// <exception cref="ExternalException">The known folder could not be retrieved.</exception>
    public void Create()
    {
        GetPath(KnownFolderFlags.Init | KnownFolderFlags.Create);
    }

    // ---- METHODS (PRIVATE) --------------------------------------------------------------------------------------

    private string GetPath(KnownFolderFlags flags)
    {
        IntPtr outPath;
        int result = SHGetKnownFolderPath(Type.GetGuid(), (uint)flags, Identity.Token, out outPath);
        if (result >= 0)
        {
            return Marshal.PtrToStringUni(outPath);
        }
        else
        {
            throw new ExternalException("Cannot get the known folder path. It may not be available on this system.",
                result);
        }
    }

    private void SetPath(KnownFolderFlags flags, string path)
    {
        int result = SHSetKnownFolderPath(Type.GetGuid(), (uint)flags, Identity.Token, path);
        if (result < 0)
        {
            throw new ExternalException("Cannot set the known folder path. It may not be available on this system.",
                result);
        }
    }

    /// <summary>
    /// Retrieves the full path of a known folder identified by the folder's known folder ID.
    /// </summary>
    /// <param name="rfid">A known folder ID that identifies the folder.</param>
    /// <param name="dwFlags">Flags that specify special retrieval options. This value can be 0; otherwise, one or
    /// more of the <see cref="KnownFolderFlags"/> values.</param>
    /// <param name="hToken">An access token that represents a particular user. If this parameter is NULL, which is
    /// the most common usage, the function requests the known folder for the current user. Assigning a value of -1
    /// indicates the Default User. The default user profile is duplicated when any new user account is created.
    /// Note that access to the Default User folders requires administrator privileges.</param>
    /// <param name="ppszPath">When this method returns, contains the address of a string that specifies the path of
    /// the known folder. The returned path does not include a trailing backslash.</param>
    /// <returns>Returns S_OK if successful, or an error value otherwise.</returns>
    /// <msdn-id>bb762188</msdn-id>
    [DllImport("Shell32.dll")]
    private static extern int SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)]Guid rfid, uint dwFlags,
        IntPtr hToken, out IntPtr ppszPath);

    /// <summary>
    /// Redirects a known folder to a new location.
    /// </summary>
    /// <param name="rfid">A <see cref="Guid"/> that identifies the known folder.</param>
    /// <param name="dwFlags">Either 0 or <see cref="KnownFolderFlags.DontUnexpand"/>.</param>
    /// <param name="hToken"></param>
    /// <param name="pszPath"></param>
    /// <returns></returns>
    /// <msdn-id>bb762249</msdn-id>
    [DllImport("Shell32.dll")]
    private static extern int SHSetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)]Guid rfid, uint dwFlags,
        IntPtr hToken, [MarshalAs(UnmanagedType.LPWStr)]string pszPath);

    // ---- ENUMERATIONS -------------------------------------------------------------------------------------------

    /// <summary>
    /// Represents the retrieval options for known folders.
    /// </summary>
    /// <msdn-id>dd378447</msdn-id>
    [Flags]
    private enum KnownFolderFlags : uint
    {
        None                      = 0x00000000,
        SimpleIDList              = 0x00000100,
        NotParentRelative         = 0x00000200,
        DefaultPath               = 0x00000400,
        Init                      = 0x00000800,
        NoAlias                   = 0x00001000,
        DontUnexpand              = 0x00002000,
        DontVerify                = 0x00004000,
        Create                    = 0x00008000,
        NoAppcontainerRedirection = 0x00010000,
        AliasOnly                 = 0x80000000
    }
}
}
</code>```

答:
I figured it out.
I got all SIDs from the system and then searched the Windows registry for each SID by the "Personal" key in the following format: "HKEY_USERS" + "SID" + "\ Software \ Microsoft \ Windows \ CurrentVersion \ Explorer \ Shell Folders \ Personal ".
The "Personal" key retains the current path of each user's "My Documents" folder.

Get SIDs:

```<code>    public static List<string> GetMachineSids()
    {
        ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_UserProfile");
        var regs = searcher.Get();
        string sid;

        List<string> sids = new List<string>();

        foreach (ManagementObject os in regs)
        {
            if (os["SID"] != null)
            {
                sid = os["SID"].ToString();
                sids.Add(sid);
            }
        }

        searcher.Dispose();
        return sids.Count > 0 ? sids : null;
    }
</code>```

Get MyDocuments Path:

```<code>    public static List<string> GetMyDocumentsPathAllUsers()
    {
        const string parcialSubkey = @"\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders";
        string subkey = string.Empty;
        const string keyName = "Personal";

        //get sids
        List<string> sids = GetMachineSids();
        List<string> myDocumentsPaths = new List<string>();

        if (sids != null)
        {
            foreach (var sid in sids)
            {
                //get paths
                subkey = sid + parcialSubkey;

                using (RegistryKey key = Registry.Users.OpenSubKey(subkey))
                {
                    if (key != null)
                    {
                        Object o = key.GetValue(keyName);
                        if (o != null)
                        {
                            myDocumentsPaths.Add(o.ToString());
                        }
                    }
                }
            }
        }

        return myDocumentsPaths.Count > 0 ? myDocumentsPaths : null;
    }
</code>```

Body:
I am looking for a way to get the paths of the My Documents folders from all users (each user) of a local machine.
I found several articles, but they show how to do this for the current user.

I tested the code below, using SHGetKnownFolderPath, but it works only for the logged user. In the class ctor that receives a WindowsIdentity object, I create it with tokens of other users, but the paths returned were of the logged-in user.

Does anyone know how I could get the folders paths?

Thanks.

using Syroot.Windows.IO;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace ConsoleApplication2
{
class Program
{
    private static Dictionary<KnownFolderType, KnownFolder> _knownFolderInstances;
    static void Main(string[] args)
    {
        KnownFolderType type = KnownFolderType.Documents;
        KnownFolder knownFolder = new KnownFolder(type);

    //Ctor with WindowsIdentity parameter
    //public KnownFolder(KnownFolderType type, WindowsIdentity identity)
    //{
    //    Type = type;
    //    Identity = identity;
    //}

    // Write down the current and default path.
    Console.WriteLine(knownFolder.Type.ToString());
        try
        {
            Console.Write("Current Path: ");
            Console.WriteLine(knownFolder.Path);
            Console.Write("Default Path: ");
            Console.WriteLine(knownFolder.DefaultPath);
        }
        catch (ExternalException ex)
        {
            // While uncommon with personal folders, other KnownFolders don't exist on every system, and trying
            // to query those returns an error which we catch here.
            Console.WriteLine("<Exception> " + ex.ErrorCode);
        }

        Console.ReadLine();
    }

    private static KnownFolder GetInstance(KnownFolderType type)
    {
        // Check if the caching directory exists yet.
        if (_knownFolderInstances == null)
        {
            _knownFolderInstances = new Dictionary<KnownFolderType, KnownFolder>();
        }

        // Get a KnownFolder instance out of the cache dictionary or create it when not cached yet.
        KnownFolder knownFolder;
        if (!_knownFolderInstances.TryGetValue(type, out knownFolder))
        {
            knownFolder = new KnownFolder(type);
            _knownFolderInstances.Add(type, knownFolder);
        }
        return knownFolder;
    }

    ///
    /// The per-user Documents folder.
    /// Defaults to "%USERPROFILE%\Documents".
    ///
    public static KnownFolder Documents
    {
        get { return GetInstance(KnownFolderType.Documents); }
    }
}
}

KnownFolder.cs

using System;
using System.Runtime.InteropServices;
using System.Security.Principal;

namespace Syroot.Windows.IO
{
///
/// Represents a special Windows directory and provides methods to retrieve information about it.
///
public sealed class KnownFolder
{
    // ---- CONSTRUCTORS & DESTRUCTOR ------------------------------------------------------------------------------

    ///
    /// Initializes a new instance of the <see cref="KnownFolder"/> class for the folder of the given type. It
    /// provides the values for the current user.
    ///
    /// <param name="type">The <see cref="KnownFolderType"/> of the known folder to represent.</param>
    public KnownFolder(KnownFolderType type)
        : this(type, WindowsIdentity.GetCurrent())
    {
    }

    ///
    /// Initializes a new instance of the <see cref="KnownFolder"/> class for the folder of the given type. It
    /// provides the values for the given impersonated user.
    ///
    /// <param name="type">The <see cref="KnownFolderType"/> of the known folder to represent.</param>
    /// <param name="identity">The <see cref="WindowsIdentity"/> of the impersonated user which values will be
    /// provided.</param>
    public KnownFolder(KnownFolderType type, WindowsIdentity identity)
    {
        Type = type;
        Identity = identity;
    }

    // ---- PROPERTIES ---------------------------------------------------------------------------------------------

    ///
    /// Gets the type of the known folder which is represented.
    ///
    public KnownFolderType Type
    {
        get;
        private set;
    }

    ///
    /// Gets the <see cref="WindowsIdentity"/> of the user whose folder values are provided.
    ///
    public WindowsIdentity Identity
    {
        get;
        private set;
    }

    ///
    /// Gets or sets the default path of the folder.
    /// This does not require the folder to be existent.
    ///
    /// <exception cref="ExternalException">The known folder could not be retrieved.</exception>
    public string DefaultPath
    {
        get
        {
            return GetPath(KnownFolderFlags.DontVerify | KnownFolderFlags.DefaultPath);
        }
        set
        {

        }
    }

    ///
    /// Gets or sets the path as currently configured.
    /// This does not require the folder to be existent.
    ///
    /// <exception cref="ExternalException">The known folder could not be retrieved.</exception>
    public string Path
    {
        get
        {
            return GetPath(KnownFolderFlags.DontVerify);
        }
        set
        {
            SetPath(KnownFolderFlags.None, value);
        }
    }

    ///
    /// Gets or sets the path as currently configured, with all environment variables expanded.
    /// This does not require the folder to be existent.
    ///
    /// <exception cref="ExternalException">The known folder could not be retrieved.</exception>
    public string ExpandedPath
    {
        get
        {
            return GetPath(KnownFolderFlags.DontVerify | KnownFolderFlags.NoAlias);
        }
        set
        {
            SetPath(KnownFolderFlags.DontUnexpand, value);
        }
    }

    // ---- METHODS (PUBLIC) ---------------------------------------------------------------------------------------

    ///
    /// Creates the folder using its Desktop.ini settings.
    ///
    /// <exception cref="ExternalException">The known folder could not be retrieved.</exception>
    public void Create()
    {
        GetPath(KnownFolderFlags.Init | KnownFolderFlags.Create);
    }

    // ---- METHODS (PRIVATE) --------------------------------------------------------------------------------------

    private string GetPath(KnownFolderFlags flags)
    {
        IntPtr outPath;
        int result = SHGetKnownFolderPath(Type.GetGuid(), (uint)flags, Identity.Token, out outPath);
        if (result >= 0)
        {
            return Marshal.PtrToStringUni(outPath);
        }
        else
        {
            throw new ExternalException("Cannot get the known folder path. It may not be available on this system.",
                result);
        }
    }

    private void SetPath(KnownFolderFlags flags, string path)
    {
        int result = SHSetKnownFolderPath(Type.GetGuid(), (uint)flags, Identity.Token, path);
        if (result < 0)
        {
            throw new ExternalException("Cannot set the known folder path. It may not be available on this system.",
                result);
        }
    }

    ///
    /// Retrieves the full path of a known folder identified by the folder's known folder ID.
    ///
    /// <param name="rfid">A known folder ID that identifies the folder.</param>
    /// <param name="dwFlags">Flags that specify special retrieval options. This value can be 0; otherwise, one or
    /// more of the <see cref="KnownFolderFlags"/> values.</param>
    /// <param name="hToken">An access token that represents a particular user. If this parameter is NULL, which is
    /// the most common usage, the function requests the known folder for the current user. Assigning a value of -1
    /// indicates the Default User. The default user profile is duplicated when any new user account is created.
    /// Note that access to the Default User folders requires administrator privileges.</param>
    /// <param name="ppszPath">When this method returns, contains the address of a string that specifies the path of
    /// the known folder. The returned path does not include a trailing backslash.</param>
    /// <returns>Returns S_OK if successful, or an error value otherwise.</returns>
    /// <msdn-id>bb762188</msdn-id>
    [DllImport("Shell32.dll")]
    private static extern int SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)]Guid rfid, uint dwFlags,
        IntPtr hToken, out IntPtr ppszPath);

    ///
    /// Redirects a known folder to a new location.
    ///
    /// <param name="rfid">A <see cref="Guid"/> that identifies the known folder.</param>
    /// <param name="dwFlags">Either 0 or <see cref="KnownFolderFlags.DontUnexpand"/>.</param>
    /// <param name="hToken"></param>
    /// <param name="pszPath"></param>
    /// <returns></returns>
    /// <msdn-id>bb762249</msdn-id>
    [DllImport("Shell32.dll")]
    private static extern int SHSetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)]Guid rfid, uint dwFlags,
        IntPtr hToken, [MarshalAs(UnmanagedType.LPWStr)]string pszPath);

    // ---- ENUMERATIONS -------------------------------------------------------------------------------------------

    ///
    /// Represents the retrieval options for known folders.
    ///
    /// <msdn-id>dd378447</msdn-id>
    [Flags]
    private enum KnownFolderFlags : uint
    {
        None                      = 0x00000000,
        SimpleIDList              = 0x00000100,
        NotParentRelative         = 0x00000200,
        DefaultPath               = 0x00000400,
        Init                      = 0x00000800,
        NoAlias                   = 0x00001000,
        DontUnexpand              = 0x00002000,
        DontVerify                = 0x00004000,
        Create                    = 0x00008000,
        NoAppcontainerRedirection = 0x00010000,
        AliasOnly                 = 0x80000000
    }
}
}

Body:
I figured it out.
I got all SIDs from the system and then searched the Windows registry for each SID by the "Personal" key in the following format: "HKEY_USERS" + "SID" + "\ Software \ Microsoft \ Windows \ CurrentVersion \ Explorer \ Shell Folders \ Personal ".
The "Personal" key retains the current path of each user's "My Documents" folder.

Get SIDs:

    public static List<string> GetMachineSids()
    {
        ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_UserProfile");
        var regs = searcher.Get();
        string sid;

        List<string> sids = new List<string>();

        foreach (ManagementObject os in regs)
        {
            if (os["SID"] != null)
            {
                sid = os["SID"].ToString();
                sids.Add(sid);
            }
        }

        searcher.Dispose();
        return sids.Count > 0 ? sids : null;
    }

Get MyDocuments Path:

    public static List<string> GetMyDocumentsPathAllUsers()
    {
        const string parcialSubkey = @"\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders";
        string subkey = string.Empty;
        const string keyName = "Personal";

        //get sids
        List<string> sids = GetMachineSids();
        List<string> myDocumentsPaths = new List<string>();

        if (sids != null)
        {
            foreach (var sid in sids)
            {
                //get paths
                subkey = sid + parcialSubkey;

                using (RegistryKey key = Registry.Users.OpenSubKey(subkey))
                {
                    if (key != null)
                    {
                        Object o = key.GetValue(keyName);
                        if (o != null)
                        {
                            myDocumentsPaths.Add(o.ToString());
                        }
                    }
                }
            }
        }

        return myDocumentsPaths.Count > 0 ? myDocumentsPaths : null;
    }


问:
how to modify values of a file-backed matrix in bigmemory rcpp
I am using R bigmemory package and Rcpp to handle big matrices (1 to 10 Million column x 1000 rows). Once I read an interger matrix consisting in 0, 2 and NA into a filebacked bigmemory matrix in R I would like to modify through C++ all the NA values in order to do imputation of the mean values per column or an arbitrary-value-imputation (I show here the latter).

Below is the Rcpp function I have written and that does not work. My hope was that calling BigNA(mybigmatrix@address) from within R could find the elements in the matrix that are NAs and modify its values directly in the backing file.

I think the problem might be in the evaluation of std::isnan(mat[j][i]). I checked this by creating an alternative function that counts the NA values with an accumulator and indeed did not count any NA. But once this is solved, I am also not sure if the expression mat[j][i] = 1 would modify the value in the backing file. Writing those statements feels intuitive for me having an R background but might be wrong.

Any help/suggestion would be very much appreciated.

```<code>#include <stdio.h>
#include <Rcpp.h>
#include <bigmemory/MatrixAccessor.hpp>
#include <numeric>
// [[Rcpp::depends(BH, bigmemory)]]
// [[Rcpp::depends(Rcpp)]]

// [[Rcpp::export]]
void BigNA(SEXP pBigMat) {
  /*
  * Imputation of "NA" values for "1" in a big 0, 2 NA matrix.
  */

  // Create the external bigmatrix pointer and iniciate matrix accessor
  XPtr<BigMatrix> xpMat(pBigMat);
  MatrixAccessor<int> mat = (*xpMat);

  // Iterater over the elements in a matrix and when NA is found, substitute for "1"
  for(int i=0; i< xpMat->ncol(); i++){
    for(int j=0; j< xpMat->nrow(); j++){
      if(std::isnan(mat[j][i])){
        mat[j][i] = 1;
      }
    }
  }
}
</code>```

答:
Package bigmemory has some functions to check NAs.

Just add the header with #include <bigmemory/isna.hpp>.
And replace std::isnan(mat[j][i]) by isna(mat[j][i]).

Body:
I am using R bigmemory package and Rcpp to handle big matrices (1 to 10 Million column x 1000 rows). Once I read an interger matrix consisting in 0, 2 and NA into a filebacked bigmemory matrix in R I would like to modify through C++ all the NA values in order to do imputation of the mean values per column or an arbitrary-value-imputation (I show here the latter).

Below is the Rcpp function I have written and that does not work. My hope was that calling BigNA(mybigmatrix@address) from within R could find the elements in the matrix that are NAs and modify its values directly in the backing file.

I think the problem might be in the evaluation of std::isnan(mat[j][i]). I checked this by creating an alternative function that counts the NA values with an accumulator and indeed did not count any NA. But once this is solved, I am also not sure if the expression mat[j][i] = 1 would modify the value in the backing file. Writing those statements feels intuitive for me having an R background but might be wrong.

Any help/suggestion would be very much appreciated.

#include <stdio.h>
#include <Rcpp.h>
#include <bigmemory/MatrixAccessor.hpp>
#include <numeric>
// [[Rcpp::depends(BH, bigmemory)]]
// [[Rcpp::depends(Rcpp)]]

// [[Rcpp::export]]
void BigNA(SEXP pBigMat) {
  /*
  * Imputation of "NA" values for "1" in a big 0, 2 NA matrix.
  */

  // Create the external bigmatrix pointer and iniciate matrix accessor
  XPtr<BigMatrix> xpMat(pBigMat);
  MatrixAccessor<int> mat = (*xpMat);

  // Iterater over the elements in a matrix and when NA is found, substitute for "1"
  for(int i=0; i< xpMat->ncol(); i++){
    for(int j=0; j< xpMat->nrow(); j++){
      if(std::isnan(mat[j][i])){
        mat[j][i] = 1;
      }
    }
  }
}


问:
Gerrit project access allows users to remove the users from gerrit project
My Gerrit Version is -2.10.2

Regarding an Gerrit group (Delete user permission), I am the Gerrit administrator, I have user add/delete permission for Gerrit groups. Today I noticed that even the users who all have access to Gerrit group, are also able to remove users from Gerrit group. I thought, only admin can perform the manage groups and users permissions, whereas it is working for user as well. I have checked the project it has configured the access from “Rights Inherit From: All-Projects” also “Project All-Projects”  it has below settings.

Global Capabilities

```<code>Administrate Server -
Allow -  Administrators

Priority -
Batch -  Non-Interactive Users

Stream Events -
Allow - Non-Interactive Users
</code>```

Could you let me know where I can configure the permission, So that user should is not allowed to remove the user from Gerrit group. Only Gerrit administrator need to have users add & delete permission from Gerrit groups.

答:
Check the following:

Click on the "General" tab of some group.

Look at the group in the "Owners" field

All users that are members of the owner group (or members of one of its sub-groups) has the permission to add and remove users to original group.

Put the administrator group (or other group you want) in this field and click on the "Change owner" button.

Body:
My Gerrit Version is -2.10.2

Regarding an Gerrit group (Delete user permission), I am the Gerrit administrator, I have user add/delete permission for Gerrit groups. Today I noticed that even the users who all have access to Gerrit group, are also able to remove users from Gerrit group. I thought, only admin can perform the manage groups and users permissions, whereas it is working for user as well. I have checked the project it has configured the access from “Rights Inherit From: All-Projects” also “Project All-Projects”  it has below settings.

Global Capabilities

Administrate Server -
Allow -  Administrators

Priority -
Batch -  Non-Interactive Users

Stream Events -
Allow - Non-Interactive Users

Could you let me know where I can configure the permission, So that user should is not allowed to remove the user from Gerrit group. Only Gerrit administrator need to have users add & delete permission from Gerrit groups.


问:
Highchart.js variable length input doesn't work
This input would work well with highcharts:

```<code>data1 = [[2, 3, 3.5, 4], [1, 1.5, 2, 3]]
</code>```

But this won't:

```<code>data2 = [[2, 3, 3.5, 4, 4.5], [1, 1.5, 2, 3]]
</code>```

Here the only difference is that in the first item, there is one more data point. Why would highchart fail to make a boxplot from it? I think all it needs to generate a boxplots like median, quartiles and minimum and maximum are all there in the second dataset too.

This is my code:

```<code>dt = [
  [760, 801, 848, 895, 930],
  [733, 853, 939, 980, 1080],
  [714, 762, 817, 870, 918],
  [724, 802, 806, 871, 950],
  [834, 836, 864, 882, 910]
];

Highcharts.chart('boxcontainer', {

  chart: {
    type: 'boxplot'
  },

  title: {
    text: 'Highcharts box plot styling'
  },

  legend: {
    enabled: false
  },

  xAxis: {
    categories: ['1', '2', '3', '4', '5'],
    title: {
      text: 'Experiment No.'
    }
  },

  yAxis: {
    title: {
      text: 'Observations'
    }
  },

  plotOptions: {
    boxplot: {
      fillColor: '#F0F0E0',
      lineWidth: 2,
      medianColor: '#0C5DA5',
      medianWidth: 3,
      stemColor: '#A63400',
      stemDashStyle: 'dot',
      stemWidth: 1,
      whiskerColor: '#3D9200',
      whiskerLength: '20%',
      whiskerWidth: 3
    }
  },

  series: [{
    name: 'Observations',
    data: dt
  }]

});
</code>```

How can I solve this problem?

答:
Highcharts accepts input data in two formats

Array of numbers

array of objects

Especially when it comes to graphs like boxplot which need multiple values to plot a single point on the graph these approaches will help you achieve what we need.

Here are the 2 ways of doing for Boxplot.
1. An array of arrays with 6 or 5 values. In this case, the values correspond to x,low,q1,median,q3,high

```<code>data: [
    [0, 3, 0, 10, 3, 5],
    [1, 7, 8, 7, 2, 9],
    [2, 6, 9, 5, 1, 3]
]
</code>```

An array of objects with named values.

```<code>data: [{
x: 1,
low: 4,
q1: 9,
median: 9,
q3: 1,
high: 10,
name: "Point2",
color: "#00FF00"},{
x: 1,
low: 5,
q1: 7,
median: 3,
q3: 6,
high: 2,
name: "Point1",
color: "#FF00FF"}]
</code>```

So in the first approach when an extra value appears in the array is distorted and hence is your graph.

When ever you would like to have extra values in the data that are not needed for plotting but are important, you can go with the second approach.

Here are the links for your ref:
API : https://api.highcharts.com/highcharts/series.boxplot.data
Exaample: http://jsfiddle.net/fzwu1ods/

Body:
This input would work well with highcharts:

data1 = [[2, 3, 3.5, 4], [1, 1.5, 2, 3]]

But this won't:

data2 = [[2, 3, 3.5, 4, 4.5], [1, 1.5, 2, 3]]

Here the only difference is that in the first item, there is one more data point. Why would highchart fail to make a boxplot from it? I think all it needs to generate a boxplots like median, quartiles and minimum and maximum are all there in the second dataset too.

This is my code:

dt = [
  [760, 801, 848, 895, 930],
  [733, 853, 939, 980, 1080],
  [714, 762, 817, 870, 918],
  [724, 802, 806, 871, 950],
  [834, 836, 864, 882, 910]
];

Highcharts.chart('boxcontainer', {

  chart: {
    type: 'boxplot'
  },

  title: {
    text: 'Highcharts box plot styling'
  },

  legend: {
    enabled: false
  },

  xAxis: {
    categories: ['1', '2', '3', '4', '5'],
    title: {
      text: 'Experiment No.'
    }
  },

  yAxis: {
    title: {
      text: 'Observations'
    }
  },

  plotOptions: {
    boxplot: {
      fillColor: '#F0F0E0',
      lineWidth: 2,
      medianColor: '#0C5DA5',
      medianWidth: 3,
      stemColor: '#A63400',
      stemDashStyle: 'dot',
      stemWidth: 1,
      whiskerColor: '#3D9200',
      whiskerLength: '20%',
      whiskerWidth: 3
    }
  },

  series: [{
    name: 'Observations',
    data: dt
  }]

});

How can I solve this problem?

Body:
Highcharts accepts input data in two formats

Array of numbers

array of objects

Especially when it comes to graphs like boxplot which need multiple values to plot a single point on the graph these approaches will help you achieve what we need.

Here are the 2 ways of doing for Boxplot.
1. An array of arrays with 6 or 5 values. In this case, the values correspond to x,low,q1,median,q3,high

data: [
    [0, 3, 0, 10, 3, 5],
    [1, 7, 8, 7, 2, 9],
    [2, 6, 9, 5, 1, 3]
]

An array of objects with named values.

data: [{
x: 1,
low: 4,
q1: 9,
median: 9,
q3: 1,
high: 10,
name: "Point2",
color: "#00FF00"},{
x: 1,
low: 5,
q1: 7,
median: 3,
q3: 6,
high: 2,
name: "Point1",
color: "#FF00FF"}]

So in the first approach when an extra value appears in the array is distorted and hence is your graph.

When ever you would like to have extra values in the data that are not needed for plotting but are important, you can go with the second approach.

Here are the links for your ref:
API : https://api.highcharts.com/highcharts/series.boxplot.data
Exaample: http://jsfiddle.net/fzwu1ods/


问:
Javascript : many if conditions doesn't work for a regular expression
I have two if conditions to check a value, the two conditions are the same.

I must use if condition twice, and not if and else if.

Here the code below :

```<code>regexp = new RegExp("[458]", "gi");
valuesArray = [5, 8];

for(var i = 0; i < valuesArray.length; i++)
{
    if(regexp.test(valuesArray[i]) == true)
    {
        console.log("true : "+valuesArray[i]);
    }

    if(regexp.test(valuesArray[i]) == false)
    {
        console.log("false : "+valuesArray[i]);
    }
}
</code>```

The javascript console output is :

```<code>true : 5
false : 5
true : 8
false : 8
</code>```

But this should be (because 5 and 8 are in [458] regexp, so regexp test must return true) :

```<code>true : 5
true : 8
</code>```

So why it doesn't work ? Have you an idea ?

Thank you, cordially.

答:
try with regexp = new RegExp("[458]", "i"); instead of regexp = new RegExp("[458]", "gi");

because

```<code>g
global match; find all matches rather than stopping after the first match
i
ignore case
</code>```

regexp = new RegExp("[458]", "i");
valuesArray = [5, 8];

for (var i = 0; i < valuesArray.length; i++) {
  if (regexp.test(valuesArray[i]) == true) {
    console.log("true : " + valuesArray[i]);
  }

  if (regexp.test(valuesArray[i]) == false) {
    console.log("false : " + valuesArray[i]);
  }
}```

Body:
I have two if conditions to check a value, the two conditions are the same.

I must use if condition twice, and not if and else if.

Here the code below :

regexp = new RegExp("[458]", "gi");
valuesArray = [5, 8];

for(var i = 0; i < valuesArray.length; i++)
{
    if(regexp.test(valuesArray[i]) == true)
    {
        console.log("true : "+valuesArray[i]);
    }

    if(regexp.test(valuesArray[i]) == false)
    {
        console.log("false : "+valuesArray[i]);
    }
}

The javascript console output is :

true : 5
false : 5
true : 8
false : 8

But this should be (because 5 and 8 are in [458] regexp, so regexp test must return true) :

true : 5
true : 8

So why it doesn't work ? Have you an idea ?

Thank you, cordially.

Body:
try with regexp = new RegExp("[458]", "i"); instead of regexp = new RegExp("[458]", "gi");

because

g
global match; find all matches rather than stopping after the first match
i
ignore case

regexp = new RegExp("[458]", "i");
valuesArray = [5, 8];

for (var i = 0; i < valuesArray.length; i++) {
  if (regexp.test(valuesArray[i]) == true) {
    console.log("true : " + valuesArray[i]);
  }

  if (regexp.test(valuesArray[i]) == false) {
    console.log("false : " + valuesArray[i]);
  }
}


问:
How to display simple Google Calendar List View
Hey folks Im very new to Json and I have been trying to integrate a calendar list view into my website. The Goal is to create a simple list view like below from my Google Public Calendar using JSON

Event Name - Start and End Date
Event Name - Start and End Date
... (display 5 upcoming events)

Here is the URL for a GET : https://www.googleapis.com/calendar/v3/calendars/eaachapter309@gmail.com/events?key=AIzaSyBZilw_M3Jk14gkmGk_bBuQUcBr_EW5RI4

The problem I am having is displaying items that are nested within root elements. For example, based on the URL above I want to display each item in a row for the following child elements:

"items":
    "summary",
    "start",
    "End"

In the URL above there are 3 events (i.e. items)
Id like each one of these events to appear like below:

EAA Chapter 309 - Young Eagles Event - November 18, from 8:45am - 11:00pm

EAA Chapter 309 Build Night - November 14, from 5:00pm - 8:00pm

etc...

So within this example the code would need to do the following:

List up to 5 upcoming calendar event entries

List the child element named "summary" from within the parent element "items"

Iterate down to the Start-->dateTime child element and End-->dateTime elements

Convert from UTC time to standard 12hr.

Here is some code I was playing around but I have no idea what Im doing. Its using tables/rows to insert data BUT the repurposed code was using a POST to a php file that had a table in it called "Customers". I was trying to repurpose code but obviously its not working.
i.e.code example - http://eaa309.club/CalendarExample.html

Any help would be awesome!!!!

```<code><!DOCTYPE html>
<html>
<body>

<h2>Make a table based on JSON data.</h2>

<p id="demo"></p>

<script>
            var obj, dbParam, xmlhttp, myObj, x, txt = "";
            obj = { "Table":"Calendar", "limit":20 };
            dbParam = JSON.stringify(obj);
            xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    myObj = JSON.parse(this.responseText);
                    txt += "<table border='1' cellpadding='7' cellspacing='0'><tr><td>Event Summary</td><td>Event Start & End</td></tr>"
                    for (x in myObj) {
                        txt += "<tr><td>" + myObj[x].summary + "</td>" + "<td>Start & End Date from JSON Data needs to go here</td></tr>";
                    }
                    txt += "</table>"
                    document.getElementById("demo").innerHTML = txt;
                }
            };
        xmlhttp.open("GET", "https://www.googleapis.com/calendar/v3/calendars/eaachapter309@gmail.com/events?key=AIzaSyBZilw_M3Jk14gkmGk_bBuQUcBr_EW5RI4", true);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.send("x=" + dbParam);

            </script>

</body>
</html>
</code>```

答:
The reason why the first two list items where repeated was because that's what's in the JSON data. Have a look at the raw JSON and you will see it. It's just a matter of using a filter to get rid of entities with status: "cancelled". As for the date format I think this should do it for you now, just replace this part of the code in your html file and you should be good to go.  </p>

```<code> //here we iterate over the object array
 $.each(data.items, function(i, item){
   //I do this to later format these timestamps
   //set options for date.toLocaleDateString() function

   var options = { month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit' };

   let start = new Date(item.start.dateTime).toLocaleDateString('en-US', options);

   let end = new Date(item.end.dateTime).toLocaleDateString('en-US', options);

   let end_splt = end.split(',');

    //append data to the list.
    if(item.status != "cancelled"){
      $('#myList').append(`
       <li>${item.summary} - ${start} - ${end_splt[1]} </li>
       `);
    }

 });

 }).fail(function(e){
   error(e);
 });
</code>```

Body:
Hey folks Im very new to Json and I have been trying to integrate a calendar list view into my website. The Goal is to create a simple list view like below from my Google Public Calendar using JSON

Event Name - Start and End Date
Event Name - Start and End Date
... (display 5 upcoming events)

Here is the URL for a GET : https://www.googleapis.com/calendar/v3/calendars/eaachapter309@gmail.com/events?key=AIzaSyBZilw_M3Jk14gkmGk_bBuQUcBr_EW5RI4

The problem I am having is displaying items that are nested within root elements. For example, based on the URL above I want to display each item in a row for the following child elements:

"items":
    "summary",
    "start",
    "End"

In the URL above there are 3 events (i.e. items)
Id like each one of these events to appear like below:

EAA Chapter 309 - Young Eagles Event - November 18, from 8:45am - 11:00pm

EAA Chapter 309 Build Night - November 14, from 5:00pm - 8:00pm

etc...

So within this example the code would need to do the following:

List up to 5 upcoming calendar event entries

List the child element named "summary" from within the parent element "items"

Iterate down to the Start-->dateTime child element and End-->dateTime elements

Convert from UTC time to standard 12hr.

Here is some code I was playing around but I have no idea what Im doing. Its using tables/rows to insert data BUT the repurposed code was using a POST to a php file that had a table in it called "Customers". I was trying to repurpose code but obviously its not working.
i.e.code example - http://eaa309.club/CalendarExample.html

Any help would be awesome!!!!

<!DOCTYPE html>

Make a table based on JSON data.

Body:
The reason why the first two list items where repeated was because that's what's in the JSON data. Have a look at the raw JSON and you will see it. It's just a matter of using a filter to get rid of entities with status: "cancelled". As for the date format I think this should do it for you now, just replace this part of the code in your html file and you should be good to go.

 //here we iterate over the object array
 $.each(data.items, function(i, item){
   //I do this to later format these timestamps
   //set options for date.toLocaleDateString() function

   var options = { month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit' };

   let start = new Date(item.start.dateTime).toLocaleDateString('en-US', options);

   let end = new Date(item.end.dateTime).toLocaleDateString('en-US', options);

   let end_splt = end.split(',');

    //append data to the list.
    if(item.status != "cancelled"){
      $('#myList').append(`
       <li>${item.summary} - ${start} - ${end_splt[1]} </li>
       `);
    }

 });

 }).fail(function(e){
   error(e);
 });


问:
Connect https using nodejs
I am trying to maintain some old Node js code. I am having trouble in connecting to https url using corporate proxy.

Below code doesn't seem to work.

```<code>var https = require('https');
var options = {
    hostname: 'PROXY_IP',
    port    : PROXY_PORT,
    path : 'https://server.ourdomain.com/path/to/secure/api',
    rejectUnauthorized : false,
    headers: {
        'Authorization': 'Basic ' + new Buffer('username:password').toString('base64'),
        'Content-Type': 'application/json',
        'Host' : 'https://server.ourdomain.com:443'
    }
}
var responseChunk = '';
callback = function(response) {
    if(response.statusCode !== 200) {
        //Error occured. Handle error
    }
    response.on('data', function (chunk) {
        responseChunk += chunk;
    });
    response.on('end', function () {
        // Got complete response. Process and do something
    });
}
var get_req = https.request(options, callback);
get_req.on('error', function(e) {
    console.log("Error:" + e)
});
get_req.end();
</code>```

Error after executing this is

```<code>Error:Error: socket hang up
</code>```

I was able to get this working using request module. But not using https module.

What seems to be the problem?

答:
Use request..</p>

```<code>var request = require('request');
request({'url':'https://anysite.you.want/sub/sub','proxy':'http://yourproxy:8087'}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
})
</code>```

Title: Connect https using nodejs

Body:
I am trying to maintain some old Node js code. I am having trouble in connecting to https url using corporate proxy.

Below code doesn't seem to work.

var https = require('https');
var options = {
    hostname: 'PROXY_IP',
    port    : PROXY_PORT,
    path : 'https://server.ourdomain.com/path/to/secure/api',
    rejectUnauthorized : false,
    headers: {
        'Authorization': 'Basic ' + new Buffer('username:password').toString('base64'),
        'Content-Type': 'application/json',
        'Host' : 'https://server.ourdomain.com:443'
    }
}
var responseChunk = '';
callback = function(response) {
    if(response.statusCode !== 200) {
        //Error occured. Handle error
    }
    response.on('data', function (chunk) {
        responseChunk += chunk;
    });
    response.on('end', function () {
        // Got complete response. Process and do something
    });
}
var get_req = https.request(options, callback);
get_req.on('error', function(e) {
    console.log("Error:" + e)
});
get_req.end();

Error after executing this is

Error:Error: socket hang up

I was able to get this working using request module. But not using https module.

What seems to be the problem?

Body:
Use request..

var request = require('request');
request({'url':'https://anysite.you.want/sub/sub','proxy':'http://yourproxy:8087'}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
})


问:
Setting up freeRadius accounting
I'm completely new to this.
My accounting data only update when the user disconnect i want to know how to set up a acct-interim-interval to harvest the acct data without needing to disconnect my users.
I have like 2k users
How do i do that ?</p>

答:
Go to your radgroupreply table:

Add a row

ID: Auto increment

groupname: Name of the group that you want to monitor (use accounting without disconnecting users)

attribule: Acct-Interim-Interval

op: := (Note-> it's := not = not == just :=)

value: Time in seconds of your updates (Default is 60 or 120 secs i guess)

PS: You also need to enable Accouting inside your mikroktik.
Go to PPP menu -> Secrets -> PPP Authentiction&Accouting and select Accounting -> Select Use Radius and Accounting

Now you are ready to go!

Title: Setting up freeRadius accounting


问:
Vb net Or logic is not working
I want to permit my user to save data if he has given 11 characters or 17 characters in the textbox.
I have written this code for my vb net form input. But this logic is not working. if i remove the Or condition than this code works for 11 characters.
But i want to implement for 11 and 17 characters both.</p>

```<code>If (txtSSN.Text.Length <> 11 Or txtSSN.Text.Length <> 17) Then
    MessageBox.Show(" National ID should be 11 or 17 characters!!",
                    "Saving Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    txtSSN.Focus()
    Return False
End If
</code>```

答:
These three examples will work:

```<code>If Not txtSSN.Text.Length = 11 And Not txtSSN.Text.Length = 17 Then
    MessageBox.Show("National ID should be 11 or 17 characters!!",
                    "Saving Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
</code>```

```<code>If txtSSN.Text.Length <> 11 And txtSSN.Text.Length <> 17 Then
    MessageBox.Show("National ID should be 11 or 17 characters!!",
                    "Saving Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
</code>```

```<code>If Not (txtSSN.Text.Length = 11 Or txtSSN.Text.Length = 17) Then
    MessageBox.Show("National ID should be 11 or 17 characters!!",
                    "Saving Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
</code>```

Title: Vb net Or logic is not working

Body:
I want to permit my user to save data if he has given 11 characters or 17 characters in the textbox.
I have written this code for my vb net form input. But this logic is not working. if i remove the Or condition than this code works for 11 characters.
But i want to implement for 11 and 17 characters both.

If (txtSSN.Text.Length <> 11 Or txtSSN.Text.Length <> 17) Then
    MessageBox.Show(" National ID should be 11 or 17 characters!!",
                    "Saving Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    txtSSN.Focus()
    Return False
End If

Body:
These three examples will work:

If Not txtSSN.Text.Length = 11 And Not txtSSN.Text.Length = 17 Then
    MessageBox.Show("National ID should be 11 or 17 characters!!",
                    "Saving Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If

If txtSSN.Text.Length <> 11 And txtSSN.Text.Length <> 17 Then
    MessageBox.Show("National ID should be 11 or 17 characters!!",
                    "Saving Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If

If Not (txtSSN.Text.Length = 11 Or txtSSN.Text.Length = 17) Then
    MessageBox.Show("National ID should be 11 or 17 characters!!",
                    "Saving Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If


问:
Aligning the divs in a single line
I am trying to align two divs inside one div in a single line . I have tried with the following code:

```<code><div style="width:100%">
 <div id="id1" style="width:40%;float:left;background-color:green;position:relative">
   float-left
 </div>
 <div id="id2" style="width:60%;float:right;background-color:yellow;position:relative">
 float-right
   <div id="id3" style="position:relative;left:0px">
   button1
   </div>
    <div id="id4" style="position:absolute;right:0px">
   button2
   </div>
 </div>
</div>
</code>```

I need divs with id3 and id4 in the same line similar to span but I dont want to use a span tag , within id2 div?

I tried using position as both absolute and relative and combinations but it is not aligning within same line. What is it that I am missing?

答:
The best solution is to set display: inline-block like this:

```<code> <div id="id2" style="width:60%;float:right;background-color:yellow;position:relative">
 float-right
   <div id="id3" style="display: inline-block;">
   button1
   </div>
    <div id="id4" style="display: inline-block;">
   button2
   </div>
 </div>
</div>
</code>```

You could also add the property top: 0px which will give you the same result. However, display: inline-block is much cleaner and exists because of your exact problem.

A div is initially a block and therefore spans the entire width of its parent element. This means divs are placed below each other, if they're not told to be inline-blocks, which will make them "wrap" their content.

Add borders to your elements and see the difference of inline-block and just block.

Title: Aligning the divs in a single line

Body:
I am trying to align two divs inside one div in a single line . I have tried with the following code:

   float-left

 float-right

   button1

   button2

I need divs with id3 and id4 in the same line similar to span but I dont want to use a span tag , within id2 div?

I tried using position as both absolute and relative and combinations but it is not aligning within same line. What is it that I am missing?

Body:
The best solution is to set display: inline-block like this:

 <div id="id2" style="width:60%;float:right;background-color:yellow;position:relative">
 float-right
   <div id="id3" style="display: inline-block;">
   button1
   </div>
    <div id="id4" style="display: inline-block;">
   button2
   </div>
 </div>
</div>

You could also add the property top: 0px which will give you the same result. However, display: inline-block is much cleaner and exists because of your exact problem.

A div is initially a block and therefore spans the entire width of its parent element. This means divs are placed below each other, if they're not told to be inline-blocks, which will make them "wrap" their content.

Add borders to your elements and see the difference of inline-block and just block.


问:
How to install Openpyxl with pip
I have windows 10 (64 bit). I want to utilize the Openpyxl package to start learning how to interact with excel and other spreadsheets.

I installed Python with "windowsx86-64web-basedinstaller" I have a 64 bit OS, was I mistaken when trying to install this version?

答:
https://pypi.python.org/pypi/openpyxl
download zip file and unzip it on local system.

go to openpyxl folder where setup.py is present.

open command prompt under the same path.

Run a command: python setup.py install

It will install openpyxl.

Title: How to install Openpyxl with pip


问:
Gradle copy and rename in loop
I'm working with Android Studio 3.

For each flavor, I want to copy mapping.txt and rename it.

My Gradle task :

```<code>task deployApks(type: Copy) {
        android.applicationVariants.all { variant ->
            if (variant.buildType.name == 'release') {
            variant.outputs.all {
                  def flavor = variant.productFlavors.name.get(0)

                  def dirApk = System.getProperty("user.dir") + '/app/build/' + flavor + '/release/'
                  def dirMapping = System.getProperty("user.dir") + '/app/build/outputs/mapping/' + flavor + '/release/'

                  //copy apk and mapping.txt
                  from dirApk, dirMapping
                  include '*-release.apk', 'mapping.txt'
                  into dirDeploy

                  //rename mapping.txt
                  from dirDeploy
                  include 'mapping.txt'
                  into dirDeploy
                  rename 'mapping.txt', 'mapping-' + flavor + '.txt'
                  println("Rename mapping.txt tomapping-" + flavor + ".txt")
             }
        }
    }
}
</code>```

What I want in deploy directory :

flavor1-release.apk

mapping-flavor1.txt

flavor2-release.apk

mapping-flavor2.txt

What I get :

flavor1-release.apk

mapping-flavor1.txt

flavor2-release.apk

Is gradle copy asynchronous.?

It looks like if renaming is done after all copies.

答:
You may not know but gradle build consists of 3 phases:

initialisation

configuration

execution

Task (including Copy you used) actions (a task is a collection of actions run in order) are configured in the second phase. Eve if you put loop in task's body the last iteration will win. The easiest way is to change your task to the following (copying manually):

```<code>task deployApks {
  doLast {
    android.applicationVariants.all { variant ->
      if (variant.buildType.name == 'release') {
      variant.outputs.all {
        def flavor = variant.productFlavors.name.get(0)

        def dirApk = System.getProperty("user.dir") + '/app/build/' + flavor + '/release/'
        def dirMapping = System.getProperty("user.dir") + '/app/build/outputs/mapping/' + flavor + '/release/'

        //copy apk and mapping.txt
        copy {
          from dirApk, dirMapping
          include '*-release.apk', 'mapping.txt'
          into dirDeploy
          rename 'mapping.txt', 'mapping-' + flavor + '.txt'
        }
       }
      }
    }
  }
}
</code>```

If that solves the problem - (you don't need to task caching) you can work with. Otherwise you need to configure Copy task appropriately or even write a custom task.

Title: Gradle copy and rename in loop

Body:
I'm working with Android Studio 3.

For each flavor, I want to copy mapping.txt and rename it.

My Gradle task :

task deployApks(type: Copy) {
        android.applicationVariants.all { variant ->
            if (variant.buildType.name == 'release') {
            variant.outputs.all {
                  def flavor = variant.productFlavors.name.get(0)

                  def dirApk = System.getProperty("user.dir") + '/app/build/' + flavor + '/release/'
                  def dirMapping = System.getProperty("user.dir") + '/app/build/outputs/mapping/' + flavor + '/release/'

                  //copy apk and mapping.txt
                  from dirApk, dirMapping
                  include '*-release.apk', 'mapping.txt'
                  into dirDeploy

                  //rename mapping.txt
                  from dirDeploy
                  include 'mapping.txt'
                  into dirDeploy
                  rename 'mapping.txt', 'mapping-' + flavor + '.txt'
                  println("Rename mapping.txt tomapping-" + flavor + ".txt")
             }
        }
    }
}

What I want in deploy directory :

flavor1-release.apk

mapping-flavor1.txt

flavor2-release.apk

mapping-flavor2.txt

What I get :

flavor1-release.apk

mapping-flavor1.txt

flavor2-release.apk

Is gradle copy asynchronous.?

It looks like if renaming is done after all copies.

Body:
You may not know but gradle build consists of 3 phases:

initialisation

configuration

execution

Task (including Copy you used) actions (a task is a collection of actions run in order) are configured in the second phase. Eve if you put loop in task's body the last iteration will win. The easiest way is to change your task to the following (copying manually):

task deployApks {
  doLast {
    android.applicationVariants.all { variant ->
      if (variant.buildType.name == 'release') {
      variant.outputs.all {
        def flavor = variant.productFlavors.name.get(0)

        def dirApk = System.getProperty("user.dir") + '/app/build/' + flavor + '/release/'
        def dirMapping = System.getProperty("user.dir") + '/app/build/outputs/mapping/' + flavor + '/release/'

        //copy apk and mapping.txt
        copy {
          from dirApk, dirMapping
          include '*-release.apk', 'mapping.txt'
          into dirDeploy
          rename 'mapping.txt', 'mapping-' + flavor + '.txt'
        }
       }
      }
    }
  }
}

If that solves the problem - (you don't need to task caching) you can work with. Otherwise you need to configure Copy task appropriately or even write a custom task.


问:
How can I print message in Makefile?
I want to print some message while doing build process with a makefile. The following one can print the message, but it will not execute the script after it.  How can I fix this issues?

```<code>ifeq (yes, ${TEST})
        CXXFLAGS := ${CXXFLAGS} -DDESKTOP_TEST
test:
        @echo '************  TEST VERSION ************'
else
release:
        @echo "************ RELEASE VERSIOIN **********"
endif
</code>```

答:
$(info your_text)    : Information. This doesn't stop the execution.

$(warning your_text) : Warning. This shows the text as a warning.

$(error your_text)   : Fatal Error. This will stop the execution.

src: https://www.gnu.org/software/make/manual/make.html#Make-Control-Functions

Title: How can I print message in Makefile?

Body:
I want to print some message while doing build process with a makefile. The following one can print the message, but it will not execute the script after it.  How can I fix this issues?

ifeq (yes, ${TEST})
        CXXFLAGS := ${CXXFLAGS} -DDESKTOP_TEST
test:
        @echo '************  TEST VERSION ************'
else
release:
        @echo "************ RELEASE VERSIOIN **********"
endif


问:
How to build and deploy an app from local directory?
I just started exploring OpenShift Online 3 and it seems really awesome.
I'm trying to setup a simple HTTP server.
Here are my steps using CLI:

oc login <...>

oc new-project <...>

oc new-app .

My current working folder consists of two files package.json and server.js.

Package.json

```<code>{
  "name": "test",
  "version": "0.0.1",
  "description": "Node.js app for OpenShift 3",
  "main": "server.js",
  "dependencies": {
    "express": "^4.13.4"
  },
  "engine": {
    "node": "*",
    "npm": "*"
  },
  "scripts": {
    "start": "node server.js"
  }
}
</code>```

Server.js

```<code>const express = require('express')
const app = express()

const port = process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT || 8080
const ip = process.env.IP   || process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0'

app.get('/', function (req, res) {
  res.status(200).send({ message: 'OK' })
})

// error handling
app.use(function(err, req, res, next){
  console.error(err.stack)
  res.status(500).send('Something bad happened!')
})

app.listen(port, ip)
console.log('Server running on http://%s:%s', ip, port)

module.exports = app
</code>```

Here's console output:

```<code>--> Creating resources ...
    imagestream "olmeo-openshift" created
    buildconfig "olmeo-openshift" created
    deploymentconfig "olmeo-openshift" created
    service "olmeo-openshift" created
--> Success
    Build scheduled, use 'oc logs -f bc/olmeo-openshift' to track its progress.
    Run 'oc status' to view your app.
</code>```

After build is done web console shows an error:

```<code>Environment:
    DEV_MODE=false
    NODE_ENV=production
    DEBUG_PORT=5858
Launching via npm...
npm info it worked if it ends with ok
npm info using npm@3.10.9
npm info using node@v6.11.3
npm ERR! Linux 3.10.0-693.12.1.el7.x86_64
npm ERR! argv "/opt/rh/rh-nodejs6/root/usr/bin/node" "/opt/rh/rh-nodejs6/root/usr/bin/npm" "run" "-d" "start"
npm ERR! node v6.11.3
npm ERR! npm  v3.10.9
npm ERR! path /opt/app-root/src/package.json
npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall open

npm ERR! enoent ENOENT: no such file or directory, open '/opt/app-root/src/package.json'
npm ERR! enoent ENOENT: no such file or directory, open '/opt/app-root/src/package.json'
npm ERR! enoent This is most likely not a problem with npm itself
npm ERR! enoent and is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! Please include the following file with any support request:
npm ERR!     /opt/app-root/src/npm-debug.log
</code>```

Apparently, package.json can't be found. What am I missing?

答:
If you use:

```<code>oc new-app .
</code>```

in a git workarea cloned off a remotely hosted Git repository, the build will be set up to pull files from the hosted Git repository. This means that if you make local changes and don't add/commit/push them to the hosted Git repository, then they will never be used.

If you want to work from a local directory and not use a hosted Git repository, you need to use a binary input build. To do that first run:

```<code>oc new-build --binary --image-stream nodejs --name olmeo-openshift
</code>```

Then start a build by running:

```<code>oc start-build olmeo-openshift --from-dir=.
</code>```

This will upload files from the local directory.

Once the first image has been built, then you can run:

```<code>oc new-app olmeo-openshift
</code>```

to deploy the image, and:

```<code>oc expose svc/olmeo-openshift
</code>```

to give it a public URL.

Each time you make code changes, run again:

```<code>oc start-build olmeo-openshift --from-dir=.
</code>```

Body:
I just started exploring OpenShift Online 3 and it seems really awesome.
I'm trying to setup a simple HTTP server.
Here are my steps using CLI:

oc login <...>

oc new-project <...>

oc new-app .

My current working folder consists of two files package.json and server.js.

Package.json

{
  "name": "test",
  "version": "0.0.1",
  "description": "Node.js app for OpenShift 3",
  "main": "server.js",
  "dependencies": {
    "express": "^4.13.4"
  },
  "engine": {
    "node": "*",
    "npm": "*"
  },
  "scripts": {
    "start": "node server.js"
  }
}

Server.js

const express = require('express')
const app = express()

const port = process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT || 8080
const ip = process.env.IP   || process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0'

app.get('/', function (req, res) {
  res.status(200).send({ message: 'OK' })
})

// error handling
app.use(function(err, req, res, next){
  console.error(err.stack)
  res.status(500).send('Something bad happened!')
})

app.listen(port, ip)
console.log('Server running on http://%s:%s', ip, port)

module.exports = app

Here's console output:

--> Creating resources ...
    imagestream "olmeo-openshift" created
    buildconfig "olmeo-openshift" created
    deploymentconfig "olmeo-openshift" created
    service "olmeo-openshift" created
--> Success
    Build scheduled, use 'oc logs -f bc/olmeo-openshift' to track its progress.
    Run 'oc status' to view your app.

After build is done web console shows an error:

Environment:
    DEV_MODE=false
    NODE_ENV=production
    DEBUG_PORT=5858
Launching via npm...
npm info it worked if it ends with ok
npm info using npm@3.10.9
npm info using node@v6.11.3
npm ERR! Linux 3.10.0-693.12.1.el7.x86_64
npm ERR! argv "/opt/rh/rh-nodejs6/root/usr/bin/node" "/opt/rh/rh-nodejs6/root/usr/bin/npm" "run" "-d" "start"
npm ERR! node v6.11.3
npm ERR! npm  v3.10.9
npm ERR! path /opt/app-root/src/package.json
npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall open

npm ERR! enoent ENOENT: no such file or directory, open '/opt/app-root/src/package.json'
npm ERR! enoent ENOENT: no such file or directory, open '/opt/app-root/src/package.json'
npm ERR! enoent This is most likely not a problem with npm itself
npm ERR! enoent and is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! Please include the following file with any support request:
npm ERR!     /opt/app-root/src/npm-debug.log

Apparently, package.json can't be found. What am I missing?

Body:
If you use:

oc new-app .

in a git workarea cloned off a remotely hosted Git repository, the build will be set up to pull files from the hosted Git repository. This means that if you make local changes and don't add/commit/push them to the hosted Git repository, then they will never be used.

If you want to work from a local directory and not use a hosted Git repository, you need to use a binary input build. To do that first run:

oc new-build --binary --image-stream nodejs --name olmeo-openshift

Then start a build by running:

oc start-build olmeo-openshift --from-dir=.

This will upload files from the local directory.

Once the first image has been built, then you can run:

oc new-app olmeo-openshift

to deploy the image, and:

oc expose svc/olmeo-openshift

to give it a public URL.

Each time you make code changes, run again:

oc start-build olmeo-openshift --from-dir=.


问:
Enable button if the mentioned input boxed are filled using jquery?
HTML:

```<code><input type="text" id="message"/>
<input type="text" id="message1"/>
<input type="button" class="sendButton" value="submit"/>
</code>```

This code displays two input boxes and one submit button.

jQuery:

```<code>$(document).ready(function(){
    $('.sendButton').attr('disabled',true);

    $("#message,#message1").bind(" change",function(){
        if($(this).val().length !=0){
            $('.sendButton').attr('disabled', false);
        }
        else
        {
            $('.sendButton').attr('disabled', true);
        }
    });
});
</code>```

This is my jQuery to enable and disable buttons. But it enables the button, if one of the field is filled.I want to enable it only when both the input fields are filled.

答:
Here is a simple small solution. Instead of checking for hardcode IDs and change event, you can actually use input with input event. This means, even if your input elements increase, this snippet would work:

$('input').on('input', function() {
  $(".sendButton").prop('disabled', true);
  if (checkIfEmpty()) {
    $(".sendButton").prop('disabled', false);
  }
});

function checkIfEmpty() {
  var flag = true;
  $('input').each(function() {
    var enteredValue = $(this).val();

    if ($.trim(enteredValue).length == 0)
      flag = false;
  });
  return flag;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="message" />
<input type="text" id="message1" />
<input type="button" class="sendButton" value="submit" disabled /></code>```

Body:
HTML:

<input type="text" id="message"/>
<input type="text" id="message1"/>
<input type="button" class="sendButton" value="submit"/>

This code displays two input boxes and one submit button.

jQuery:

$(document).ready(function(){
    $('.sendButton').attr('disabled',true);

    $("#message,#message1").bind(" change",function(){
        if($(this).val().length !=0){
            $('.sendButton').attr('disabled', false);
        }
        else
        {
            $('.sendButton').attr('disabled', true);
        }
    });
});

This is my jQuery to enable and disable buttons. But it enables the button, if one of the field is filled.I want to enable it only when both the input fields are filled.

Body:
Here is a simple small solution. Instead of checking for hardcode IDs and change event, you can actually use input with input event. This means, even if your input elements increase, this snippet would work:

$('input').on('input', function() {
  $(".sendButton").prop('disabled', true);
  if (checkIfEmpty()) {
    $(".sendButton").prop('disabled', false);
  }
});

function checkIfEmpty() {
  var flag = true;
  $('input').each(function() {
    var enteredValue = $(this).val();

    if ($.trim(enteredValue).length == 0)
      flag = false;
  });
  return flag;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="message" />
<input type="text" id="message1" />
<input type="button" class="sendButton" value="submit" disabled />


问:
Confluence Storage Format - Anyone played with anchor and anchor-link macro
I am parsing dita xml and I have to generate Confluence Storage Format.

I am facing difficulty with Anchor macro, while dita format have xref who behave the same way as html local link <xref href="#id">title</xref>....<any id="id"..., confluence seam to have its own unique synthax.

Did someone have any good example on how to build a correct anchor and link it properly?

答:
There is a small mistake in the Saloparenator's answer. The anchor link is:</p>

```<code><ac:link ac:anchor="The_Id">
    <ac:plain-text-link-body>
        <[CDATA[text describing the link]]>
    </ac:plain-text-link-body>
</ac:link>
</code>```

Body:
There is a small mistake in the Saloparenator's answer. The anchor link is:

<ac:link ac:anchor="The_Id">
    <ac:plain-text-link-body>
        <[CDATA[text describing the link]]>
    </ac:plain-text-link-body>
</ac:link>