问:
'cp932' codec can't encode character '\u98c8' in position 32: illegal multibyte sequence
I want to write strings to a file but get a UnicodeEncodeError.

```<code>      7 with open('testfile.txt', 'w') as f:
      8     for item in list:
----> 9         f.write("%s\n" % item)
</code>```

UnicodeEncodeError: 'cp932' codec can't encode character '\u98c8' in position 32: illegal multibyte sequence

How to fix this?

My program gets a text from web pages and saves them as a .txt file.

答:
Try setting utf-8 encoding to your file data,</p>

```<code>with open('testfile.txt', 'w', encoding="utf-8") as f:
    for item in list:
        f.write("%s\n" % item)
</code>```

Body:
I want to write strings to a file but get a UnicodeEncodeError.

      7 with open('testfile.txt', 'w') as f:
      8     for item in list:
----> 9         f.write("%s\n" % item)

UnicodeEncodeError: 'cp932' codec can't encode character '\u98c8' in position 32: illegal multibyte sequence

How to fix this?

My program gets a text from web pages and saves them as a .txt file.

Body:
Try setting utf-8 encoding to your file data,

with open('testfile.txt', 'w', encoding="utf-8") as f:
    for item in list:
        f.write("%s\n" % item)


来源: stackexchange

问:
Highcharts addPlotLine for one set of values
I have the following code. For a given day it shows the average wait time and the maximum wait time in seconds. The plotline currently gives an average of these two values. What I would like is that the average just take into account the average times so for a particular period as chosen by the user, the line would display the average for that period</p>

```<code>var seriesOptionsChatChart = [],
seriesCounterChatChart = 0,
namesChatChart = ['ChatChartAVG','ChatChartMAX'];

function createChartChatChart() {

    Highcharts.stockChart('chart27', {

        rangeSelector: {
            buttons: [{
                type: 'day',
                count: 1,
                text: '1d'
            },{
                type: 'day',
                count: 5,
                text: '5d'
            }, {
                type: 'week',
                count: 1,
                text: '1w'
            }, {
                type: 'month',
                count: 1,
                text: '1m'
            }, {
                type: 'month',
                count: 3,
                text: '3m'
            }, {
                type: 'year',
                count: 1,
                text: '1y'
            }, {
                type: 'all',
                text: 'All'
            }],
            selected: 3 // all
        },
    credits: {
          enabled: false
      },
          chart: {
            zoomType: 'x',
            events: {
                load: computeAvg,
                redraw: computeAvg
            }
        },

        yAxis: {

            plotLines: [{
                value: 0,
                width: 2,
                color: 'silver'
            }],
            title: {
                text: 'Seconds'
            }
        },

        plotOptions: {
            series: {
                showInNavigator: true,
                turboThreshold:0
            }
        },

        tooltip: {
            pointFormat: '<span style="color:{series.color}">Seconds</span>: <b>{point.y}</b><br/>',
            split: true
        },

        series: seriesOptionsChatChart
    });
}

$.each(namesChatChart, function (i, name) {

    $.getJSON('/' + name.toLowerCase(),    function (data) {

        if (name=='ChatChartMAX') {
            seriesColour = '#D50000';
        }
        else {
            seriesColour = '#1DA2B6';
        }

        seriesOptionsChatChart[i] = {
            name: name,
            data: data,
            color: seriesColour,
        };
        seriesCounterChatChart += 1;
        if (seriesCounterChatChart === namesChatChart.length) {
            createChartChatChart();
        }
    });
});

function computeAvg() {
    var chart = this,
        series = chart.series,
        yAxis = chart.yAxis[0],
        xAxis = chart.xAxis[0],
        extremes = xAxis.getExtremes(),
        min = extremes.min,
        max = extremes.max,
        plotLine = chart.get('avgLine'),
        sum = 0,
        count = 0;

    Highcharts.each(series, function (serie, i) {
        if(serie.name !== 'Navigator') {
            Highcharts.each(serie.data, function (point, j) {
                if (point.x >= min && point.x <= max) {
                    sum += point.y;
                    count++;
                }
            });
        }
    });

    yAxis.removePlotLine('avgLine');
    yAxis.addPlotLine({
        value: (sum/count),
        color: '#52B184',
        width: 2,
        id: 'avgLine',
        label: {
          text: (sum / count).toFixed(2),
          verticalAlign: 'middle',
          align: 'right',
          rotation: 0,
        }
    });

}
</code>```

答: Changed if(serie.name !== 'Navigator') { to focus on the series I wanted

ContentLicense: CC BY-SA 3.0

Body:
I have the following code. For a given day it shows the average wait time and the maximum wait time in seconds. The plotline currently gives an average of these two values. What I would like is that the average just take into account the average times so for a particular period as chosen by the user, the line would display the average for that period

var seriesOptionsChatChart = [],
seriesCounterChatChart = 0,
namesChatChart = ['ChatChartAVG','ChatChartMAX'];

function createChartChatChart() {

    Highcharts.stockChart('chart27', {

        rangeSelector: {
            buttons: [{
                type: 'day',
                count: 1,
                text: '1d'
            },{
                type: 'day',
                count: 5,
                text: '5d'
            }, {
                type: 'week',
                count: 1,
                text: '1w'
            }, {
                type: 'month',
                count: 1,
                text: '1m'
            }, {
                type: 'month',
                count: 3,
                text: '3m'
            }, {
                type: 'year',
                count: 1,
                text: '1y'
            }, {
                type: 'all',
                text: 'All'
            }],
            selected: 3 // all
        },
    credits: {
          enabled: false
      },
          chart: {
            zoomType: 'x',
            events: {
                load: computeAvg,
                redraw: computeAvg
            }
        },

        yAxis: {

            plotLines: [{
                value: 0,
                width: 2,
                color: 'silver'
            }],
            title: {
                text: 'Seconds'
            }
        },

        plotOptions: {
            series: {
                showInNavigator: true,
                turboThreshold:0
            }
        },

        tooltip: {
            pointFormat: 'Seconds: {point.y}
',
            split: true
        },

        series: seriesOptionsChatChart
    });
}

$.each(namesChatChart, function (i, name) {

    $.getJSON('/' + name.toLowerCase(),    function (data) {

        if (name=='ChatChartMAX') {
            seriesColour = '#D50000';
        }
        else {
            seriesColour = '#1DA2B6';
        }

        seriesOptionsChatChart[i] = {
            name: name,
            data: data,
            color: seriesColour,
        };
        seriesCounterChatChart += 1;
        if (seriesCounterChatChart === namesChatChart.length) {
            createChartChatChart();
        }
    });
});

function computeAvg() {
    var chart = this,
        series = chart.series,
        yAxis = chart.yAxis[0],
        xAxis = chart.xAxis[0],
        extremes = xAxis.getExtremes(),
        min = extremes.min,
        max = extremes.max,
        plotLine = chart.get('avgLine'),
        sum = 0,
        count = 0;

    Highcharts.each(series, function (serie, i) {
        if(serie.name !== 'Navigator') {
            Highcharts.each(serie.data, function (point, j) {
                if (point.x >= min && point.x <= max) {
                    sum += point.y;
                    count++;
                }
            });
        }
    });

    yAxis.removePlotLine('avgLine');
    yAxis.addPlotLine({
        value: (sum/count),
        color: '#52B184',
        width: 2,
        id: 'avgLine',
        label: {
          text: (sum / count).toFixed(2),
          verticalAlign: 'middle',
          align: 'right',
          rotation: 0,
        }
    });

}


问:
angular - vc-recaptcha in sibling controllers
I have a view where I have two sibling controllers - AppsController and CampaignsController. Each view contains a captcha widget respectively:

```<code>  <div class="sign-up-recaptca" vc-recaptcha key="'KEY'" on-create="onAppFormRecaptchaCreate(id)"></div>
  <div class="sign-up-recaptca" vc-recaptcha key="'KEY'" on-create="onCampaignFormReCaptchaCreate(id)"></div>
</code>```

And in their controllers, respectively:

```<code>$scope.onAppFormRecaptchaCreate = function (id) {
    console.log('id apps catcha is ' + id);

    $scope.appsRecaptchaID = id;
}

$scope.onCampaignFormReCaptchaCreate = function (id) {
    console.log('id campaigns catcha is ' + id);

    $scope.campaignsRecaptchaID = id;
}
</code>```

Both console.logs print undefined, however the Apps captcha works fine, maybe because it is loaded first. However, in the second one, when I run vcRecaptchaService.getResponse($scope.campaignsRecaptchaID) I get an empty string.

Thanks for your help.

答: I found my mistake. In the html the id parameter must be replaced with widgetId.

Body:
I have a view where I have two sibling controllers - AppsController and CampaignsController. Each view contains a captcha widget respectively:

And in their controllers, respectively:

$scope.onAppFormRecaptchaCreate = function (id) {
    console.log('id apps catcha is ' + id);

    $scope.appsRecaptchaID = id;
}

$scope.onCampaignFormReCaptchaCreate = function (id) {
    console.log('id campaigns catcha is ' + id);

    $scope.campaignsRecaptchaID = id;
}

Both console.logs print undefined, however the Apps captcha works fine, maybe because it is loaded first. However, in the second one, when I run vcRecaptchaService.getResponse($scope.campaignsRecaptchaID) I get an empty string.

Thanks for your help.


问:
SharpZipLib - ZipException "System.ArgumentOutOfRangeException" - Why am I getting this exception?
I'm using SharpZipLib to unzip files. My code has been working nicely for all zipfiles except the zip file what i am extracting now...

Got this exception:

```<code>System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: length
</code>```

The exception is being thrown at   size = s.Read(data, 0, data.Length);

Hereb is my code...

```<code> public static void UnzipFile(string sourcePath, string targetDirectory)
     {
        try
        {
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(sourcePath)))
            {
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    //string directoryName = Path.GetDirectoryName(theEntry.Name);
                    string fileName = Path.GetFileName(theEntry.Name);

                    if (targetDirectory.Length > 0)
                    {
                        Directory.CreateDirectory(targetDirectory);
                    }

                    if (fileName != String.Empty)
                    {
                        using (FileStream streamWriter = File.Create(targetDirectory + fileName))
                        {
                            int size = 2048;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception("Error unzipping file \"" + sourcePath + "\"", ex);
        }
    }
</code>```

答:
Looking at the code, you are reading the same set of bytes again (and advancing the position).

size = s.Read(data, 0, data.Length);

An example from here shows that the 2nd argument should be a moving position & not a fixed number.

ContentLicense: CC BY-SA 2.5

Body:
I'm using SharpZipLib to unzip files. My code has been working nicely for all zipfiles except the zip file what i am extracting now...

Got this exception:

System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: length

The exception is being thrown at   size = s.Read(data, 0, data.Length);

Hereb is my code...

 public static void UnzipFile(string sourcePath, string targetDirectory)
     {
        try
        {
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(sourcePath)))
            {
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    //string directoryName = Path.GetDirectoryName(theEntry.Name);
                    string fileName = Path.GetFileName(theEntry.Name);

                    if (targetDirectory.Length > 0)
                    {
                        Directory.CreateDirectory(targetDirectory);
                    }

                    if (fileName != String.Empty)
                    {
                        using (FileStream streamWriter = File.Create(targetDirectory + fileName))
                        {
                            int size = 2048;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception("Error unzipping file \"" + sourcePath + "\"", ex);
        }
    }


问:
Commands in IotAgent Ultralight 2.0 FIWARE
I am trying to send a command to a device using Orion + Ultralight 2.0.
The device is registered and I can send measures easily. I want to work in the pooling mode in order to execute commands, but when I execute the updateContext operation, IDAS doesn't found the entity. Here are the configuration and the logs:

Configuration:

```<code>var config = {};

config.mqtt = {
    host: 'mosquitto',
    port: 1883
};

config.http = {
    port: 7896
};

config.iota = {
    logLevel: 'DEBUG',
    timestamp: true,
    contextBroker: {
        host: 'MY_IP',
        port: '1026'
    },
    server: {
        port: 4041
    },
    deviceRegistry: {
        type: 'mongodb'
    },
    mongodb: {
        host: 'mongo',
        port: '27017',
        db: 'iotagentul'
    },
    types: {},
    service: 'howtoService',
    subservice: '/howto',
    providerUrl: 'http://YIP:4041',
    deviceRegistrationDuration: 'P1M',
    defaultType: 'Thing'
};

config.defaultKey = 'TEF';

module.exports = config;
</code>```

I have tried different IP's and routes, and at the end i tried with the public IP, assuring that there is communication from the outside to those ports.

Device registration:

```<code>curl -X POST \
  http://MYIP:4041/iot/devices \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -H 'fiware-service: howtoService' \
  -H 'fiware-servicepath: /howto' \
  -d '{
    "devices": [{
        "device_id": "muvone",
        "protocol": "IoTA-UL",
        "entity_name": "muvone",
        "entity_type": "Thing",
        "attributes": [{
            "object_id": "t",
            "name": "temperature",
            "type": "Float"
        }],
        "commands": [{
            "name":"blink",
            "type": "command",
            "value": "muvone@blink|%s"
        }],
        "static_attributes": []
    }]
}'
</code>```

Then I send some observations from a physical device and from POSTMAN:

```<code>curl -X POST \
  'http://MYIP:7896/iot/d?i=muvone&k=TEF&getCmd=1' \
  -H 'cache-control: no-cache' \
  -H 'fiware-service: howtoService' \
  -H 'fiware-servicepath: /howto' \
  -d 'temperature|16'
</code>```

Which actually updates the entity correctly, as can be seen in Orion Context Broker:
Query:

```<code>curl -X GET \
  http://MYIP:1026/v2/entities \
  -H 'cache-control: no-cache' \
  -H 'fiware-service: howtoService' \
  -H 'fiware-servicepath: /howto' \
</code>```

Response:

```<code>[
  {
    "id": "muvone",
    "type": "Thing",
    "TimeInstant": {
      "type": "ISO8601",
      "value": "2017-06-01T11:37:52.537Z",
      "metadata": {}
    },
    "blink_info": {
      "type": "commandResult",
      "value": " ",
      "metadata": {}
    },
    "blink_status": {
      "type": "commandStatus",
      "value": "UNKNOWN",
      "metadata": {}
    },
    "temperature": {
      "type": "Float",
      "value": "16",
      "metadata": {
        "TimeInstant": {
          "type": "ISO8601",
          "value": "2017-06-01T11:37:52.537Z"
        }
      }
    }
  }
]
</code>```

So now, If I want to send a command, I have done it in a lot of ways. I tried following this guide:

http://fiware-iot-stack.readthedocs.io/en/master/topics/device_connection/index.html

So I tried to use the following request:

```<code>curl -X PUT \
  http://MYIP:1026/v2/entities \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -H 'fiware-service: howtoService' \
  -H 'fiware-servicepath: /howto' \
  -d '{
  "id": "muvone",
  "type": "Thing",
  "blink": {
    "type" : "command",
    "value" : "true"
  }
}'
</code>```

Which response is:

```<code>{
  "error": "MethodNotAllowed",
  "description": "method not allowed"
}
</code>```

So I tried updating a single attribute, in this case the blink attribute, which is a command. This should trigger that the Orion Context Broker acts as a NGSI proxy and passes the request to the IoTAgent, which occurs. But the problem is that the IoTAgent doesn't find the entity, as it can be seen in the logs:

```<code>curl -X PUT \
  'http://MYIP:1026/v2/entities/muvone/attrs/blink?type=Thing' \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -H 'fiware-service: howtoService' \
  -H 'fiware-servicepath: /howto' \
  -d '{
    "type": "command",
    "value": "true"
}'
</code>```

or

```<code>curl -X PUT \
  'http://MYIP:1026/v2/entities/muvone/attrs/blink?type=Thing' \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -H 'fiware-service: howtoService' \
  -H 'fiware-servicepath: /howto' \
  -H 'postman-token: 6b42d06d-2a9f-3081-e315-bd9919aeded5' \
  -d '{
    "value": "true"
}'
</code>```

Responds with:

```<code>{
  "error": "NotFound",
  "description": "The requested entity has not been found. Check type and id"
}
</code>```

Edit: The get v2/entities to orion result, after issuing these requests is:

```<code>curl -X POST \
  http://MYIP:4041/iot/devices \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -H 'fiware-service: howtoService' \
  -H 'fiware-servicepath: /howto' \
  -d '{
    "devices": [{
        "device_id": "muvone",
        "protocol": "IoTA-UL",
        "entity_name": "muvone",
        "entity_type": "Thing",
        "attributes": [{
            "object_id": "t",
            "name": "temperature",
            "type": "Float"
        }],
        "commands": [{
            "name":"blink",
            "type": "command",
            "value": "muvone@blink|%s"
        }],
        "static_attributes": []
    }]
}'
</code>```0

Now, having a look at Orion and IoTAgent logs, it can be seen that IoTAgent doesn't find the entity:

Orion logs to the request:

```<code>curl -X POST \
  http://MYIP:4041/iot/devices \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -H 'fiware-service: howtoService' \
  -H 'fiware-servicepath: /howto' \
  -d '{
    "devices": [{
        "device_id": "muvone",
        "protocol": "IoTA-UL",
        "entity_name": "muvone",
        "entity_type": "Thing",
        "attributes": [{
            "object_id": "t",
            "name": "temperature",
            "type": "Float"
        }],
        "commands": [{
            "name":"blink",
            "type": "command",
            "value": "muvone@blink|%s"
        }],
        "static_attributes": []
    }]
}'
</code>```1

IDAS log:

```<code>curl -X POST \
  http://MYIP:4041/iot/devices \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -H 'fiware-service: howtoService' \
  -H 'fiware-servicepath: /howto' \
  -d '{
    "devices": [{
        "device_id": "muvone",
        "protocol": "IoTA-UL",
        "entity_name": "muvone",
        "entity_type": "Thing",
        "attributes": [{
            "object_id": "t",
            "name": "temperature",
            "type": "Float"
        }],
        "commands": [{
            "name":"blink",
            "type": "command",
            "value": "muvone@blink|%s"
        }],
        "static_attributes": []
    }]
}'
</code>```2

In the mongo database, it can be seen that the registrations, entities and everything is set up correctly.

I have worked around this issue for days with no result.
Any help will be appreciated. Thanks in advance

UPDATE

After using the v1 of the Orion API, the result is the same that the given by v2:

```<code>curl -X POST \
  http://MYIP:1026/v1/updateContext \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -H 'fiware-service: howtoService' \
  -H 'fiware-servicepath: /howto' \
  -d '{
    "contextElements": [
        {
            "type": "Thing",
            "isPattern": "false",
            "id": "muvone",
            "attributes": [
                {
                    "name": "blink",
                    "type": "command",
                    "value": "true"
                }
            ]
        }
    ],
    "updateAction": "UPDATE"
} '
</code>```

Result:

```<code>{
  "errorCode": {
    "code": "404",
    "reasonPhrase": "No context element found"
  }
}
</code>```

2nd UPDATE
I have a service that sends the commands that I issue to the context broker. The difference is that if the command is defined in the device, it responses with the 404 error, but if it is not defined in the preprovision, it responds with the code 472:

Undefined command

```<code>curl -X POST \
  http://localhost:3000/api/devices/1111/sendCommand/update_firmware \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -d '{
    "value":"example value"
}'
</code>```

472:

```<code>{
  "contextResponses": [
    {
      "contextElement": {
        "type": "Thing",
        "isPattern": "false",
        "id": "muvone",
        "attributes": [
          {
            "name": "update_firmware",
            "type": "command",
            "value": ""
          }
        ]
      },
      "statusCode": {
        "code": "472",
        "reasonPhrase": "request parameter is invalid/not allowed",
        "details": "action: UPDATE - entity: [muvone, Thing] - offending attribute: update_firmware"
      }
    }
  ]
}
</code>```

Defined command:

```<code>curl -X POST \
  http://localhost:3000/api/devices/1111/sendCommand/blink \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -d '{
    "value":"asd"
}'
</code>```

404:

```<code>{
  "errorCode": {
    "code": "404",
    "reasonPhrase": "No context element found"
  }
}
</code>```

答:
I found the solution to this issue, and I think it must be considered as a bug. It was a problem with camelcases.
In my case, I was using the headers howtoService for the Fiware-service header, and in the database was stored correctly:

```<code>{ "_id" : ObjectId("5935316c4cfcb20001ec6181"), "polling" : true, "transport" : "HTTP", "protocol" : "IoTA-UL", "internalId" : null, "registrationId" : "5935316c5937ac933167d477", "subservice" : "/howto", "service" : "howtoService", "name" : "muvone", "type" : "Thing", "id" : "muvone", "creationDate" : ISODate("2017-06-05T10:24:44.336Z"), "subscriptions" : [ ], "staticAttributes" : [ ], "commands" : [ { "object_id" : "blink", "value" : "muvone@blink|%s", "type" : "command", "name" : "blink" } ], "active" : [ { "type" : "Float", "name" : "temperature", "object_id" : "ta" } ], "__v" : 0 }
</code>```

But, when the operation from the IOTAgent comes, it uses lowercase, resulting in a Not found operation from mongo filters:

```<code>{ "op" : "query", "ns" : "iotagentul.devices", "query" : { "find" : "devices", "filter" : { "subservice" : "/howto", "service" : "howtoservice", "name" : "muvone" }, "projection" : { "__v" : 0 }, "limit" : 1, "batchSize" : 1, "singleBatch" : true }, "keysExamined" : 0, "docsExamined" : 1, "cursorExhausted" : true, "keyUpdates" : 0, "writeConflicts" : 0, "numYield" : 0, "locks" : { "Global" : { "acquireCount" : { "r" : NumberLong(2) } }, "Database" : { "acquireCount" : { "r" : NumberLong(1) } }, "Collection" : { "acquireCount" : { "r" : NumberLong(1) } } }, "nreturned" : 0, "responseLength" : 124, "protocol" : "op_query", "millis" : 0, "execStats" : { "stage" : "LIMIT", "nReturned" : 0, "executionTimeMillisEstimate" : 0, "works" : 3, "advanced" : 0, "needTime" : 2, "needYield" : 0, "saveState" : 0, "restoreState" : 0, "isEOF" : 1, "invalidates" : 0, "limitAmount" : 1, "inputStage" : { "stage" : "PROJECTION", "nReturned" : 0, "executionTimeMillisEstimate" : 0, "works" : 3, "advanced" : 0, "needTime" : 2, "needYield" : 0, "saveState" : 0, "restoreState" : 0, "isEOF" : 1, "invalidates" : 0, "transformBy" : { "__v" : 0 }, "inputStage" : { "stage" : "COLLSCAN", "filter" : { "$and" : [ { "name" : { "$eq" : "muvone" } }, { "service" : { "$eq" : "howtoservice" } }, { "subservice" : { "$eq" : "/howto" } } ] }, "nReturned" : 0, "executionTimeMillisEstimate" : 0, "works" : 3, "advanced" : 0, "needTime" : 2, "needYield" : 0, "saveState" : 0, "restoreState" : 0, "isEOF" : 1, "invalidates" : 0, "direction" : "forward", "docsExamined" : 1 } } }, "ts" : ISODate("2017-06-05T10:40:37.401Z"), "client" : "172.17.0.4", "allUsers" : [ ], "user" : "" }
</code>```

After updating in database the howtoService to howtoservice, the command works properly

Body:
I am trying to send a command to a device using Orion + Ultralight 2.0.
The device is registered and I can send measures easily. I want to work in the pooling mode in order to execute commands, but when I execute the updateContext operation, IDAS doesn't found the entity. Here are the configuration and the logs:

Configuration:

var config = {};

config.mqtt = {
    host: 'mosquitto',
    port: 1883
};

config.http = {
    port: 7896
};

config.iota = {
    logLevel: 'DEBUG',
    timestamp: true,
    contextBroker: {
        host: 'MY_IP',
        port: '1026'
    },
    server: {
        port: 4041
    },
    deviceRegistry: {
        type: 'mongodb'
    },
    mongodb: {
        host: 'mongo',
        port: '27017',
        db: 'iotagentul'
    },
    types: {},
    service: 'howtoService',
    subservice: '/howto',
    providerUrl: 'http://YIP:4041',
    deviceRegistrationDuration: 'P1M',
    defaultType: 'Thing'
};

config.defaultKey = 'TEF';

module.exports = config;

I have tried different IP's and routes, and at the end i tried with the public IP, assuring that there is communication from the outside to those ports.

Device registration:

curl -X POST \
  http://MYIP:4041/iot/devices \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -H 'fiware-service: howtoService' \
  -H 'fiware-servicepath: /howto' \
  -d '{
    "devices": [{
        "device_id": "muvone",
        "protocol": "IoTA-UL",
        "entity_name": "muvone",
        "entity_type": "Thing",
        "attributes": [{
            "object_id": "t",
            "name": "temperature",
            "type": "Float"
        }],
        "commands": [{
            "name":"blink",
            "type": "command",
            "value": "muvone@blink|%s"
        }],
        "static_attributes": []
    }]
}'

Then I send some observations from a physical device and from POSTMAN:

curl -X POST \
  'http://MYIP:7896/iot/d?i=muvone&k=TEF&getCmd=1' \
  -H 'cache-control: no-cache' \
  -H 'fiware-service: howtoService' \
  -H 'fiware-servicepath: /howto' \
  -d 'temperature|16'

Which actually updates the entity correctly, as can be seen in Orion Context Broker:
Query:

curl -X GET \
  http://MYIP:1026/v2/entities \
  -H 'cache-control: no-cache' \
  -H 'fiware-service: howtoService' \
  -H 'fiware-servicepath: /howto' \

Response:

[
  {
    "id": "muvone",
    "type": "Thing",
    "TimeInstant": {
      "type": "ISO8601",
      "value": "2017-06-01T11:37:52.537Z",
      "metadata": {}
    },
    "blink_info": {
      "type": "commandResult",
      "value": " ",
      "metadata": {}
    },
    "blink_status": {
      "type": "commandStatus",
      "value": "UNKNOWN",
      "metadata": {}
    },
    "temperature": {
      "type": "Float",
      "value": "16",
      "metadata": {
        "TimeInstant": {
          "type": "ISO8601",
          "value": "2017-06-01T11:37:52.537Z"
        }
      }
    }
  }
]

So now, If I want to send a command, I have done it in a lot of ways. I tried following this guide:

http://fiware-iot-stack.readthedocs.io/en/master/topics/device_connection/index.html

So I tried to use the following request:

curl -X PUT \
  http://MYIP:1026/v2/entities \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -H 'fiware-service: howtoService' \
  -H 'fiware-servicepath: /howto' \
  -d '{
  "id": "muvone",
  "type": "Thing",
  "blink": {
    "type" : "command",
    "value" : "true"
  }
}'

Which response is:

{
  "error": "MethodNotAllowed",
  "description": "method not allowed"
}

So I tried updating a single attribute, in this case the blink attribute, which is a command. This should trigger that the Orion Context Broker acts as a NGSI proxy and passes the request to the IoTAgent, which occurs. But the problem is that the IoTAgent doesn't find the entity, as it can be seen in the logs:

curl -X PUT \
  'http://MYIP:1026/v2/entities/muvone/attrs/blink?type=Thing' \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -H 'fiware-service: howtoService' \
  -H 'fiware-servicepath: /howto' \
  -d '{
    "type": "command",
    "value": "true"
}'

or

curl -X PUT \
  'http://MYIP:1026/v2/entities/muvone/attrs/blink?type=Thing' \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -H 'fiware-service: howtoService' \
  -H 'fiware-servicepath: /howto' \
  -H 'postman-token: 6b42d06d-2a9f-3081-e315-bd9919aeded5' \
  -d '{
    "value": "true"
}'

Responds with:

{
  "error": "NotFound",
  "description": "The requested entity has not been found. Check type and id"
}

Edit: The get v2/entities to orion result, after issuing these requests is:

[
  {
    "id": "muvone",
    "type": "Thing",
    "TimeInstant": {
      "type": "ISO8601",
      "value": "2017-06-02T10:26:32.212Z",
      "metadata": {}
    },
    "blink_info": {
      "type": "commandResult",
      "value": " ",
      "metadata": {}
    },
    "blink_status": {
      "type": "commandStatus",
      "value": "UNKNOWN",
      "metadata": {}
    },
    "temperature": {
      "type": "Float",
      "value": "26",
      "metadata": {
        "TimeInstant": {
          "type": "ISO8601",
          "value": "2017-06-02T10:26:32.212Z"
        }
      }
    }
  }
]

Now, having a look at Orion and IoTAgent logs, it can be seen that IoTAgent doesn't find the entity:

Orion logs to the request:

time=Thursday 01 Jun 12:10:13 2017.880Z | lvl=INFO | corr=446f4532-46c3-11e7-b1a4-0242ac110003 | trans=1496315963-946-00000000039 | from=pending | srv=pending | subsrv=pending | comp=Orion | op=logMsg.h[1832]:lmTransactionStart | msg=Starting transaction from 91.126.73.210:2880/v2/entities/muvone/attrs/blink
time=Thursday 01 Jun 12:10:13 2017.880Z | lvl=INFO | corr=446f4532-46c3-11e7-b1a4-0242ac110003 | trans=1496315963-946-00000000039 | from=91.126.73.210 | srv=pending | subsrv=/howto | comp=Orion | op=rest.cpp[872]:servicePathSplit | msg=Service Path 0: '/howto'
time=Thursday 01 Jun 12:10:13 2017.881Z | lvl=INFO | corr=446f4532-46c3-11e7-b1a4-0242ac110003 | trans=1496315963-946-00000000039 | from=91.126.73.210 | srv=howtoservice | subsrv=/howto | comp=Orion | op=connectionOperations.cpp[237]:collectionCount | msg=Database Operation Successful (count: { _id.id: "muvone", _id.type: "Thing", _id.servicePath: { $in: [ /^/howto$/ ] } })
time=Thursday 01 Jun 12:10:13 2017.881Z | lvl=INFO | corr=446f4532-46c3-11e7-b1a4-0242ac110003 | trans=1496315963-946-00000000039 | from=91.126.73.210 | srv=howtoservice | subsrv=/howto | comp=Orion | op=connectionOperations.cpp[92]:collectionQuery | msg=Database Operation Successful (query: { _id.id: "muvone", _id.type: "Thing", _id.servicePath: { $in: [ /^/howto$/ ] } })
time=Thursday 01 Jun 12:10:13 2017.881Z | lvl=INFO | corr=446f4532-46c3-11e7-b1a4-0242ac110003 | trans=1496315963-946-00000000039 | from=91.126.73.210 | srv=howtoservice | subsrv=/howto | comp=Orion | op=connectionOperations.cpp[175]:collectionRangedQuery | msg=Database Operation Successful (query: { query: { $or: [ { contextRegistration.entities: { $in: [ { id: "muvone", type: "Thing" }, { type: "Thing", id: "muvone" } ] } }, { contextRegistration.entities.id: { $in: [] } } ], expiration: { $gt: 1496319013 }, contextRegistration.attrs.name: { $in: [ "blink" ] }, servicePath: { $in: [ /^/howto$/ ] } }, orderby: { _id: 1 } })
time=Thursday 01 Jun 12:10:13 2017.882Z | lvl=INFO | corr=446f4532-46c3-11e7-b1a4-0242ac110003 | trans=1496315963-946-00000000040 | from=pending | srv=pending | subsrv=pending | comp=Orion | op=logMsg.h[1832]:lmTransactionStart | msg=Starting transaction to http://MYIP:4041//updateContext
time=Thursday 01 Jun 12:10:13 2017.882Z | lvl=INFO | corr=446f4532-46c3-11e7-b1a4-0242ac110003 | trans=1496315963-946-00000000040 | from=pending | srv=pending | subsrv=pending | comp=Orion | op=httpRequestSend.cpp[577]:httpRequestSendWithCurl | msg=Sending message 14 to HTTP server: sending message of 558 bytes to HTTP server
time=Thursday 01 Jun 12:10:13 2017.886Z | lvl=INFO | corr=446f4532-46c3-11e7-b1a4-0242ac110003 | trans=1496315963-946-00000000040 | from=pending | srv=pending | subsrv=pending | comp=Orion | op=httpRequestSend.cpp[598]:httpRequestSendWithCurl | msg=Notification Successfully Sent to http://MYIP:4041//updateContext
time=Thursday 01 Jun 12:10:13 2017.886Z | lvl=INFO | corr=446f4532-46c3-11e7-b1a4-0242ac110003 | trans=1496315963-946-00000000040 | from=pending | srv=pending | subsrv=pending | comp=Orion | op=logMsg.h[1916]:lmTransactionEnd | msg=Transaction ended
time=Thursday 01 Jun 12:10:13 2017.886Z | lvl=WARN | corr=N/A | trans=N/A | from=N/A | srv=N/A | subsrv=N/A | comp=Orion | op=postUpdateContext.cpp[225]:updateForward | msg=Internal Error (error parsing reply from prov app: )
time=Thursday 01 Jun 12:10:13 2017.886Z | lvl=INFO | corr=N/A | trans=N/A | from=N/A | srv=N/A | subsrv=N/A | comp=Orion | op=logMsg.h[1916]:lmTransactionEnd | msg=Transaction ended

IDAS log:

time=2017-06-01T12:10:13.882Z | lvl=DEBUG | corr=446f4532-46c3-11e7-b1a4-0242ac110003 | trans=8dcc19e7-e3ce-472a-a1bb-c7983dad7025 | op=IoTAgentNGSI.GenericMiddlewares | srv=howtoservice | subsrv=/howto | msg=Request for path [//updateContext] from [MYIP:4041] | comp=IoTAgent
time=2017-06-01T12:10:13.882Z | lvl=DEBUG | corr=446f4532-46c3-11e7-b1a4-0242ac110003 | trans=8dcc19e7-e3ce-472a-a1bb-c7983dad7025 | op=IoTAgentNGSI.GenericMiddlewares | srv=howtoservice | subsrv=/howto | msg=Body:

{
    "contextElements": [
        {
            "type": "Thing",
            "isPattern": "false",
            "id": "muvone",
            "attributes": [
                {
                    "name": "blink",
                    "type": "command",
                    "value": "true"
                }
            ]
        }
    ],
    "updateAction": "UPDATE"
}

 | comp=IoTAgent
time=2017-06-01T12:10:13.883Z | lvl=DEBUG | corr=446f4532-46c3-11e7-b1a4-0242ac110003 | trans=8dcc19e7-e3ce-472a-a1bb-c7983dad7025 | op=IoTAgentNGSI.ContextServer | srv=howtoservice | subsrv=/howto | msg=Handling update from [MYIP:4041] | comp=IoTAgent
time=2017-06-01T12:10:13.883Z | lvl=DEBUG | corr=446f4532-46c3-11e7-b1a4-0242ac110003 | trans=8dcc19e7-e3ce-472a-a1bb-c7983dad7025 | op=IoTAgentNGSI.ContextServer | srv=howtoservice | subsrv=/howto | msg=[object Object] | comp=IoTAgent
time=2017-06-01T12:10:13.883Z | lvl=DEBUG | corr=446f4532-46c3-11e7-b1a4-0242ac110003 | trans=8dcc19e7-e3ce-472a-a1bb-c7983dad7025 | op=IoTAgentNGSI.MongoDBDeviceRegister | srv=howtoservice | subsrv=/howto | msg=Looking for entity with name [muvone]. | comp=IoTAgent
time=2017-06-01T12:10:13.883Z | lvl=DEBUG | corr=446f4532-46c3-11e7-b1a4-0242ac110003 | trans=8dcc19e7-e3ce-472a-a1bb-c7983dad7025 | op=IoTAgentNGSI.MongoDBDeviceRegister | srv=howtoservice | subsrv=/howto | msg=Entity [muvone] not found. | comp=IoTAgent
time=2017-06-01T12:10:13.884Z | lvl=DEBUG | corr=446f4532-46c3-11e7-b1a4-0242ac110003 | trans=8dcc19e7-e3ce-472a-a1bb-c7983dad7025 | op=IoTAgentNGSI.ContextServer | srv=howtoservice | subsrv=/howto | msg=There was an error handling the update action: [object Object]. | comp=IoTAgent
time=2017-06-01T12:10:13.884Z | lvl=DEBUG | corr=446f4532-46c3-11e7-b1a4-0242ac110003 | trans=8dcc19e7-e3ce-472a-a1bb-c7983dad7025 | op=IoTAgentNGSI.ContextServer | srv=howtoservice | subsrv=/howto | msg=Update error [ENTITY_NOT_FOUND] handing request: The entity with the requested id [muvone] was not found. | comp=IoTAgent
time=2017-06-01T12:10:13.884Z | lvl=DEBUG | corr=446f4532-46c3-11e7-b1a4-0242ac110003 | trans=8dcc19e7-e3ce-472a-a1bb-c7983dad7025 | op=IoTAgentNGSI.DomainControl | srv=howtoservice | subsrv=/howto | msg=response-time: 2 | comp=IoTAgent

In the mongo database, it can be seen that the registrations, entities and everything is set up correctly.

I have worked around this issue for days with no result.
Any help will be appreciated. Thanks in advance

UPDATE

After using the v1 of the Orion API, the result is the same that the given by v2:

curl -X POST \
  http://MYIP:1026/v1/updateContext \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -H 'fiware-service: howtoService' \
  -H 'fiware-servicepath: /howto' \
  -d '{
    "contextElements": [
        {
            "type": "Thing",
            "isPattern": "false",
            "id": "muvone",
            "attributes": [
                {
                    "name": "blink",
                    "type": "command",
                    "value": "true"
                }
            ]
        }
    ],
    "updateAction": "UPDATE"
} '

Result:

{
  "errorCode": {
    "code": "404",
    "reasonPhrase": "No context element found"
  }
}

2nd UPDATE
I have a service that sends the commands that I issue to the context broker. The difference is that if the command is defined in the device, it responses with the 404 error, but if it is not defined in the preprovision, it responds with the code 472:

Undefined command

curl -X POST \
  http://localhost:3000/api/devices/1111/sendCommand/update_firmware \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -d '{
    "value":"example value"
}'

472:

{
  "contextResponses": [
    {
      "contextElement": {
        "type": "Thing",
        "isPattern": "false",
        "id": "muvone",
        "attributes": [
          {
            "name": "update_firmware",
            "type": "command",
            "value": ""
          }
        ]
      },
      "statusCode": {
        "code": "472",
        "reasonPhrase": "request parameter is invalid/not allowed",
        "details": "action: UPDATE - entity: [muvone, Thing] - offending attribute: update_firmware"
      }
    }
  ]
}

Defined command:

curl -X POST \
  http://localhost:3000/api/devices/1111/sendCommand/blink \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -d '{
    "value":"asd"
}'

404:

{
  "errorCode": {
    "code": "404",
    "reasonPhrase": "No context element found"
  }
}

Body:
I found the solution to this issue, and I think it must be considered as a bug. It was a problem with camelcases.
In my case, I was using the headers howtoService for the Fiware-service header, and in the database was stored correctly:

{ "_id" : ObjectId("5935316c4cfcb20001ec6181"), "polling" : true, "transport" : "HTTP", "protocol" : "IoTA-UL", "internalId" : null, "registrationId" : "5935316c5937ac933167d477", "subservice" : "/howto", "service" : "howtoService", "name" : "muvone", "type" : "Thing", "id" : "muvone", "creationDate" : ISODate("2017-06-05T10:24:44.336Z"), "subscriptions" : [ ], "staticAttributes" : [ ], "commands" : [ { "object_id" : "blink", "value" : "muvone@blink|%s", "type" : "command", "name" : "blink" } ], "active" : [ { "type" : "Float", "name" : "temperature", "object_id" : "ta" } ], "__v" : 0 }

But, when the operation from the IOTAgent comes, it uses lowercase, resulting in a Not found operation from mongo filters:

{ "op" : "query", "ns" : "iotagentul.devices", "query" : { "find" : "devices", "filter" : { "subservice" : "/howto", "service" : "howtoservice", "name" : "muvone" }, "projection" : { "__v" : 0 }, "limit" : 1, "batchSize" : 1, "singleBatch" : true }, "keysExamined" : 0, "docsExamined" : 1, "cursorExhausted" : true, "keyUpdates" : 0, "writeConflicts" : 0, "numYield" : 0, "locks" : { "Global" : { "acquireCount" : { "r" : NumberLong(2) } }, "Database" : { "acquireCount" : { "r" : NumberLong(1) } }, "Collection" : { "acquireCount" : { "r" : NumberLong(1) } } }, "nreturned" : 0, "responseLength" : 124, "protocol" : "op_query", "millis" : 0, "execStats" : { "stage" : "LIMIT", "nReturned" : 0, "executionTimeMillisEstimate" : 0, "works" : 3, "advanced" : 0, "needTime" : 2, "needYield" : 0, "saveState" : 0, "restoreState" : 0, "isEOF" : 1, "invalidates" : 0, "limitAmount" : 1, "inputStage" : { "stage" : "PROJECTION", "nReturned" : 0, "executionTimeMillisEstimate" : 0, "works" : 3, "advanced" : 0, "needTime" : 2, "needYield" : 0, "saveState" : 0, "restoreState" : 0, "isEOF" : 1, "invalidates" : 0, "transformBy" : { "__v" : 0 }, "inputStage" : { "stage" : "COLLSCAN", "filter" : { "$and" : [ { "name" : { "$eq" : "muvone" } }, { "service" : { "$eq" : "howtoservice" } }, { "subservice" : { "$eq" : "/howto" } } ] }, "nReturned" : 0, "executionTimeMillisEstimate" : 0, "works" : 3, "advanced" : 0, "needTime" : 2, "needYield" : 0, "saveState" : 0, "restoreState" : 0, "isEOF" : 1, "invalidates" : 0, "direction" : "forward", "docsExamined" : 1 } } }, "ts" : ISODate("2017-06-05T10:40:37.401Z"), "client" : "172.17.0.4", "allUsers" : [ ], "user" : "" }

After updating in database the howtoService to howtoservice, the command works properly


问:
Create index list for np.split from the list that already has number for each section
I have two lists of numbers

```<code>list = [1,2,3,4,5,6,7,8,9]
number = [3,2,1,3]
</code>```

I want to create index for np.split from number

```<code>index = [3,5,6,9]
</code>```

for

```<code>np.split(list, index)
</code>```

Expected outcome

```<code>[[1,2,3],[4,5],[6],[7,8,9]]
</code>```

I tried something like newlist = [x+number[0:index(x)] for x in list] but it still does not work

答:
Approach #1

If we want to use np.split resulting in a list of arrays, we need to use np.cumsum on those indexes to give us indices where we need to split the input list -

```<code>np.split(list1, np.cumsum(number)[:-1])
</code>```

Sample run -

```<code>In [36]: list1 = [1,2,3,4,5,6,7,8,9]
    ...: number = [3,2,1,3]
    ...:

In [37]: np.split(list1, np.cumsum(number)[:-1])
Out[37]: [array([1, 2, 3]), array([4, 5]), array([6]), array([7, 8, 9])]
</code>```

Approach #2

To have a list of lists, another approach with a loop comprehension again using cumsum -

```<code>idx = np.r_[0,np.cumsum(number)]
out = [list1[idx[i]:idx[i+1]] for i in range(len(idx)-1)]
</code>```

Sample run -

```<code>In [45]: idx = np.r_[0,np.cumsum(number)]

In [46]: [list1[idx[i]:idx[i+1]] for i in range(len(idx)-1)]
Out[46]: [[1, 2, 3], [4, 5], [6], [7, 8, 9]]
</code>```

Body:
I have two lists of numbers

list = [1,2,3,4,5,6,7,8,9]
number = [3,2,1,3]

I want to create index for np.split from number

index = [3,5,6,9]

for

np.split(list, index)

Expected outcome

[[1,2,3],[4,5],[6],[7,8,9]]

I tried something like newlist = [x+number[0:index(x)] for x in list] but it still does not work

Body:
Approach #1

If we want to use np.split resulting in a list of arrays, we need to use np.cumsum on those indexes to give us indices where we need to split the input list -

np.split(list1, np.cumsum(number)[:-1])

Sample run -

In [36]: list1 = [1,2,3,4,5,6,7,8,9]
    ...: number = [3,2,1,3]
    ...:

In [37]: np.split(list1, np.cumsum(number)[:-1])
Out[37]: [array([1, 2, 3]), array([4, 5]), array([6]), array([7, 8, 9])]

Approach #2

To have a list of lists, another approach with a loop comprehension again using cumsum -

idx = np.r_[0,np.cumsum(number)]
out = [list1[idx[i]:idx[i+1]] for i in range(len(idx)-1)]

Sample run -

In [45]: idx = np.r_[0,np.cumsum(number)]

In [46]: [list1[idx[i]:idx[i+1]] for i in range(len(idx)-1)]
Out[46]: [[1, 2, 3], [4, 5], [6], [7, 8, 9]]


问:
How to save google-services.json file
I'm trying to connect my app to firebase. What do I need to do to save the google-services.json file? My computer automatically download it to text file (I uploaded the pic of the download). How to open and download it?

答:
The google-services.json file is indeed a text file. But you don't need to open or read it. All you have to do is drag it from explorer/finder into the app folder of your app in Android Studio. From there on, the Android app will automatically find the file when it builds the app.

If you're having problems with this, you might be better served by using the Firebase Assistant that is built into Android Studio. Go to the Tools menu and then click Firebase.

Title: How to save google-services.json file


问:
Python: Regex help
```<code>str = "a\b\c\dsdf\matchthis\erwe.txt"
</code>```

The last folder name.

Match "matchthis"

答:
Better to use os.path.split(path) since it's platform independent.  You'll have to call it twice to get the final directory:

```<code>path_file = "a\b\c\dsdf\matchthis\erwe.txt"
path, file = os.path.split(path_file)
path, dir = os.path.split(path)
</code>```

Title: Python: Regex help

Body:
str = "a\b\c\dsdf\matchthis\erwe.txt"

The last folder name.

Match "matchthis"

Body:
Better to use os.path.split(path) since it's platform independent.  You'll have to call it twice to get the final directory:

path_file = "a\b\c\dsdf\matchthis\erwe.txt"
path, file = os.path.split(path_file)
path, dir = os.path.split(path)


问:
How to parse array of JSON in Swift 3
I am getting some data from Socket which I would like to access but I am getting error saying can't convert NSArray to NSDictionary each time.

```<code>struct SocketEventHandler {
    let event: String
    let id: UUID
    let callback: NormalCallback

    func executeCallback(with items: [Any], withAck ack: Int, withSocket socket: SocketIOClient) {
        callback(items, SocketAckEmitter(socket: socket, ackNum: ack))
    }
}

let onFriendRequestStatus: NormalCallback = {dataArray,socketAck in
        AppLog.debug(tag: TAG, msg: "Response: \(dataArray)")
        AppLog.debug(tag: TAG, msg: "Response: \(dataArray[0])")
        let response  = dataArray[0] as! Dictionary<String, Any> **// APP CRASHES ON THIS LINE**
}
</code>```

Response :-

```<code>[
    {
        "status": "A",
        "acceptorId": 126,
        "id": 94,
        "createdAt": "2017-06-05T09:50:42.000Z",
        "updatedAt": "2017-06-05T09:52:26.000Z",
        "userId": 126,
        "friendId": 401
    }
]
</code>```

Error - Could not cast value of type '__NSArrayM' (0x102f0de00) to 'NSDictionary' (0x102f0e2d8).

答:
Make a breakpoint on sentence crashes, and then use following command to check what exactly the dataArray is:

```<code>po print(dataArray)
</code>```

Title: How to parse array of JSON in Swift 3

Body:
I am getting some data from Socket which I would like to access but I am getting error saying can't convert NSArray to NSDictionary each time.

struct SocketEventHandler {
    let event: String
    let id: UUID
    let callback: NormalCallback

    func executeCallback(with items: [Any], withAck ack: Int, withSocket socket: SocketIOClient) {
        callback(items, SocketAckEmitter(socket: socket, ackNum: ack))
    }
}

let onFriendRequestStatus: NormalCallback = {dataArray,socketAck in
        AppLog.debug(tag: TAG, msg: "Response: \(dataArray)")
        AppLog.debug(tag: TAG, msg: "Response: \(dataArray[0])")
        let response  = dataArray[0] as! Dictionary<String, Any> **// APP CRASHES ON THIS LINE**
}

Response :-

[
    {
        "status": "A",
        "acceptorId": 126,
        "id": 94,
        "createdAt": "2017-06-05T09:50:42.000Z",
        "updatedAt": "2017-06-05T09:52:26.000Z",
        "userId": 126,
        "friendId": 401
    }
]

Error - Could not cast value of type '__NSArrayM' (0x102f0de00) to 'NSDictionary' (0x102f0e2d8).

Body:
Make a breakpoint on sentence crashes, and then use following command to check what exactly the dataArray is:

po print(dataArray)


问:
How do you correctly handle redirection in FOR loop in one line of command?
I want to output the file cat.txt's content and save them in another text file using FOR /F loop ( in one line of command of standard cmd shell.)

for example, here is the source file.

```<code># content of cat.txt:
meow
meo
me
m
</code>```

after use this command, I've got some unintended result:

FOR /F "tokens=*" %G in (cat.txt) DO echo %G > D:\copy-cat.txt

```<code># I got output:
meow > D:\copy-cat.txt
meo > D:\copy-cat.txt
me > D:\copy-cat.txt
m > D:\copy-cat.txt
</code>```

I understand in this scenario, the redirection is being affected by echo, hence recognized as string and echoed out.

Question: How do I semantically separate the code so that I can redirect all the content that were written to stdout into D:\copy-cat.txt?

Note: as you can see by %G, I need to write this directly in commandline, not in a batch script.

答:
>copy-cat.txt (FOR /F "delims=" %G in (cat.txt) DO @echo %G)
```

Instead of redirecting each output line, redirect the full for output

To avoid the inclusion of the echo command itself, use prefix the command with @ to not echo the echo (single command echo off)

Body:
I want to output the file cat.txt's content and save them in another text file using FOR /F loop ( in one line of command of standard cmd shell.)

for example, here is the source file.

# content of cat.txt:
meow
meo
me
m

after use this command, I've got some unintended result:

FOR /F "tokens=*" %G in (cat.txt) DO echo %G > D:\copy-cat.txt

# I got output:
meow > D:\copy-cat.txt
meo > D:\copy-cat.txt
me > D:\copy-cat.txt
m > D:\copy-cat.txt

I understand in this scenario, the redirection is being affected by echo, hence recognized as string and echoed out.

Question: How do I semantically separate the code so that I can redirect all the content that were written to stdout into D:\copy-cat.txt?

Note: as you can see by %G, I need to write this directly in commandline, not in a batch script.

Body:
>copy-cat.txt (FOR /F "delims=" %G in (cat.txt) DO @echo %G)

Instead of redirecting each output line, redirect the full for output

To avoid the inclusion of the echo command itself, use prefix the command with @ to not echo the echo (single command echo off)


问:
catalog is missing error on pg_dump postgresql 9.5
I can't dumb the database in postgresql 9.5. The issue is only in 1 database and when we selecting the data from a view. It shows the catalog is missing 128 attribute(s). Is there any solution for this? There is no problem in table for select,Insert and delete operations. I can't update the VIEWS or remove them. Please help me for removing the views for solving the issues.</p>

答:
You have a corrupted database.

Try to find out what table is affected:

```<code>SELECT 183772::regclass;
</code>```

Can you get a description of this table? How many columns should it have?

The error message is thrown if the number of attributes in the pg_class catalog does not correspond to the actual number of attributes in pg_attribute. These two queries should return the same value, but in your case the first will return 128 more than the second:

```<code>SELECT relnatts FROM pg_class
   WHERE oid = 183772;

SELECT count(*) FROM pg_attribute
   WHERE attrelid = 183772 AND attnum > 0;
</code>```

I would restore from a backup.

Investigate which number of columns is correct.

Since the difference is exactly 128, perhaps a bit flipped in RAM. Do you have fault tolerant RAM? If not, maybe now you have an incentive to get some.

Check your hardware, especially your memory, for faults!

Get your oldest backup and see how things are there.

If it is really only one bit that flipped and the number from pg_class is off by 128, you could update relnatts for table 183772, and your problem would be fixed.

Body:
You have a corrupted database.

Try to find out what table is affected:

SELECT 183772::regclass;

Can you get a description of this table? How many columns should it have?

The error message is thrown if the number of attributes in the pg_class catalog does not correspond to the actual number of attributes in pg_attribute. These two queries should return the same value, but in your case the first will return 128 more than the second:

SELECT relnatts FROM pg_class
   WHERE oid = 183772;

SELECT count(*) FROM pg_attribute
   WHERE attrelid = 183772 AND attnum > 0;

I would restore from a backup.

Investigate which number of columns is correct.

Since the difference is exactly 128, perhaps a bit flipped in RAM. Do you have fault tolerant RAM? If not, maybe now you have an incentive to get some.

Check your hardware, especially your memory, for faults!

Get your oldest backup and see how things are there.

If it is really only one bit that flipped and the number from pg_class is off by 128, you could update relnatts for table 183772, and your problem would be fixed.


问:
Android dotted underline is staying in middle of textview
I want to show a dotted underline below the textview, following are my codes

```<code><TextView
  android:id="@+id/contact_num"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:paddingTop="4dp"
  android:text="1234567890"
  android:background="@drawable/dashed_line"
  android:layerType="software"
  android:textSize="20dp" />
</code>```

dashed_line.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line">

    <stroke
        android:color="@color/oceanBlue"
        android:dashWidth="2dp"
        android:dashGap="3dp"
        android:width="1dp"/>
</shape>
</code>```

and the textview looks as above

can anyone help me to get the dotted line below to the textview?

tried with drawableBottom also but no use

```<code>android:drawableBottom="@drawable/dashed_line"
</code>```

答:
```<code><TextView .....
    ..........
>
<ImageView
    android:layout_width="match_parent"
    android:layout_height="5dp"
    android:layerType="software"
    android:src="@drawable/dotted_line" />
</code>```

dotted_line.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line">
    <stroke
        android:width="1dp"
        android:color="@color/colorAccent"
        android:dashGap="15px"
        android:dashWidth="15dp" />
</shape>
</code>```

Body:
I want to show a dotted underline below the textview, following are my codes

<TextView
  android:id="@+id/contact_num"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:paddingTop="4dp"
  android:text="1234567890"
  android:background="@drawable/dashed_line"
  android:layerType="software"
  android:textSize="20dp" />

dashed_line.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line">

    <stroke
        android:color="@color/oceanBlue"
        android:dashWidth="2dp"
        android:dashGap="3dp"
        android:width="1dp"/>
</shape>

and the textview looks as above

can anyone help me to get the dotted line below to the textview?

tried with drawableBottom also but no use

android:drawableBottom="@drawable/dashed_line"

Body:
<TextView .....
    ..........
>
<ImageView
    android:layout_width="match_parent"
    android:layout_height="5dp"
    android:layerType="software"
    android:src="@drawable/dotted_line" />

dotted_line.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line">
    <stroke
        android:width="1dp"
        android:color="@color/colorAccent"
        android:dashGap="15px"
        android:dashWidth="15dp" />
</shape>


问:
Why doesn't IN operator work on the result returned by subquery ?
Why doesn't operator work i.e. returns nothing?

```<code>Select * from complaints where Code
IN
(select
   distinct
    stuff((
        select ',' + QUOTENAME(cs.Code,'''')
        from MC_Complaints.dbo.Complaints cs where cs.OverDue= 1
        order by cs.Code asc
        for xml path('')
    ),1,1,'') as codeslist
from MC_Complaints.dbo.Complaints cs)
</code>```

This query

```<code>select
   distinct
    stuff((
        select ',' + QUOTENAME(cs.Code,'''')
        from MC_Complaints.dbo.Complaints cs where cs.OverDue= 1
        order by cs.Code asc
        for xml path('')
    ),1,1,'') as codeslist
from MC_Complaints.dbo.Complaints cs
</code>```

returns

```<code>'LG/17/05/0','LG/17/05/2','LG/17/05/3','Local Council Board/17/05/1','Local Council Board/17/05/10','Local Council Board/17/05/11'
</code>```

but IN doesn't pick any record but when I put these codes in IN operator i.e.

```<code>Select * from complaints where Code in
(
    'LG/17/05/0','LG/17/05/2','LG/17/05/3','Local Council Board/17/05/1','Local Council Board/17/05/10','Local Council Board/17/05/11'
)
</code>```

then it works surprisingly but not when returned but the subquery. Why ?

答:
The result from the stuff() is a string.  Just because the string happens to contain commas does not mean that it is a list of values.  The string 'A,B,C' is quite different from the list 'A', 'B', 'C'.

The good news is that this can greatly simplify your logic:

```<code>Select c.*
from complaints c
where c.code in (select cs.Code
                 from MC_Complaints.dbo.Complaints cs
                 where cs.OverDue = 1
                );
</code>```

Two more points.  First, your in expression is followed by a column alias (codelist).  That is not permitted syntax.

Second, the relevant comparison would be:

```<code>where cCode in (
    '''LG/17/05/0'',''LG/17/05/2'',''LG/17/05/3'',''Local Council Board/17/05/1'',''Local Council Board/17/05/10'',''Local Council Board/17/05/11'''
      )
</code>```

That is an in list that has a single string value.

Body:
Why doesn't operator work i.e. returns nothing?

Select * from complaints where Code
IN
(select
   distinct
    stuff((
        select ',' + QUOTENAME(cs.Code,'''')
        from MC_Complaints.dbo.Complaints cs where cs.OverDue= 1
        order by cs.Code asc
        for xml path('')
    ),1,1,'') as codeslist
from MC_Complaints.dbo.Complaints cs)

This query

select
   distinct
    stuff((
        select ',' + QUOTENAME(cs.Code,'''')
        from MC_Complaints.dbo.Complaints cs where cs.OverDue= 1
        order by cs.Code asc
        for xml path('')
    ),1,1,'') as codeslist
from MC_Complaints.dbo.Complaints cs

returns

'LG/17/05/0','LG/17/05/2','LG/17/05/3','Local Council Board/17/05/1','Local Council Board/17/05/10','Local Council Board/17/05/11'

but IN doesn't pick any record but when I put these codes in IN operator i.e.

Select * from complaints where Code in
(
    'LG/17/05/0','LG/17/05/2','LG/17/05/3','Local Council Board/17/05/1','Local Council Board/17/05/10','Local Council Board/17/05/11'
)

then it works surprisingly but not when returned but the subquery. Why ?

Body:
The result from the stuff() is a string.  Just because the string happens to contain commas does not mean that it is a list of values.  The string 'A,B,C' is quite different from the list 'A', 'B', 'C'.

The good news is that this can greatly simplify your logic:

Select c.*
from complaints c
where c.code in (select cs.Code
                 from MC_Complaints.dbo.Complaints cs
                 where cs.OverDue = 1
                );

Two more points.  First, your in expression is followed by a column alias (codelist).  That is not permitted syntax.

Second, the relevant comparison would be:

where cCode in (
    '''LG/17/05/0'',''LG/17/05/2'',''LG/17/05/3'',''Local Council Board/17/05/1'',''Local Council Board/17/05/10'',''Local Council Board/17/05/11'''
      )

That is an in list that has a single string value.


问:
Using python and matplotlib on android
Is there a way to set up python 2.7.x + matplotlib on an android tablet so that you can run simple standard python code? I would like to be able to run the same scripts I run on my Linux desktop. This is just for my own use and I don't need to distribute the code to anyone else.

As a concrete example, is it possible to run this script?

```<code>import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 5, 0.1);
y = np.sin(x)
plt.plot(x, y)
</code>```

答:
<s> Upon searching numpy android on Google, I found a very nice library. I guess it might be helpful. </s>

The above link no longer works. Please find more information regarding the library here.

Title: Using python and matplotlib on android

Body:
Is there a way to set up python 2.7.x + matplotlib on an android tablet so that you can run simple standard python code? I would like to be able to run the same scripts I run on my Linux desktop. This is just for my own use and I don't need to distribute the code to anyone else.

As a concrete example, is it possible to run this script?

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 5, 0.1);
y = np.sin(x)
plt.plot(x, y)

ContentLicense: CC BY-SA 4.0


问:
react-native modify index.android.js no change
When I first init a react-native project ,I can see new app running in my Android emulator.But when open "index.android.js" in my text editor of choice and edit some lines, select Reload from the Developer Menu .But i can't see any change.When I shut up the server and restart it ,I can see the change.
why?</p>

答:
The Same issue was coming in my project because server was shut down.
 so do not shut down your server while you are making some changes.if you shut down the server again use this command to rebuild and run: cd android && gradlew and then

```<code>cd .. && react-native run-android
</code>```

Body:
The Same issue was coming in my project because server was shut down.
 so do not shut down your server while you are making some changes.if you shut down the server again use this command to rebuild and run: cd android && gradlew and then

cd .. && react-native run-android


问:
CSS Resizing failure when browser window is scaled vertically
I am trying to create a simple login page, and after learning about CSS3 flexbox some time ago I redid the page using this new concept. So now, my page looks like this:

which is what I wanted...until I tried to resize the browser. Then, I got this (when I simply decreased the height of the browser window without decreasing the width):

and this (when I decreased both the height and the width of the browser window to a minimum):

This confused me since I read on other stackoverflow answers that I do not have to have media queries yet to create a responsive web design (which I do intend to do, later on), but just CSS by specifying the max-width in terms of percentages.

Here's my code:

HTML:

```<code><div class="center">
    <!-- Logo -->
    <img id="logo" src="assets/logowshadow.png" alt="cueclick logo">

    <!-- Login element -->
    <form class="login" action="/action_page.js" method="post">
        <p>Enter <i>your</i> secret key</p>
        <div id="password">
            <img id ="eye" src="assets/eye2.png" alt="eye">
            <input type="password" name="secret-key" placeholder="ilovecueclick" autofocus autocomplete="off"/>
        </div>
    </form>
</div>
</code>```

CSS:

```<code>/* -- Background image -- */
body {
    background-image: url(assets/wood.png);
    background-repeat: no-repeat;
    background-size: cover;
    background-attachment: fixed;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

/* -- Center element -- */
.center {
    max-width: 60%;
    max-height: 80%;
    width: 30%;
    height: 40%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: rgba(255, 255, 255, 0.7);
    border-radius: 15%;
    box-shadow: 2px 2px 4px 3px #505050;
    position: absolute;
    z-index: 1;
}

/* -- Logo style -- */
#logo {
    position: relative;
    z-index: 2;
    max-width: 100%;
    height: auto;
}

/* -- Form styles -- */
form.login {
    max-width: 100%;
    height: auto;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    position: relative;
    z-index: 2;
}

#password {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-bottom: 5%;
}

/* -- Show password -- */
#eye {
    height: auto;
    max-width: 15%;
    margin-right: 3%;
}

/* -- Login element -- */
form.login p {
    font-family: Palatino, "Palatino Linotype", "Palatino LT STD", "Book Antiqua", Georgia, serif;
    font-size: 2vw;
    max-width: 100%;
    height: auto;
    line-height: 2%;
}

form.login input[type=password] {
    max-width: 100%;
    width: 100%;
    height: auto;
}
</code>```

To explain what this code is doing further:
- body has a full-size background image that scales with the browser window
- 'center' is essentially the translucent white rectangle above the background
- the logo and the form log-in elements overlap the white rectangle

I have also created three flex containers for their flex items (to deal with the troublesome issue of centering):
1) body is the flex container, and the flex item is the center element
2) center is the flex container, and the logo and the form input section (ie. the paragraph + eye + input field) are the flex items
3) the 'password' div is the flex container (in-line), and the eye and login field are the flex items

I am really unsure where the issue lies, since there seems to be some scaling achieved with the current code...

The full HTML can be found here: https://pastebin.com/6tS6SXi3, and the full CSS can be found here: https://pastebin.com/6M11HnJE

Thanks in advance!

EDIT:

After experimenting further, it turns out that I simply had to let the height of the center class be auto...

Accepted the answer for its simplicity even though it does not use flex-box like I would have wanted it to

答:
Start from Mobile up..

Something like this (obliviously adjust the 100% to what you desire)

Work from mobile to desktop and I thinki you will  find you situation easier to deal with that way..

This resizes fine for me..

```<code>@media (max-width:768px){
    .center {
    max-width: 100%;
    max-height: 100%;
    width: 100%;
    height: 100%;
    }

/* -- Logo style -- */
#logo {
    max-width: 100%;
    height: auto;
}

/* -- Form styles -- */
form.login {
    max-width: 100%;

}

#password {
max-width:100%
}

/* -- Show password -- */
#eye {
    max-width: 100%;
}

/* -- Login element -- */
form.login p {
    max-width: 100%;
    height: auto;
}

form.login input[type=password] {
    max-width: 100%;
    width: 100%;
    height: auto;
}

}
</code>```

Body:
I am trying to create a simple login page, and after learning about CSS3 flexbox some time ago I redid the page using this new concept. So now, my page looks like this:

which is what I wanted...until I tried to resize the browser. Then, I got this (when I simply decreased the height of the browser window without decreasing the width):

and this (when I decreased both the height and the width of the browser window to a minimum):

This confused me since I read on other stackoverflow answers that I do not have to have media queries yet to create a responsive web design (which I do intend to do, later on), but just CSS by specifying the max-width in terms of percentages.

Here's my code:

HTML:

    <form class="login" action="/action_page.js" method="post">

Enter your secret key

            <input type="password" name="secret-key" placeholder="ilovecueclick" autofocus autocomplete="off"/>

    </form>

CSS:

/* -- Background image -- */
body {
    background-image: url(assets/wood.png);
    background-repeat: no-repeat;
    background-size: cover;
    background-attachment: fixed;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

/* -- Center element -- */
.center {
    max-width: 60%;
    max-height: 80%;
    width: 30%;
    height: 40%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: rgba(255, 255, 255, 0.7);
    border-radius: 15%;
    box-shadow: 2px 2px 4px 3px #505050;
    position: absolute;
    z-index: 1;
}

/* -- Logo style -- */
#logo {
    position: relative;
    z-index: 2;
    max-width: 100%;
    height: auto;
}

/* -- Form styles -- */
form.login {
    max-width: 100%;
    height: auto;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    position: relative;
    z-index: 2;
}

#password {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-bottom: 5%;
}

/* -- Show password -- */
#eye {
    height: auto;
    max-width: 15%;
    margin-right: 3%;
}

/* -- Login element -- */
form.login p {
    font-family: Palatino, "Palatino Linotype", "Palatino LT STD", "Book Antiqua", Georgia, serif;
    font-size: 2vw;
    max-width: 100%;
    height: auto;
    line-height: 2%;
}

form.login input[type=password] {
    max-width: 100%;
    width: 100%;
    height: auto;
}

To explain what this code is doing further:
- body has a full-size background image that scales with the browser window
- 'center' is essentially the translucent white rectangle above the background
- the logo and the form log-in elements overlap the white rectangle

I have also created three flex containers for their flex items (to deal with the troublesome issue of centering):
1) body is the flex container, and the flex item is the center element
2) center is the flex container, and the logo and the form input section (ie. the paragraph + eye + input field) are the flex items
3) the 'password' div is the flex container (in-line), and the eye and login field are the flex items

I am really unsure where the issue lies, since there seems to be some scaling achieved with the current code...

The full HTML can be found here: https://pastebin.com/6tS6SXi3, and the full CSS can be found here: https://pastebin.com/6M11HnJE

Thanks in advance!

EDIT:

After experimenting further, it turns out that I simply had to let the height of the center class be auto...

Accepted the answer for its simplicity even though it does not use flex-box like I would have wanted it to

Body:
Start from Mobile up..

Something like this (obliviously adjust the 100% to what you desire)

Work from mobile to desktop and I thinki you will  find you situation easier to deal with that way..

This resizes fine for me..

@media (max-width:768px){
    .center {
    max-width: 100%;
    max-height: 100%;
    width: 100%;
    height: 100%;
    }

/* -- Logo style -- */
#logo {
    max-width: 100%;
    height: auto;
}

/* -- Form styles -- */
form.login {
    max-width: 100%;

}

#password {
max-width:100%
}

/* -- Show password -- */
#eye {
    max-width: 100%;
}

/* -- Login element -- */
form.login p {
    max-width: 100%;
    height: auto;
}

form.login input[type=password] {
    max-width: 100%;
    width: 100%;
    height: auto;
}

}


问:
Dojo EnhancedGrid editable problem
I'm having problem with making my dojo EnhancedGrid editable.
Currently, I can double click the grid cells and I can change the value, but the moment I press enter again or try to leave the cells (i.e. to save the new value to the grid), I received the "assertion failed in ItemFileWriteStore" error in my firebug.

Below is my source code:

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
    <style type="text/css">
        body, html { font-family:helvetica,arial,sans-serif; font-size:90%; }
    </style>
    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dijit/themes/claro/claro.css" />
    <style type="text/css">
        @import "http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojox/grid/resources/Grid.css";
        @import "http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojox/grid/resources/claroGrid.css";
        .dojoxGrid table { margin: 0; }
    </style>
    <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojo/dojo.xd.js" djConfig="parseOnLoad: true">
    </script>

    <script type="text/javascript">
        dojo.require("dojox.grid.EnhancedGrid");
        dojo.require("dojo.data.ItemFileWriteStore");
        dojo.require("dojox.grid.cells._base");

        dojo.addOnLoad(function() {

            var layoutabc =
            [[
                {
                    field: "title",
                    name: "TitleofMovie",
                    width: "300px",
                    editable: true
                },
                {
                    field: "year",
                    name: "Year",
                    width: "200px",
                    editable: true
                },
                {
                    field: "producer",
                    name: "Producer",
                    width: "auto",
                    editable: true,
                    type: dojox.grid.cells.Cell
                }
            ]];

            var mystore = new dojo.data.ItemFileWriteStore({
                url: "movies.json"
            });

            // create a new grid:
            var grid = new dojox.grid.EnhancedGrid(
                {
                    query: {},
                    store: mystore,
                    structure: layoutabc
                },
                document.createElement("div")
            );
            dojo.byId("gridDiv").appendChild(grid.domNode);

            grid.startup();
        });
    </script>
</head>

<body class="claro">
    <div id="gridDiv" style="width: 800px; height: 400px;">
    </div>
</body>
</code>```

And this is the content of my movies.json (the content of data is weird, I know):

```<code>{
    items:
    [
        {
            title: "Africa",
            year: "continent",
            producer: "Katia Lund"
        },
        {
            title: "Kenya",
            year: "country",
            producer: "Christine Jeffs"
        },
        {
            title: "Mombasa",
            year: "city",
            producer: "Ridley Scott"
        }
    ]
}
</code>```

答: Problem solved. Turns out I need to define the "plugins" attribute for the EnhancedGrid object even though it is just an empty object. Once that is defined it works properly.</p>

Title: Dojo EnhancedGrid editable problem

Body:
I'm having problem with making my dojo EnhancedGrid editable.
Currently, I can double click the grid cells and I can change the value, but the moment I press enter again or try to leave the cells (i.e. to save the new value to the grid), I received the "assertion failed in ItemFileWriteStore" error in my firebug.

Below is my source code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dijit/themes/claro/claro.css" />

And this is the content of my movies.json (the content of data is weird, I know):

{
    items:
    [
        {
            title: "Africa",
            year: "continent",
            producer: "Katia Lund"
        },
        {
            title: "Kenya",
            year: "country",
            producer: "Christine Jeffs"
        },
        {
            title: "Mombasa",
            year: "city",
            producer: "Ridley Scott"
        }
    ]
}


问:
How to join 2 tables in codeigniter PHP?
I have 2 tables guest_info and guest_profile.two columns are there g_uid and company_id.Based on company_id(I have companyID), i have to take all g_uid.
In guest_info table,

g_uid | companyID

1        5

2        5

3        6

In guest_profile table,display all values from this table(only need to display first two datas)

g_uid | fname

1         xyz

2         fds

3         fsdf

答:
```<code>//Try this sql query to join 2 table in codeigniter
$company_id = 5;
$this->db->query("select * from `guest_info` INNER JOIN `guest_profile` ON guest_info.g_uid = guest_profile.g_uid WHERE guest_info.company_id = ".$company_id." LIMIT 2");
</code>```


问:
subprocess.py error: Ninja not building from source on Windows 8
I tried building Ninja from source. I did:

```<code>$ git clone git://github.com/martine/ninja.git && cd ninja
$ git checkout release
</code>```

Then in a Visual Studio command line I ran configure.py with Python:

```<code>$ C:\Python27\python.exe configure.py --bootstrap
</code>```

But here I get the following error:

```<code>C:\ninja>C:\Python27\python.exe configure.py --bootstrap
bootstrapping ninja...
Traceback (most recent call last):
  File "configure.py", line 320, in <module>
    if platform.msvc_needs_fs():
  File "configure.py", line 84, in msvc_needs_fs
    stderr=subprocess.PIPE)
  File "C:\Python27\Lib\subprocess.py", line 390, in __init__
    errread, errwrite)
  File "C:\Python27\Lib\subprocess.py", line 640, in _execute_chi
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
</code>```

After reading this answer, I added shell=True to all call() and check_call() occurrences in configure.py. But that still doesn't help.

Any ideas what to do?

答:
Looking at the code in question, it's trying to run cl, which is part of Microsoft Visual C++.

Do you have MSVC installed and in your PATH? I.e. does just running cl on the command line work?

Body:
I tried building Ninja from source. I did:

$ git clone git://github.com/martine/ninja.git && cd ninja
$ git checkout release

Then in a Visual Studio command line I ran configure.py with Python:

$ C:\Python27\python.exe configure.py --bootstrap

But here I get the following error:

C:\ninja>C:\Python27\python.exe configure.py --bootstrap
bootstrapping ninja...
Traceback (most recent call last):
  File "configure.py", line 320, in <module>
    if platform.msvc_needs_fs():
  File "configure.py", line 84, in msvc_needs_fs
    stderr=subprocess.PIPE)
  File "C:\Python27\Lib\subprocess.py", line 390, in __init__
    errread, errwrite)
  File "C:\Python27\Lib\subprocess.py", line 640, in _execute_chi
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

After reading this answer, I added shell=True to all call() and check_call() occurrences in configure.py. But that still doesn't help.

Any ideas what to do?


问:
How to call a function to execute on the url
I wrote a code which is working fine but now I want it to be in a function so as to call it on the url. I will really appreciate if you guys can help.

Here is my code.

```<code>$conn = mysqli_connect("localhost","root","","db");
if(mysqli_connect_errno()){
    echo "Unable to connect".mysqli_connect_error();
}

function day(){
$sql = "SELECT *, DATE_FORMAT(user_registerdate, '%m/%d/%Y') FROM ts_user
        WHERE DATE(user_registerdate) = CURDATE() - INTERVAL 5 DAY";
    if($result = mysqli_query($conn,$sql)){
        while($row = mysqli_fetch_assoc($result)){
            echo $row['user_uname']."<br />";
        }
    }
}
</code>```

And am calling it on the url as
http://localhost/test/index.php/day

Please telling me what am doing wrong. am I calling it wrongly on the url?

答:
you can try like that:

```<code>call_user_func($_GET['function']);
</code>```

And use URL http://localhost/test/index.php?function=day
In this way you can execute any function that you pass by GET parameter.

Body:
I wrote a code which is working fine but now I want it to be in a function so as to call it on the url. I will really appreciate if you guys can help.

Here is my code.

$conn = mysqli_connect("localhost","root","","db");
if(mysqli_connect_errno()){
    echo "Unable to connect".mysqli_connect_error();
}

function day(){
$sql = "SELECT *, DATE_FORMAT(user_registerdate, '%m/%d/%Y') FROM ts_user
        WHERE DATE(user_registerdate) = CURDATE() - INTERVAL 5 DAY";
    if($result = mysqli_query($conn,$sql)){
        while($row = mysqli_fetch_assoc($result)){
            echo $row['user_uname']."
";
        }
    }
}

And am calling it on the url as
http://localhost/test/index.php/day

Please telling me what am doing wrong. am I calling it wrongly on the url?

Body:
you can try like that:

call_user_func($_GET['function']);

And use URL http://localhost/test/index.php?function=day
In this way you can execute any function that you pass by GET parameter.


问:
Default initialization vs. copy initialization from default-constructed value
Let thing be a default-constructible and move-constructible type. Consider the following two initializations:

```<code>thing t1;          // (1)
auto t2 = thing{}; // (2)
</code>```

(1) default-constructs t1.

(2) default-constructs a temporary of type thing and moves it into t2.

Under which circumstances will the move in (2) be elided?

In modern style C++ initializations, the type usually either doesn't appear at all or appears on the right. For example:

```<code>auto copy = vec;                              // Type doesn't appear

auto p_derived = std::make_unique<derived>(); // Type appears naturally on the right

// Putting the type on the right here makes it explicit that the upcast is intended
auto p_base = std::unique_ptr<base>{ std::make_unique<derived>() };
</code>```

Using (2) would be consistent with those styles, whereas using (1) wouldn't.

Also, when using (1) with a long typename, the variable name appears far on the right. When using (2), the variable name is equally appparent no matter how long the typename is.

Does that mean that (2) is preferable over (1) for the sake of consistency?

答:
Under which circumstances will the move in (2) be elided?

When the compiler chooses to elide. This is practically always on modern compilers. However, there is no guaranteed copy elision in C++11 (nor C++14).

Using (2) would be consistent with those styles, whereas using (1) wouldn't.

Does that mean that (2) is preferable over (1) for the sake of consistency?

There is very little advantage in consistency for consistency's sake.

It is useful to understand why the type is on the right in your examples, and why (this meaning of) auto exists. The type is on the right because it is needed there for template instantiation. Still a type has to be on the left side also to have the syntax of a declaration. The type is also the return type of the right hand expression, so auto was introduced to allow deduction from that expression. This is advantageous because we avoid fragile duplication of the type.

(1) has no duplication, so there is no de-duplication advantage when introducing auto. There is no right hand expression and there is no need to introduce one. (2) has unnecessary extra boilerplate, and the added requirement for the type to be movable.

Also, when using (1) with a long typename, the variable name appears far on the right. When using (2), the variable name is equally appparent no matter how long the typename is.

This is a weak argument in my opinion. You should avoid unnecessarily long typenames anyway, but in case you're stuck with one, you can simply place them in separate lines:

```<code>thing_with_extra_long_type_name_for_some_reason<omg_it_doesnt_end>
  t1;
</code>```

Body:
Let thing be a default-constructible and move-constructible type. Consider the following two initializations:

thing t1;          // (1)
auto t2 = thing{}; // (2)

(1) default-constructs t1.

(2) default-constructs a temporary of type thing and moves it into t2.

Under which circumstances will the move in (2) be elided?

In modern style C++ initializations, the type usually either doesn't appear at all or appears on the right. For example:

auto copy = vec;                              // Type doesn't appear

auto p_derived = std::make_unique<derived>(); // Type appears naturally on the right

// Putting the type on the right here makes it explicit that the upcast is intended
auto p_base = std::unique_ptr<base>{ std::make_unique<derived>() };

Using (2) would be consistent with those styles, whereas using (1) wouldn't.

Also, when using (1) with a long typename, the variable name appears far on the right. When using (2), the variable name is equally appparent no matter how long the typename is.

Does that mean that (2) is preferable over (1) for the sake of consistency?

Body:
Under which circumstances will the move in (2) be elided?

When the compiler chooses to elide. This is practically always on modern compilers. However, there is no guaranteed copy elision in C++11 (nor C++14).

Using (2) would be consistent with those styles, whereas using (1) wouldn't.

Does that mean that (2) is preferable over (1) for the sake of consistency?

There is very little advantage in consistency for consistency's sake.

It is useful to understand why the type is on the right in your examples, and why (this meaning of) auto exists. The type is on the right because it is needed there for template instantiation. Still a type has to be on the left side also to have the syntax of a declaration. The type is also the return type of the right hand expression, so auto was introduced to allow deduction from that expression. This is advantageous because we avoid fragile duplication of the type.

(1) has no duplication, so there is no de-duplication advantage when introducing auto. There is no right hand expression and there is no need to introduce one. (2) has unnecessary extra boilerplate, and the added requirement for the type to be movable.

Also, when using (1) with a long typename, the variable name appears far on the right. When using (2), the variable name is equally appparent no matter how long the typename is.

This is a weak argument in my opinion. You should avoid unnecessarily long typenames anyway, but in case you're stuck with one, you can simply place them in separate lines:

thing_with_extra_long_type_name_for_some_reason<omg_it_doesnt_end>
  t1;


问:
socket server responding multiple requests simultaneously from a client socket
I am building a socket server with Python.

This server

receives data from client

does something here (approximately it takes about 10 sec in maximum depending on input data)

sends back data after some works done above

This system works fine unless client doesn't send data simultaneously in a row. For example, say server takes 5 seconds to process data and client sends data every 10 seconds. The problem, however, is that client send multiple requests at a time, thus causing a delay. Currently, client cannot send data to server unless server is ready to receive data which means that server is not doing any work. Below are what I want to build.

a) build a queue at socket server whose main task is to make a queue of input data so that client can send data to server even when server is busy

b) make a thread(here, I'm bit confused with concurrency and parallelism. Work in socket focused on computation rather than system call) at socket server so that server can do work 'simultaneously'.

c) send back data to client socket

My questions are as follows.

Is it Queue that I need to use in order to achieve a) ?

Is it thread or something else that I need to use in order to achieve b)?

Thanks in advance

Best

Gee

答:
Yeah something like this could work.

First, you'll need a thread to receive and send data. If you have limited amount of clients, you can create a thread per client, but it's not an option for a more or less robust system. In order to be able to serve multiple clients in a single thread, the sockets should be nonblocking. Otherwise one long transmission would block other transmissions. Nonblocking code has more sophisticated structure that uses select, so I would advice to spend some time reading about it.

Then you'll need a thread to do the math. Or several threads/processes if "the math" is taking long to execute.

Last but not least, these socket threads and a "math" thread should use two queues to exchange data. Simple lists's are enough, but make sure they are synchronized. Guard them with mutexes, or locks. This is another vast topic that is worth reading about.


问:
How to count duplicate elements in ArrayList?
I need to separate and count how many values in arraylist are the same and print them according to the number of occurrences.

I've got an arraylist called digits :

```<code> [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]
</code>```

I created a method which separates each value and saves it to a new array.

```<code>public static ArrayList<Integer> myNumbers(int z) {

    ArrayList<Integer> digits = new ArrayList<Integer>();
    String number = String.valueOf(z);
    for (int a = 0; a < number.length(); a++) {
        int j = Character.digit(number.charAt(a), 10);
        digits.add(j);
    }
    return digits;

}
</code>```

After this I've got a new array called numbers. I'm using sort on this array

```<code>Collections.sort(numbers);
</code>```

and my ArrayList looks like this:

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

It has:

```<code>2 times 0;
9 times 1;
4 times 2;
6 times 3;
5 times 4;
6 times 5;
5 times 6;
5 times 7;
5 times 8;
3 times 9;
</code>```

I need to print out the string of numbers depend on how many are they
So it suppose to look like this :
1354678290

答:
Well, for that you can try to use Map

```<code>Map<Integer, Integer> countMap = new HashMap<>();

  for (Integer item: yourArrayList) {

      if (countMap.containsKey(item))
          countMap.put(item, countMap.get(item) + 1);
      else
          countMap.put(item, 1);
  }
</code>```

After end of forEach loop you will have a filled map with your items against it count

Body:
I need to separate and count how many values in arraylist are the same and print them according to the number of occurrences.

I've got an arraylist called digits :

 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]

I created a method which separates each value and saves it to a new array.

public static ArrayList<Integer> myNumbers(int z) {

    ArrayList<Integer> digits = new ArrayList<Integer>();
    String number = String.valueOf(z);
    for (int a = 0; a < number.length(); a++) {
        int j = Character.digit(number.charAt(a), 10);
        digits.add(j);
    }
    return digits;

}

After this I've got a new array called numbers. I'm using sort on this array

Collections.sort(numbers);

and my ArrayList looks like this:

[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9]

It has:

2 times 0;
9 times 1;
4 times 2;
6 times 3;
5 times 4;
6 times 5;
5 times 6;
5 times 7;
5 times 8;
3 times 9;

I need to print out the string of numbers depend on how many are they
So it suppose to look like this :
1354678290

Body:
Well, for that you can try to use Map

Map<Integer, Integer> countMap = new HashMap<>();

  for (Integer item: yourArrayList) {

      if (countMap.containsKey(item))
          countMap.put(item, countMap.get(item) + 1);
      else
          countMap.put(item, 1);
  }

After end of forEach loop you will have a filled map with your items against it count


问:
Trouble connecting NodeMCU to Microsoft Azure IoT Hub
I am trying to connect my ESP8266, running the latest NodeMCU build, to a Microsoft Azure IoT Hub via MQTT Protocol.

It appears that this is possible, as it is shown here...

http://thinglabs.io/workshop/esp8266/sending-d2c-messages/

I am using the correct syntax as far as I can see from the MS Azure help...

https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-mqtt-support

Unlike the example in ThingLabs, which creates a SAS token using NodeMCU, I have followed the MS document and generated a SAS token using the Device Explorer, for testing purposes.

My LUA code is as follows...

```<code>-- Create variables

DEVICE = "testdevice"
IOTHUB = "mynewiothub.azure-devices.net"
PORT = 8883
USER = IOTHUB.."/"..DEVICE.."/api-version=2016-11-14"
PASS = "SharedAccessSignature sr=mynewiothub.azure-devices.net%2Fdevices%2Ftestdevice&sig=Roa5P8BPiGj...v2Vu%2Bm1j9sas%3D&se=1485704099"

-- Create an MQTT Client

azure = mqtt.Client(DEVICE, 60, USER, PASS)

-- Connect to IoTHub via MQTT

azure:connect(IOTHUB, PORT, 1, 0,
    -- Callback for a successful connection
    function(client)
        print("Connected")
    end,
    -- Error callback, if connection fails
    function(client, reason)
        print("Error Connecting: "..reason)
    end
)
</code>```

The response is always Error Connecting: -5 which translates to "There is no broker listening at the specified IP Address and Port".

I suspected that NodeMCU was struggling with the SSL (port 8883) connection. So I ensured that I was able to make HTTPS connections (after verifying the SSL root certificate) with the following code, this worked but did not help.

```<code>http.get("https://example.com/info", nil,
function (code, resp)
     print(code, resp)
end)
</code>```

I cannot seem to get this to work! @Marcel Stör - any thoughts?

Many thanks in advance.

答:
I had the same error Error Connecting: -5 , I have set the time on the ESP and it fix this error.

You will find some information about sntp on http://thinglabs.io/workshop/esp8266/sending-d2c-messages/ (as you mention it).

Body:
I am trying to connect my ESP8266, running the latest NodeMCU build, to a Microsoft Azure IoT Hub via MQTT Protocol.

It appears that this is possible, as it is shown here...

http://thinglabs.io/workshop/esp8266/sending-d2c-messages/

I am using the correct syntax as far as I can see from the MS Azure help...

https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-mqtt-support

Unlike the example in ThingLabs, which creates a SAS token using NodeMCU, I have followed the MS document and generated a SAS token using the Device Explorer, for testing purposes.

My LUA code is as follows...

-- Create variables

DEVICE = "testdevice"
IOTHUB = "mynewiothub.azure-devices.net"
PORT = 8883
USER = IOTHUB.."/"..DEVICE.."/api-version=2016-11-14"
PASS = "SharedAccessSignature sr=mynewiothub.azure-devices.net%2Fdevices%2Ftestdevice&sig=Roa5P8BPiGj...v2Vu%2Bm1j9sas%3D&se=1485704099"

-- Create an MQTT Client

azure = mqtt.Client(DEVICE, 60, USER, PASS)

-- Connect to IoTHub via MQTT

azure:connect(IOTHUB, PORT, 1, 0,
    -- Callback for a successful connection
    function(client)
        print("Connected")
    end,
    -- Error callback, if connection fails
    function(client, reason)
        print("Error Connecting: "..reason)
    end
)

The response is always Error Connecting: -5 which translates to "There is no broker listening at the specified IP Address and Port".

I suspected that NodeMCU was struggling with the SSL (port 8883) connection. So I ensured that I was able to make HTTPS connections (after verifying the SSL root certificate) with the following code, this worked but did not help.

http.get("https://example.com/info", nil,
function (code, resp)
     print(code, resp)
end)

I cannot seem to get this to work! @Marcel Stör - any thoughts?

Many thanks in advance.


问:
Set spinner title when activity is created
I have a spinner whose elements set by an arrayList.this arraylist gets data by calling an api. I have set title at 0th position of  arrayList .the problem is i want to show this title as activity is created. but this will set only when api calling is successful .it takes some time to load data. can anyone give me better idea to set title to spinner. </p>

答:
Try this way

```<code>ArrayList<String> list  = new ArrayList<>();
        list.add(0,"Please Select");

        ArrayAdapter stringArrayAdapter = new ArrayAdapter(this,  android.R.layout.simple_spinner_item, CatagoryName);
        Spinner spinner = (Spinner) findViewById(R.id.spinner);
        spinner.setAdapter(stringArrayAdapter);

        // now call the API for data

        //After data received, you have to make  temp list to store response
        ArrayList<String> Templist  = new ArrayList<>();

        //Templist = Server response

        //now add templist in main List
        list.addAll(Templist);
        // and call this
        stringArrayAdapter.notifyDataSetChanged();
</code>```

Body:
Try this way

ArrayList<String> list  = new ArrayList<>();
        list.add(0,"Please Select");

        ArrayAdapter stringArrayAdapter = new ArrayAdapter(this,  android.R.layout.simple_spinner_item, CatagoryName);
        Spinner spinner = (Spinner) findViewById(R.id.spinner);
        spinner.setAdapter(stringArrayAdapter);

        // now call the API for data

        //After data received, you have to make  temp list to store response
        ArrayList<String> Templist  = new ArrayList<>();

        //Templist = Server response

        //now add templist in main List
        list.addAll(Templist);
        // and call this
        stringArrayAdapter.notifyDataSetChanged();