问:
Unable to fetch commit from github
The following commands fail to check out this commit:

```<code>$ git clone git@github.com:DefinitelyTyped/DefinitelyTyped.git
$ cd DefinitelyTyped
$ git checkout e90424c424ef9087d0589234e9e9cd0140bab0d7
fatal: reference is not a tree: e90424c424ef9087d0589234e9e9cd0140bab0d7
</code>```

Attempting to follow the advice given here results in the following:

```<code>$ git fetch origin e90424c424ef9087d0589234e9e9cd0140bab0d7
$ echo $?
1
</code>```

Is this failure something specific to GitHub / large repos on GitHub?  My git version is 2.10.1.

** edit **

```<code>$ git fetch origin e90424c424ef9087d0589234e9e9cd0140bab0d7:refs/remotes/origin/foo-commit
$ echo $?
1
$ git cat-file -p e90424c424ef9087d0589234e9e9cd0140bab0d7
fatal: Not a valid object name e90424c424ef9087d0589234e9e9cd0140bab0d7
$ git branch -a --contains e90424c424ef9087d0589234e9e9cd0140bab0d7
error: no such commit e90424c424ef9087d0589234e9e9cd0140bab0d7
$ git reset e90424c424ef9087d0589234e9e9cd0140bab0d7
fatal: Could not parse object 'e90424c424ef9087d0589234e9e9cd0140bab0d7'.
</code>```

答:
I suspect that the commit is not reachable from any ref (branch or tag) so the server isn't including it in the pack file it sends you.

In my tests, fetching a specific commit by SHA1 only seems to work if the commit is already in your local repo (which isn't too useful as far as I can tell; it does update FETCH_HEAD I guess)... I didn't even know it would work in that case.

Without direct access to the remote repo, I don't know a procedure to recover.  (I'm not counting the idea of manually fetching each object individually and reconstructing the commit - and any missing history - locally; even if it can be done in theory, it's totally impractical.)

A little research suggests trying this command:

```<code>git archive -o repo.tar --remote=git@github.com:DefinitelyTyped/DefinitelyTyped.git e90424c424ef9087d0589234e9e9cd0140bab0d7
</code>```

I'm not in a position to test this with any protocol but https, and it won't work with that protocol; but you might give it a shot.

Title: Unable to fetch commit from github

Body:
The following commands fail to check out this commit:

$ git clone git@github.com:DefinitelyTyped/DefinitelyTyped.git
$ cd DefinitelyTyped
$ git checkout e90424c424ef9087d0589234e9e9cd0140bab0d7
fatal: reference is not a tree: e90424c424ef9087d0589234e9e9cd0140bab0d7

Attempting to follow the advice given here results in the following:

$ git fetch origin e90424c424ef9087d0589234e9e9cd0140bab0d7
$ echo $?
1

Is this failure something specific to GitHub / large repos on GitHub?  My git version is 2.10.1.

** edit **

$ git fetch origin e90424c424ef9087d0589234e9e9cd0140bab0d7:refs/remotes/origin/foo-commit
$ echo $?
1
$ git cat-file -p e90424c424ef9087d0589234e9e9cd0140bab0d7
fatal: Not a valid object name e90424c424ef9087d0589234e9e9cd0140bab0d7
$ git branch -a --contains e90424c424ef9087d0589234e9e9cd0140bab0d7
error: no such commit e90424c424ef9087d0589234e9e9cd0140bab0d7
$ git reset e90424c424ef9087d0589234e9e9cd0140bab0d7
fatal: Could not parse object 'e90424c424ef9087d0589234e9e9cd0140bab0d7'.

Body:
I suspect that the commit is not reachable from any ref (branch or tag) so the server isn't including it in the pack file it sends you.

In my tests, fetching a specific commit by SHA1 only seems to work if the commit is already in your local repo (which isn't too useful as far as I can tell; it does update FETCH_HEAD I guess)... I didn't even know it would work in that case.

Without direct access to the remote repo, I don't know a procedure to recover.  (I'm not counting the idea of manually fetching each object individually and reconstructing the commit - and any missing history - locally; even if it can be done in theory, it's totally impractical.)

A little research suggests trying this command:

git archive -o repo.tar --remote=git@github.com:DefinitelyTyped/DefinitelyTyped.git e90424c424ef9087d0589234e9e9cd0140bab0d7

I'm not in a position to test this with any protocol but https, and it won't work with that protocol; but you might give it a shot.


来源: stackexchange

问:
Distance from nurbs curve to its control points
Is it possible to get distance from nurbs control points to the nurbs curve?
I understand the weights control the shape of the curve but i would like to get the distance to the control points.</p>

答:
The nurbs curve is defined by the control points, so you just need to run a Point-Curve distance algorithm.

The algorithm is described in "The Nurbs Book", but essentially you just have to minimize this function:

```<code>    f(u) = C'(u)∙[C(u) - P]
</code>```

where P is the control point, and C is your nurbs curve. C' is the derivative of the curve.

You can use any numerical method to find the minimum of f(u), (Newton, for example)

ContentLicense: CC BY-SA 3.0

Body:
The nurbs curve is defined by the control points, so you just need to run a Point-Curve distance algorithm.

The algorithm is described in "The Nurbs Book", but essentially you just have to minimize this function:

    f(u) = C'(u)∙[C(u) - P]

where P is the control point, and C is your nurbs curve. C' is the derivative of the curve.

You can use any numerical method to find the minimum of f(u), (Newton, for example)


问:
Hiding an item from KendoUI DDL
I am currently using KendoUI DropDownListfor and I am trying to hide an item from my options list.

I could do this with @Html.DropDownListFor with javascript using the following script:

```<code>$("#relationDDL").children('option[value="2"]').hide();
</code>```

But when I wanted to change my dropdownlist to the KendoUI one I couldn't achieve that. I used multiple solutions posted in the forum and in How to modify KendoUI DropDownList items but no chance. How can I solve this?

答:
I know this is a very old question but it may still be relevant today, so here's my solution:

Because the dropdown-items are stored in a seperate container you're be able to hide the items from there.

In your case the container element id is: #relationDDL_listbox.

From there it's easy.

Solution to hide specific option per index:

```<code>$('#relationDDL_listbox .k-item').eq(1).hide();
</code>```

Solution to hide specific option per value:

First you need the the index of the value you want to hide so I wrote a simple function to get it:

```<code>//for modern browsers only
function getIndex(kendoDropDownList, value) {
    const index = kendoDropDownList.dataSource.options.data.findIndex(x => x.value == value);
    if (~index) return index;
    throw 'value not found in options';
}

//older browsers
function getIndex(kendoDropDownList, value) {
    var d = kendoDropDownList.dataSource.options.data;
    for(var i = d.length; i--;) {
        if (d[i].value == value) return i;
    }

    throw 'value not found in options';
}

var index = getIndex($('#relationDDL').data('kendoDropDownList'), '2'); //you may want to use 'const' instead of 'var' for modern browsers
$('#relationDDL_listbox .k-item').eq(index).hide();
</code>```

I'm pretty sure there are a few more ways to get the same result...

Title: Hiding an item from KendoUI DDL

Body:
I am currently using KendoUI DropDownListfor and I am trying to hide an item from my options list.

I could do this with @Html.DropDownListFor with javascript using the following script:

$("#relationDDL").children('option[value="2"]').hide();

But when I wanted to change my dropdownlist to the KendoUI one I couldn't achieve that. I used multiple solutions posted in the forum and in How to modify KendoUI DropDownList items but no chance. How can I solve this?

Body:
I know this is a very old question but it may still be relevant today, so here's my solution:

Because the dropdown-items are stored in a seperate container you're be able to hide the items from there.

In your case the container element id is: #relationDDL_listbox.

From there it's easy.

Solution to hide specific option per index:

$('#relationDDL_listbox .k-item').eq(1).hide();

Solution to hide specific option per value:

First you need the the index of the value you want to hide so I wrote a simple function to get it:

//for modern browsers only
function getIndex(kendoDropDownList, value) {
    const index = kendoDropDownList.dataSource.options.data.findIndex(x => x.value == value);
    if (~index) return index;
    throw 'value not found in options';
}

//older browsers
function getIndex(kendoDropDownList, value) {
    var d = kendoDropDownList.dataSource.options.data;
    for(var i = d.length; i--;) {
        if (d[i].value == value) return i;
    }

    throw 'value not found in options';
}

var index = getIndex($('#relationDDL').data('kendoDropDownList'), '2'); //you may want to use 'const' instead of 'var' for modern browsers
$('#relationDDL_listbox .k-item').eq(index).hide();

I'm pretty sure there are a few more ways to get the same result...


问:
ng is not recognized as an internal or external command
Running windows 7 Professional 32bit.

I tried running npm install -g angular-cli both under normal or admin.

I also tried adding it to the Enviorment Variables under PATH: (C:\Users\Administrator\AppData\Roaming\npm\node_modules\angular-cli\bin\ng) , with no success also.

What am i doing wrong?

答:
For me it works with:</p>

```<code>npm run ng <command>
</code>```

Body:
For me it works with:

npm run ng <command>


问:
After Installing Visual Studio 2017 I am unable to debug in SQL Server Management Studio (SSMS)
After Installing VS2017 I am unable to debug queries in SQL Server Management Studio 2012 (SSMS). I keep getting the error:

Unable to start program 'MSSQL:://YOUR_SERVER/YOUR_DATABASE/sys/=0'

A Visual Studio DLL, coloader80.dll, is not correctly installed.
  Please repair you Visual Studio installation via 'Add or Remove
  Programs' in Control Panel.

If the problem persis, you can manually register coloader80.dll from
  the command prompt with 'regsvr32 "%CommonProgramFiles%\Microsoft
  Shared\VS7Debug\coloader80.dll'

答:
From: Developer Community.
To fix this issue, you can either:

Open a command prompt with administrator privileges and execute the following command:

```<code>reg add HKEY_CLASSES_ROOT\TypeLib{6A1A7D39-8449-4287-8EF0-CE256582C940}\8.0\0\win32 /t REG_SZ /d "C:\Program Files (x86)\Common Files\Microsoft Shared\VS7Debug\coloader80.tlb"
</code>```

Alternatively you can execute:

```<code>regsvr32 "C:\Program Files (x86)\Common Files\Microsoft Shared\VS7Debug\coloader80.dll"
</code>```

The correct registration will be included in future versions of Visual Studio.

Body:
From: Developer Community.
To fix this issue, you can either:

Open a command prompt with administrator privileges and execute the following command:

reg add HKEY_CLASSES_ROOT\TypeLib{6A1A7D39-8449-4287-8EF0-CE256582C940}\8.0\0\win32 /t REG_SZ /d "C:\Program Files (x86)\Common Files\Microsoft Shared\VS7Debug\coloader80.tlb"

Alternatively you can execute:

regsvr32 "C:\Program Files (x86)\Common Files\Microsoft Shared\VS7Debug\coloader80.dll"

The correct registration will be included in future versions of Visual Studio.


问:
PrestaShop, get ID when insert in DB
I am creating a script for PrestaShop 1.6 that inserts data into a table.
My table is made in this way:

id: int AUTO INCREMENT

desc: string

As I enter a description I would get back the ID value.

On can not use the standard because it blocked by PrestaShop.

I find this a situation:

```<code>$sql = "INSERT INTO `"._DB_PREFIX_."table`(`desc`) VALUES ('".$this->desc."')";
$restpo = Db::getInstance()->execute($sql);
var_dump($restpo);
</code>```

But I have an answer only a boolean.
Can you suggest something?

答: Use $id = Db::getInstance()->Insert_ID(); after executing your SQL.

Title: PrestaShop, get ID when insert in DB

Body:
I am creating a script for PrestaShop 1.6 that inserts data into a table.
My table is made in this way:

id: int AUTO INCREMENT

desc: string

As I enter a description I would get back the ID value.

On can not use the standard because it blocked by PrestaShop.

I find this a situation:

$sql = "INSERT INTO `"._DB_PREFIX_."table`(`desc`) VALUES ('".$this->desc."')";
$restpo = Db::getInstance()->execute($sql);
var_dump($restpo);

But I have an answer only a boolean.
Can you suggest something?


问:
Count number of appearances in JSON data for nested element
How I can get the appearance of elements in JSON data for nested element?

```<code>[
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'highestCurrent(scale(vcenter.*.*.*.*.cpu.usage_percent_average, 0.01), 5)'  -w 1 -c 6 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"vm_cpu_average",
                            "issued":1490774610,
                            "executed":1490774610,
                            "duration":0.142,
                            "output":"CheckGraphiteStat WARNING: No data from Graphite\n",
                            "status":3,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'collectd.*.*.system.memory.used.pct' -w 50 -c 75 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"mem_average",
                            "issued":1490774614,
                            "executed":1490774614,
                            "duration":0.223,
                            "output":"CheckGraphiteStat CRITICAL: collectd.DEMO.172_16_109_100.system.memory.used.pct is 94.44555555555556 \n",
                            "status":2,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'scale(vcenter.*.*.*.*.mem.usage_percent_average, 0.01)' -w 50 -c 75 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"vm_mem_average",
                            "issued":1490774614,
                            "executed":1490774614,
                            "duration":0.216,
                            "output":"CheckGraphiteStat WARNING: No data from Graphite\n",
                            "status":3,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'absolute(offset(collectd.*.*.system.cpu.idle.pct, -100))'  -c 7 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"cpu_average",
                            "issued":1490774613,
                            "executed":1490774613,
                            "duration":0.124,
                            "output":"CheckGraphiteStat CRITICAL: absolute(offset(collectd.DEMO.172_16_109_100.system.cpu.idle.pct,-100)) is 10.585147058823525 \n",
                            "status":2,
                            "type":"standard"
                    }
    }
</code>```

]

I need to count the number of appearances of WARNING and CRITICAL appeared, if it's appeared in output(check -> output).

Please excuse if this is a novice question. I'm new to this.

答:
You could do something like:

```<code>let critialCount = 0
let warningCount = 0

for(let i = 0; i < data.length; i++) {
  if(data[i].check.output.indexOf('CRITICAL') > -1) {
    critialCount++
  }
  else if(data[i].check.output.indexOf('WARNING') > -1) {
    warningCount++
  }
}

console.log('Critical count: ' + critialCount)
console.log('Warning count: ' + warningCount)
</code>```

Working example:

const data =[
    {
        "client": "172.16.109.96",
        "check": {
            "command": "/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'highestCurrent(scale(vcenter.*.*.*.*.cpu.usage_percent_average, 0.01), 5)'  -w 1 -c 6 -p -6hours",
            "standalone": true,
            "interval": 5,
            "name": "vm_cpu_average",
            "issued": 1490774610,
            "executed": 1490774610,
            "duration": 0.142,
            "output": "CheckGraphiteStat WARNING: No data from Graphite\n",
            "status": 3,
            "type": "standard"
        }
    },
    {
        "client": "172.16.109.96",
        "check": {
            "command": "/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'collectd.*.*.system.memory.used.pct' -w 50 -c 75 -p -6hours",
            "standalone": true,
            "interval": 5,
            "name": "mem_average",
            "issued": 1490774614,
            "executed": 1490774614,
            "duration": 0.223,
            "output": "CheckGraphiteStat CRITICAL: collectd.DEMO.172_16_109_100.system.memory.used.pct is 94.44555555555556 \n",
            "status": 2,
            "type": "standard"
        }
    },
    {
        "client": "172.16.109.96",
        "check": {
            "command": "/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'scale(vcenter.*.*.*.*.mem.usage_percent_average, 0.01)' -w 50 -c 75 -p -6hours",
            "standalone": true,
            "interval": 5,
            "name": "vm_mem_average",
            "issued": 1490774614,
            "executed": 1490774614,
            "duration": 0.216,
            "output": "CheckGraphiteStat WARNING: No data from Graphite\n",
            "status": 3,
            "type": "standard"
        }
    },
    {
        "client": "172.16.109.96",
        "check": {
            "command": "/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'absolute(offset(collectd.*.*.system.cpu.idle.pct, -100))'  -c 7 -p -6hours",
            "standalone": true,
            "interval": 5,
            "name": "cpu_average",
            "issued": 1490774613,
            "executed": 1490774613,
            "duration": 0.124,
            "output": "CheckGraphiteStat CRITICAL: absolute(offset(collectd.DEMO.172_16_109_100.system.cpu.idle.pct,-100)) is 10.585147058823525 \n",
            "status": 2,
            "type": "standard"
        }
    }
]

let critialCount = 0
let warningCount = 0

for(let i = 0; i < data.length; i++) {
  if(data[i].check.output.indexOf('CRITICAL') > -1) {
    critialCount++
  }
  else if(data[i].check.output.indexOf('WARNING') > -1) {
    warningCount++
  }
}

console.log('Critical count: ' + critialCount)
console.log('Warning count: ' + warningCount)```

Body:
How I can get the appearance of elements in JSON data for nested element?

[
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'highestCurrent(scale(vcenter.*.*.*.*.cpu.usage_percent_average, 0.01), 5)'  -w 1 -c 6 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"vm_cpu_average",
                            "issued":1490774610,
                            "executed":1490774610,
                            "duration":0.142,
                            "output":"CheckGraphiteStat WARNING: No data from Graphite\n",
                            "status":3,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'collectd.*.*.system.memory.used.pct' -w 50 -c 75 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"mem_average",
                            "issued":1490774614,
                            "executed":1490774614,
                            "duration":0.223,
                            "output":"CheckGraphiteStat CRITICAL: collectd.DEMO.172_16_109_100.system.memory.used.pct is 94.44555555555556 \n",
                            "status":2,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'scale(vcenter.*.*.*.*.mem.usage_percent_average, 0.01)' -w 50 -c 75 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"vm_mem_average",
                            "issued":1490774614,
                            "executed":1490774614,
                            "duration":0.216,
                            "output":"CheckGraphiteStat WARNING: No data from Graphite\n",
                            "status":3,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'absolute(offset(collectd.*.*.system.cpu.idle.pct, -100))'  -c 7 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"cpu_average",
                            "issued":1490774613,
                            "executed":1490774613,
                            "duration":0.124,
                            "output":"CheckGraphiteStat CRITICAL: absolute(offset(collectd.DEMO.172_16_109_100.system.cpu.idle.pct,-100)) is 10.585147058823525 \n",
                            "status":2,
                            "type":"standard"
                    }
    }

]

I need to count the number of appearances of WARNING and CRITICAL appeared, if it's appeared in output(check -> output).

Please excuse if this is a novice question. I'm new to this.

Body:
You could do something like:

let critialCount = 0
let warningCount = 0

for(let i = 0; i < data.length; i++) {
  if(data[i].check.output.indexOf('CRITICAL') > -1) {
    critialCount++
  }
  else if(data[i].check.output.indexOf('WARNING') > -1) {
    warningCount++
  }
}

console.log('Critical count: ' + critialCount)
console.log('Warning count: ' + warningCount)

Working example:

const data =[
    {
        "client": "172.16.109.96",
        "check": {
            "command": "/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'highestCurrent(scale(vcenter.*.*.*.*.cpu.usage_percent_average, 0.01), 5)'  -w 1 -c 6 -p -6hours",
            "standalone": true,
            "interval": 5,
            "name": "vm_cpu_average",
            "issued": 1490774610,
            "executed": 1490774610,
            "duration": 0.142,
            "output": "CheckGraphiteStat WARNING: No data from Graphite\n",
            "status": 3,
            "type": "standard"
        }
    },
    {
        "client": "172.16.109.96",
        "check": {
            "command": "/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'collectd.*.*.system.memory.used.pct' -w 50 -c 75 -p -6hours",
            "standalone": true,
            "interval": 5,
            "name": "mem_average",
            "issued": 1490774614,
            "executed": 1490774614,
            "duration": 0.223,
            "output": "CheckGraphiteStat CRITICAL: collectd.DEMO.172_16_109_100.system.memory.used.pct is 94.44555555555556 \n",
            "status": 2,
            "type": "standard"
        }
    },
    {
        "client": "172.16.109.96",
        "check": {
            "command": "/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'scale(vcenter.*.*.*.*.mem.usage_percent_average, 0.01)' -w 50 -c 75 -p -6hours",
            "standalone": true,
            "interval": 5,
            "name": "vm_mem_average",
            "issued": 1490774614,
            "executed": 1490774614,
            "duration": 0.216,
            "output": "CheckGraphiteStat WARNING: No data from Graphite\n",
            "status": 3,
            "type": "standard"
        }
    },
    {
        "client": "172.16.109.96",
        "check": {
            "command": "/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'absolute(offset(collectd.*.*.system.cpu.idle.pct, -100))'  -c 7 -p -6hours",
            "standalone": true,
            "interval": 5,
            "name": "cpu_average",
            "issued": 1490774613,
            "executed": 1490774613,
            "duration": 0.124,
            "output": "CheckGraphiteStat CRITICAL: absolute(offset(collectd.DEMO.172_16_109_100.system.cpu.idle.pct,-100)) is 10.585147058823525 \n",
            "status": 2,
            "type": "standard"
        }
    }
]

let critialCount = 0
let warningCount = 0

for(let i = 0; i < data.length; i++) {
  if(data[i].check.output.indexOf('CRITICAL') > -1) {
    critialCount++
  }
  else if(data[i].check.output.indexOf('WARNING') > -1) {
    warningCount++
  }
}

console.log('Critical count: ' + critialCount)
console.log('Warning count: ' + warningCount)


问:
How to create a queryset that filters multiple fields based on a single condition in Django?
My model is

```<code>class TestModel(models.Model)
    field1 = models.IntegerField()
    field2 = models.IntegerField()
    field3 = models.IntegerField()
    field4 = models.IntegerField()
    field5 = models.IntegerField()
</code>```

I need a simple queryset that applies a single condition on all the five fields of the model without writing every combination of fields and filtering them.

For example I want to apply a condition of checking for None to two or more fields

```<code>TestModel.objects.filter(two_or_more_fields=None)
</code>```

I don't want write every possible combination of 5 fields to find the queryset with any two or more fields as None. In other words, is there a better way to accomplish this than:

```<code>from django.db.models import Q
TestModel.objects.filter(
    #condition for exactly 2 None
    Q(field1=None & field2=None) |
    Q(field2=None & field3=None) |
    Q(field3=None & field4=None) |
    Q(field4=None & field5=None) |
    Q(field5=None & field1=None) |
    #condition for more than 2 None
    Q(field1=None & field2=None & field3 = None) |
    '''''
    .
    .
    #so on to cover all possible cases of any two or more fields as None
     )
</code>```

I think there should be a better and simple way to accomplish this.

答:
After spending hours I could not find a simple way to do this using built in Django filter constructs. However I found this solution which is closer to what I was searching for:</p>

```<code>field_list = ['field1', 'field2', 'field3', 'field4', 'field5']

def get_all_possible_filter_dict_list_for_a_condition(field_list):

    all_possible_filter_dict_for_a_condition = []
    for field_1, field_2 in combinations(field_list, 2):
        all_possible_filter_dict_for_a_condition.append(
        {
         field_1:None,
         field_2:None
         }
        )
    return all_possible_filter_dict_for_a_condition

def get_qs_list_to_perform_or_operation(all_possible_filter_dict_list_for_a_condition):

    qs_list_to_perform_or_operation = []
    for i, filter_dict in enumerate(all_possible_filter_dict_list_for_a_condition):
       qs_to_append = qs.filter(**filter_dict)
       qs_list_to_perform_or_operation.append(qs_to_append)
    return qs_list_to_perform_or_operation

def get_qs_to_filter_fields_with_more_than_1_none(qs_list_to_perform_or_operation ):

    final_qs = qs_list_to_perform_or_operation [0]
    for i in range(len(qs_list_to_perform_or_operation ) - 1):
        final_qs = final_qs | qs_list[i + 1]
    return final_qs

all_possible_filter_dict_list_for_a_condition
   = get_all_possible_filter_dict_list_for_a_condition(field_list)
qs_list_to_perform_or_operation = get_qs_list_to_perform_or_operation(all_possible_filter_dict_list_for_a_condition)
final_qs_to_filter_multiple_fields_with_same_condtion = get_qs_to_filter_fields_with_more_than_1_none(qs_list_to_perform_or_operation)
</code>```

Body:
My model is

class TestModel(models.Model)
    field1 = models.IntegerField()
    field2 = models.IntegerField()
    field3 = models.IntegerField()
    field4 = models.IntegerField()
    field5 = models.IntegerField()

I need a simple queryset that applies a single condition on all the five fields of the model without writing every combination of fields and filtering them.

For example I want to apply a condition of checking for None to two or more fields

TestModel.objects.filter(two_or_more_fields=None)

I don't want write every possible combination of 5 fields to find the queryset with any two or more fields as None. In other words, is there a better way to accomplish this than:

from django.db.models import Q
TestModel.objects.filter(
    #condition for exactly 2 None
    Q(field1=None & field2=None) |
    Q(field2=None & field3=None) |
    Q(field3=None & field4=None) |
    Q(field4=None & field5=None) |
    Q(field5=None & field1=None) |
    #condition for more than 2 None
    Q(field1=None & field2=None & field3 = None) |
    '''''
    .
    .
    #so on to cover all possible cases of any two or more fields as None
     )

I think there should be a better and simple way to accomplish this.

Body:
After spending hours I could not find a simple way to do this using built in Django filter constructs. However I found this solution which is closer to what I was searching for:

field_list = ['field1', 'field2', 'field3', 'field4', 'field5']

def get_all_possible_filter_dict_list_for_a_condition(field_list):

    all_possible_filter_dict_for_a_condition = []
    for field_1, field_2 in combinations(field_list, 2):
        all_possible_filter_dict_for_a_condition.append(
        {
         field_1:None,
         field_2:None
         }
        )
    return all_possible_filter_dict_for_a_condition

def get_qs_list_to_perform_or_operation(all_possible_filter_dict_list_for_a_condition):

    qs_list_to_perform_or_operation = []
    for i, filter_dict in enumerate(all_possible_filter_dict_list_for_a_condition):
       qs_to_append = qs.filter(**filter_dict)
       qs_list_to_perform_or_operation.append(qs_to_append)
    return qs_list_to_perform_or_operation

def get_qs_to_filter_fields_with_more_than_1_none(qs_list_to_perform_or_operation ):

    final_qs = qs_list_to_perform_or_operation [0]
    for i in range(len(qs_list_to_perform_or_operation ) - 1):
        final_qs = final_qs | qs_list[i + 1]
    return final_qs

all_possible_filter_dict_list_for_a_condition
   = get_all_possible_filter_dict_list_for_a_condition(field_list)
qs_list_to_perform_or_operation = get_qs_list_to_perform_or_operation(all_possible_filter_dict_list_for_a_condition)
final_qs_to_filter_multiple_fields_with_same_condtion = get_qs_to_filter_fields_with_more_than_1_none(qs_list_to_perform_or_operation)


问:
C# PDF Printing Library
Are there any free libraries that would "print" to a PDF without actually having to install a PDF printer on the system.  I want something that can be completely self contained in my application.  The reason I say I want it to "print" is that I've tried and tried to find a solution for directly converting from HTML with CSS to PDF, but it does't seem very possible.  So I want to use the System.Windows.Forms.WebBrowser control to render the page first and then output that rendering to PDF.  I just don't want the user to be required to install a PDFPrinter.</p>

答:
Does it have to be free? Last time I looked at ABCpdf it looked quite good, and claims to support css (here).

HTMLDOC should support css at some point, but last time I checked the css stuff was still in beta. And has been for "some time"; I've given up waiting... It isn't .NET, but you can use Process to invoke it.

OwnerDisplayName: Adam Haile

ContentLicense: CC BY-SA 2.5

Title: C# PDF Printing Library

OwnerDisplayName: Marc Gravell


问:
Compiling a static executable with CMake
for a project I need to create an executable that includes all the libraries that I used (opencv, cgal) in order to execute it on a computer that has not those libraries. Currently, this is my CMakeLists.txt (I use linux).

```<code>cmake_minimum_required(VERSION 2.8)
#set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -Wall -O2")
project( labeling )
set(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
add_library(OpenCV STATIC IMPORTED)
add_library(CGAL STATIC IMPORTED COMPONENTS Core)
add_library(GMP STATIC IMPORTED)
find_package(OpenCV REQUIRED)
find_package(CGAL QUIET COMPONENTS Core )
find_library(GMP_LIBRARY gmp /usr/lib)

include(src)
include( ${CGAL_USE_FILE} )
include( CGAL_CreateSingleSourceCGALProgram )

set(EXECUTABLE_OUTPUT_PATH ../bin)
set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++")

include_directories( src )
include_directories( ${OpenCV_INCLUDE_DIRS} )

file(GLOB_RECURSE nei_SRC "src/*.cpp")
add_executable( nei_segmentation ${nei_SRC})
target_link_libraries( nei_segmentation ${OpenCV_LIBS} ${GMP_LIBRARY})
</code>```

In such a way only GMP and some other c++ libraries are included in my executable. My question is: How can I create a makefile in order to automatically including all the libraries in a static manner and creating only a "big" executable that contains all the libraries? Can you help me?

答:
Add these lines after add_executable(MyExec "main.c") (for example) :

target_link_libraries(MyExec PUBLIC "-static")

or before: link_libraries("-static")

Body:
for a project I need to create an executable that includes all the libraries that I used (opencv, cgal) in order to execute it on a computer that has not those libraries. Currently, this is my CMakeLists.txt (I use linux).

cmake_minimum_required(VERSION 2.8)
#set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -Wall -O2")
project( labeling )
set(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
add_library(OpenCV STATIC IMPORTED)
add_library(CGAL STATIC IMPORTED COMPONENTS Core)
add_library(GMP STATIC IMPORTED)
find_package(OpenCV REQUIRED)
find_package(CGAL QUIET COMPONENTS Core )
find_library(GMP_LIBRARY gmp /usr/lib)

include(src)
include( ${CGAL_USE_FILE} )
include( CGAL_CreateSingleSourceCGALProgram )

set(EXECUTABLE_OUTPUT_PATH ../bin)
set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++")

include_directories( src )
include_directories( ${OpenCV_INCLUDE_DIRS} )

file(GLOB_RECURSE nei_SRC "src/*.cpp")
add_executable( nei_segmentation ${nei_SRC})
target_link_libraries( nei_segmentation ${OpenCV_LIBS} ${GMP_LIBRARY})

In such a way only GMP and some other c++ libraries are included in my executable. My question is: How can I create a makefile in order to automatically including all the libraries in a static manner and creating only a "big" executable that contains all the libraries? Can you help me?

ContentLicense: CC BY-SA 4.0


问:
How to add miliseconds to my timer?
I try to put milliseconds to my timer, but they act like seconds instead of milliseconds. They're already after the seconds. But there not acting like the milliseconds. Also I have been trying to make the percentage see how far the countdown is. So how can I fix this?

This is the link with the whole script: http://embed.plnkr.co/hUeAAzBBszAnCq7FdeGO/

// Code goes here
window.addEventListener('load', start);

function start() {
  countdown();
}

function isNumberKey(evt) {
  var charCode = (evt.which) ? evt.which : event.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57))
  //if charcode is keycode more then 31 and keycode less then 48 and more then 57 return false
  {
    return false;
    //aren't numbers
  } else {
    return true;
    //only can type numbers
  }
}

function countdown(val) {
  var counter = parseInt(val);
  var myVar = setInterval(function() {
    if (counter >= 0) {
      document.getElementById("timer").innerHTML = Math.floor(counter / 60) + ":" + ("0" + Math.floor(counter) % 60).slice(-2) + "." + Math.floor((counter % 1000) * 1000) / 1000;
      //counter/60 calculates the minute and counter%60 calculates the seconds.
      counter--;
    }
    if (counter < 0) {
      document.getElementById("timer").innerHTML = "That was the countdown";
    }
  }, 1000)
}

var stop = 0;

function decrease() {
  var percent = Number($('#counter span').text());
  if (percent > stop) {
    $('#counter span').text(--percent);
    var t = setTimeout(decrease, 1000);
  }
}

setTimeout(decrease, 1000);

function count() {
  var input = document.getElementById("number_input").value;
  countdown(input);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

only numbers please :
<input type="text" placeholder="type in a number" id="number_input" onkeypress="return isNumberKey(event)" />
<button onclick="count()">tel af</button>

<p id="timer">0</p>
<div id="counter">
  <p><span>100</span>%</p>
</div></code>```

答:
your timeout is setup wrongly, it been setup for every 1 sec which is causing the problem.

1000 = 1 sec
100 = 100 milli sec... now adjust it as per your need

The way you are managing counter needs to be isolated or change the HTML change logic differntly

Title: How to add miliseconds to my timer?

Body:
I try to put milliseconds to my timer, but they act like seconds instead of milliseconds. They're already after the seconds. But there not acting like the milliseconds. Also I have been trying to make the percentage see how far the countdown is. So how can I fix this?

This is the link with the whole script: http://embed.plnkr.co/hUeAAzBBszAnCq7FdeGO/

// Code goes here
window.addEventListener('load', start);

function start() {
  countdown();
}

function isNumberKey(evt) {
  var charCode = (evt.which) ? evt.which : event.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57))
  //if charcode is keycode more then 31 and keycode less then 48 and more then 57 return false
  {
    return false;
    //aren't numbers
  } else {
    return true;
    //only can type numbers
  }
}

function countdown(val) {
  var counter = parseInt(val);
  var myVar = setInterval(function() {
    if (counter >= 0) {
      document.getElementById("timer").innerHTML = Math.floor(counter / 60) + ":" + ("0" + Math.floor(counter) % 60).slice(-2) + "." + Math.floor((counter % 1000) * 1000) / 1000;
      //counter/60 calculates the minute and counter%60 calculates the seconds.
      counter--;
    }
    if (counter < 0) {
      document.getElementById("timer").innerHTML = "That was the countdown";
    }
  }, 1000)
}

var stop = 0;

function decrease() {
  var percent = Number($('#counter span').text());
  if (percent > stop) {
    $('#counter span').text(--percent);
    var t = setTimeout(decrease, 1000);
  }
}

setTimeout(decrease, 1000);

function count() {
  var input = document.getElementById("number_input").value;
  countdown(input);
}

only numbers please :
<input type="text" placeholder="type in a number" id="number_input" onkeypress="return isNumberKey(event)" />
<button onclick="count()">tel af</button>

0

100%


问:
How to change the size of tablayout icon
I'm using a tablayout with a viewpager. The icons namely notification icon and message icon change when there is a new message or notification. I replace the icons with the similar icon but with a badge. This is what the icons look like without the bage:

Now the issue is that the icons with the badge appear smaller in size as shown in the image below

Though the difference is very small but I have to get the icons the same size. I figured the icons are the same size but the badges take up the space and make the icons smaller. I'm using tabLayout.GetTabAt(1).SetIcon(Resource.Drawable.messageWhite);to set the icons.
I tried to use custom view which fix the problem but then I have issue changing the custom view dynamically.
Is there a way I can define the size of the icon using setIcon' property?

答:
You have to get the view of your tab item first.After that you can set your icon in respective imageview in your custom tab item view.</p>

```<code>View v = LayoutInflater.from(this).inflate(R.layout.tab_item_horizontal,null);
    tabLayout.getTabAt(0).setCustomView(v);
    TextView text_tab_item = (TextView)v.findViewById(R.id.text_tab_item);
    ImageView img_tabtxt = (ImageView)v.findViewById(R.id.img_tabtxt);
    img_tabtxt.setImageResource(R.drawable.request_tab_white);
    text_tab_item.setText("Members");
    text_tab_item.setTextColor(getResources().getColor(R.color.white_color));
</code>```

Body:
You have to get the view of your tab item first.After that you can set your icon in respective imageview in your custom tab item view.

View v = LayoutInflater.from(this).inflate(R.layout.tab_item_horizontal,null);
    tabLayout.getTabAt(0).setCustomView(v);
    TextView text_tab_item = (TextView)v.findViewById(R.id.text_tab_item);
    ImageView img_tabtxt = (ImageView)v.findViewById(R.id.img_tabtxt);
    img_tabtxt.setImageResource(R.drawable.request_tab_white);
    text_tab_item.setText("Members");
    text_tab_item.setTextColor(getResources().getColor(R.color.white_color));


问:
Is there a better way to do these mySql updates?
```<code>    executeSQL("UPDATE records SET played = played + 1 WHERE player IN " + generateClause(all));
    executeSQL("UPDATE records SET wins = wins + 1 WHERE player IN " + generateClause(r.getWinners()));
    executeSQL("UPDATE records SET winrate = ((wins/played) * 1000) WHERE player IN " + generateClause(all));
</code>```

Basically i'm trying to update the records of the players after a match. My program works as expected but it seems to require 3 queries, i'd want to do just one if possible since i've figured out that less queries drastically reduces the runtime of the app, even if the modifications to the db are the same.

My queries are as follows...
1) increase the "played" count for all the players that have played
2) add a win for the players that have won
3) calculate the winrate for all players that have just played

any advice would be appreciated

答:
I suppose that generateClause(all) contains all players, and the other one contains only the winners, right?...

I'd suggest this:

```<code>UPDATE ... SET wins = wins + player IN( list of winners ),
              played = played+1,
              winrate = 1000*(wins + player IN( list of winners ))/(played+1)
WHERE player IN (list of players)
</code>```

I just checked: IN seems to be properly optimized here.

However, if you use a more recent version of MySQL, remember that you can create expression (ie, virtual) columns, and you could make winrate a virtual column. These can be indexed, too!

EDIT:

"seq" contains 1M rows.

```<code>SELECT sum(id) FROM seq
SELECT sum(id IN (list of 1000 numbers)) FROM seq
</code>```

The difference in execution time is 0.3s, which means IN(1000 numbers) takes 0.3 µs, which means MySQL must use some form of hash to optimize it. So, don't worry about repeating your IN() three times... It will be fast.

Body:
    executeSQL("UPDATE records SET played = played + 1 WHERE player IN " + generateClause(all));
    executeSQL("UPDATE records SET wins = wins + 1 WHERE player IN " + generateClause(r.getWinners()));
    executeSQL("UPDATE records SET winrate = ((wins/played) * 1000) WHERE player IN " + generateClause(all));

Basically i'm trying to update the records of the players after a match. My program works as expected but it seems to require 3 queries, i'd want to do just one if possible since i've figured out that less queries drastically reduces the runtime of the app, even if the modifications to the db are the same.

My queries are as follows...
1) increase the "played" count for all the players that have played
2) add a win for the players that have won
3) calculate the winrate for all players that have just played

any advice would be appreciated

Body:
I suppose that generateClause(all) contains all players, and the other one contains only the winners, right?...

I'd suggest this:

UPDATE ... SET wins = wins + player IN( list of winners ),
              played = played+1,
              winrate = 1000*(wins + player IN( list of winners ))/(played+1)
WHERE player IN (list of players)

I just checked: IN seems to be properly optimized here.

However, if you use a more recent version of MySQL, remember that you can create expression (ie, virtual) columns, and you could make winrate a virtual column. These can be indexed, too!

EDIT:

"seq" contains 1M rows.

SELECT sum(id) FROM seq
SELECT sum(id IN (list of 1000 numbers)) FROM seq

The difference in execution time is 0.3s, which means IN(1000 numbers) takes 0.3 µs, which means MySQL must use some form of hash to optimize it. So, don't worry about repeating your IN() three times... It will be fast.


问:
RecyclerView Multiple Layout View(s) in an Adapter class
Here is what I have achieved ? 3 different sections, 10 different items in each section.

Here is the tutorial link I am following and below is the Screenshot:

Trying to show different Views for each and every Section. Like:

For Section 1 (layout_1.xml)

For Section 2 (layout_2.xml)

For Section 3 (layout_3.xml)

But showing layout view of layout_1.xml in every Section... (Section 1, 2, 3)

May I know where I am doing mistake in my code, what I have missed ?

```<code>public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> {

    private ArrayList<SingleItemModel> itemsList;
    private Context mContext;

    public SectionListDataAdapter(Context context, ArrayList<SingleItemModel> itemsList) {
        this.itemsList = itemsList;
        this.mContext = context;
    }

    @Override
    public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

        switch (i) {

            case 0:
                View viewONE = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_1, null, false);
                SingleItemRowHolder rowONE = new SingleItemRowHolder(viewONE);
                return rowONE;

            case 1:
                View viewTWO = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_2, null, false);
                SingleItemRowHolder rowTWO = new SingleItemRowHolder(viewTWO);
                return rowTWO;

            case 2:
                View viewTHREE = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_3, null, false);
                SingleItemRowHolder rowTHREE = new SingleItemRowHolder(viewTHREE);
                return rowTHREE;

        }

        return null;

    }

    @Override
    public void onBindViewHolder(SingleItemRowHolder holder, int i) {

        SingleItemModel singleItem = itemsList.get(i);
        holder.tvTitle.setText(singleItem.getName());
    }

    @Override
    public int getItemCount() {
        return (null != itemsList ? itemsList.size() : 0);
    }

    public class SingleItemRowHolder extends RecyclerView.ViewHolder {

        protected TextView tvTitle;

        protected ImageView itemImage;

        public SingleItemRowHolder(View view) {
            super(view);

            this.tvTitle = (TextView) view.findViewById(R.id.tvTitle);
            this.itemImage = (ImageView) view.findViewById(R.id.itemImage);

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Toast.makeText(v.getContext(), tvTitle.getText(), Toast.LENGTH_SHORT).show();

                }
            });

        }

    }

}
</code>```

答:
All you need to do is override the method getItemViewType() inside your adapter.

You can write it as:

```<code> @Override
    public int getItemViewType(int position) {
        if (position < 0) {
            return 0;
        } else if(position < 20) {
            return 1;
        } else {
          return 2;
        }
    }
</code>```

Now the above logic works if your itemsList ArrayList have first 10 items of section 1, next 10 items of section 2, and last 10 items of section 3.

If that is not the case then you can have an integer field sectionNumber in your SingleItemModel class which specifies the section number in which that model belongs to. Now you can modify the method getItemViewType() as

```<code>@Override
public int getItemViewType(int position) {
    SingleItemModel singleItemModel = itemsList.get(position);
    if (singleItemModel.getSection() == 1) {
        return 0;
    } else if(singleItemModel.getSection() == 2) {
        return 1;
    } else {
      return 2;
    }
}
</code>```

Body:
Here is what I have achieved ? 3 different sections, 10 different items in each section.

Here is the tutorial link I am following and below is the Screenshot:

Trying to show different Views for each and every Section. Like:

For Section 1 (layout_1.xml)

For Section 2 (layout_2.xml)

For Section 3 (layout_3.xml)

But showing layout view of layout_1.xml in every Section... (Section 1, 2, 3)

May I know where I am doing mistake in my code, what I have missed ?

public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> {

    private ArrayList<SingleItemModel> itemsList;
    private Context mContext;

    public SectionListDataAdapter(Context context, ArrayList<SingleItemModel> itemsList) {
        this.itemsList = itemsList;
        this.mContext = context;
    }

    @Override
    public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

        switch (i) {

            case 0:
                View viewONE = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_1, null, false);
                SingleItemRowHolder rowONE = new SingleItemRowHolder(viewONE);
                return rowONE;

            case 1:
                View viewTWO = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_2, null, false);
                SingleItemRowHolder rowTWO = new SingleItemRowHolder(viewTWO);
                return rowTWO;

            case 2:
                View viewTHREE = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_3, null, false);
                SingleItemRowHolder rowTHREE = new SingleItemRowHolder(viewTHREE);
                return rowTHREE;

        }

        return null;

    }

    @Override
    public void onBindViewHolder(SingleItemRowHolder holder, int i) {

        SingleItemModel singleItem = itemsList.get(i);
        holder.tvTitle.setText(singleItem.getName());
    }

    @Override
    public int getItemCount() {
        return (null != itemsList ? itemsList.size() : 0);
    }

    public class SingleItemRowHolder extends RecyclerView.ViewHolder {

        protected TextView tvTitle;

        protected ImageView itemImage;

        public SingleItemRowHolder(View view) {
            super(view);

            this.tvTitle = (TextView) view.findViewById(R.id.tvTitle);
            this.itemImage = (ImageView) view.findViewById(R.id.itemImage);

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Toast.makeText(v.getContext(), tvTitle.getText(), Toast.LENGTH_SHORT).show();

                }
            });

        }

    }

}

Body:
All you need to do is override the method getItemViewType() inside your adapter.

You can write it as:

 @Override
    public int getItemViewType(int position) {
        if (position < 0) {
            return 0;
        } else if(position < 20) {
            return 1;
        } else {
          return 2;
        }
    }

Now the above logic works if your itemsList ArrayList have first 10 items of section 1, next 10 items of section 2, and last 10 items of section 3.

If that is not the case then you can have an integer field sectionNumber in your SingleItemModel class which specifies the section number in which that model belongs to. Now you can modify the method getItemViewType() as

@Override
public int getItemViewType(int position) {
    SingleItemModel singleItemModel = itemsList.get(position);
    if (singleItemModel.getSection() == 1) {
        return 0;
    } else if(singleItemModel.getSection() == 2) {
        return 1;
    } else {
      return 2;
    }
}


问:
How do i remove a row from an icefaces datatable?
I have a simple ice:dataTable which has 2 columns, one an action column the other a string representing a regular expression.  The action column has as its header an add action, and for each row a remove action.  I dont really care how this works as long as it does.  Right now I am attempting to mimic the icefaces composite component editableTable which requires you to select a row at which point the actions get rendered for that row then when you click an action it is applied to the selected row.  So in my attempt to make this work, I created simple datatable with an rowSelector that sets my item.selected for the selected row:

```<code>    <ice:dataTable value="#{configuration.selectedTagPositiveRegexes}"
      var="item">
      <ice:column>
        <ice:rowSelector value="#{item.selected}" />
        <f:facet name="header">
          <ice:commandLink styleClass="linkBlue"
            action="#{configuration.tagRegexAdd}">
            <ice:outputText value="Add" />
          </ice:commandLink>
        </f:facet>
        <ice:commandLink styleClass="linkBlue"
          action="#{configuration.tagRegexRemove}"
          rendered="#{item.selected}">
          <ice:outputText value="Remove" />
        </ice:commandLink>
      </ice:column>
      <ice:column>
        <f:facet name="header">
          <ice:outputText value="Regular Expression" />
        </f:facet>
        <ice:inputText value="#{item.object}" size="100" />
      </ice:column>
    </ice:dataTable>
</code>```

Then in my backing bean, I have these 2 methods:

```<code>public void tagRegexAdd() {
    log.debug( "add a new regex" );
    for ( SelectableRow<String> row : selectedTagPositiveRegexes ) {
        row.selected = false;
    }
    selectedTagPositiveRegexes.add( 0, new SelectableRow<String>( "", true ) );
}

public void tagRegexRemove() {
    log.debug( "remove an existing regex" );
    int i = 0;
    int selectedIndex = -1;
    for ( SelectableRow<String> row : selectedTagPositiveRegexes ) {
        if ( row.selected ) {
            selectedIndex = i;
            row.selected = false;
        }
        i++;
    }
    if ( selectedIndex >= 0 ) {
        selectedTagPositiveRegexes.remove( selectedIndex );
    }
}
</code>```

What I notice happening as I step through this code is that the getter for selectedTagPositiveRegexes is getting called 3 times when the remove action is clicked, followed by the actual remove method followed by 1 more call to the getter at which point the browser receives a response that does what I want.  However, some event must have been queued by something because after returning the response, the getter gets called 3 more times after which the item after that item that was removed gets replaced with the item that was removed.  I have no idea what is going on here and must have a serious misunderstanding as to how this is used, but my assumption was that the datatable, being backed by a list of elements should obtain its content from that list.  That way if i add or remove to/from the list, the datatable should represent the new state.  But I appear to be terribly wrong in that assumption.  Any insight whatsoever as to how this is actually working will be greatly appreciated.

答:
I haven't tried it that way, but this has worked for me.

In your managed bean, create a property of type HtmlDataTable and then use the binding attribute of ice:dataTable to point to it.  Now in the callback, do this:

```<code>RowClass row=(RowClass)htmlTable.getRowData();
rowList.remove(row);
</code>```

In some cases I've had to run this to make it update correctly.  I believe this only when you have nested tables:

```<code>htmlTable.getChildren().clear();
</code>```

Body:
I have a simple ice:dataTable which has 2 columns, one an action column the other a string representing a regular expression.  The action column has as its header an add action, and for each row a remove action.  I dont really care how this works as long as it does.  Right now I am attempting to mimic the icefaces composite component editableTable which requires you to select a row at which point the actions get rendered for that row then when you click an action it is applied to the selected row.  So in my attempt to make this work, I created simple datatable with an rowSelector that sets my item.selected for the selected row:

    <ice:dataTable value="#{configuration.selectedTagPositiveRegexes}"
      var="item">
      <ice:column>
        <ice:rowSelector value="#{item.selected}" />
        <f:facet name="header">
          <ice:commandLink styleClass="linkBlue"
            action="#{configuration.tagRegexAdd}">
            <ice:outputText value="Add" />
          </ice:commandLink>
        </f:facet>
        <ice:commandLink styleClass="linkBlue"
          action="#{configuration.tagRegexRemove}"
          rendered="#{item.selected}">
          <ice:outputText value="Remove" />
        </ice:commandLink>
      </ice:column>
      <ice:column>
        <f:facet name="header">
          <ice:outputText value="Regular Expression" />
        </f:facet>
        <ice:inputText value="#{item.object}" size="100" />
      </ice:column>
    </ice:dataTable>

Then in my backing bean, I have these 2 methods:

public void tagRegexAdd() {
    log.debug( "add a new regex" );
    for ( SelectableRow<String> row : selectedTagPositiveRegexes ) {
        row.selected = false;
    }
    selectedTagPositiveRegexes.add( 0, new SelectableRow<String>( "", true ) );
}

public void tagRegexRemove() {
    log.debug( "remove an existing regex" );
    int i = 0;
    int selectedIndex = -1;
    for ( SelectableRow<String> row : selectedTagPositiveRegexes ) {
        if ( row.selected ) {
            selectedIndex = i;
            row.selected = false;
        }
        i++;
    }
    if ( selectedIndex >= 0 ) {
        selectedTagPositiveRegexes.remove( selectedIndex );
    }
}

What I notice happening as I step through this code is that the getter for selectedTagPositiveRegexes is getting called 3 times when the remove action is clicked, followed by the actual remove method followed by 1 more call to the getter at which point the browser receives a response that does what I want.  However, some event must have been queued by something because after returning the response, the getter gets called 3 more times after which the item after that item that was removed gets replaced with the item that was removed.  I have no idea what is going on here and must have a serious misunderstanding as to how this is used, but my assumption was that the datatable, being backed by a list of elements should obtain its content from that list.  That way if i add or remove to/from the list, the datatable should represent the new state.  But I appear to be terribly wrong in that assumption.  Any insight whatsoever as to how this is actually working will be greatly appreciated.

Body:
I haven't tried it that way, but this has worked for me.

In your managed bean, create a property of type HtmlDataTable and then use the binding attribute of ice:dataTable to point to it.  Now in the callback, do this:

RowClass row=(RowClass)htmlTable.getRowData();
rowList.remove(row);

In some cases I've had to run this to make it update correctly.  I believe this only when you have nested tables:

htmlTable.getChildren().clear();


答:
You can use the:

```<code>$id = (int)Db::getInstance()->Insert_ID();
</code>```

For example, in the Cart class:

```<code>$last_id = (int)Db::getInstance()->Insert_ID();
</code>```

I also recommend the use of the function insert, for example in the Carrier class:

```<code>$values = array();
foreach ($shops as $id_shop) {
      $values[] = array(
           'id_carrier' => (int)$this->id,
           'id_tax_rules_group' => (int)$id_tax_rules_group,
           'id_shop' => (int)$id_shop,
       );
}
$res = Db::getInstance()->insert('carrier_tax_rules_group_shop', $values);
</code>```

Then use the Insert_ID to get the last one.

Title: PrestaShop, get ID when insert in DB

Body:
You can use the:

$id = (int)Db::getInstance()->Insert_ID();

For example, in the Cart class:

$last_id = (int)Db::getInstance()->Insert_ID();

I also recommend the use of the function insert, for example in the Carrier class:

$values = array();
foreach ($shops as $id_shop) {
      $values[] = array(
           'id_carrier' => (int)$this->id,
           'id_tax_rules_group' => (int)$id_tax_rules_group,
           'id_shop' => (int)$id_shop,
       );
}
$res = Db::getInstance()->insert('carrier_tax_rules_group_shop', $values);

Then use the Insert_ID to get the last one.


答:
PrestaShop's DB class provides the last inserted id via

```<code>Db::getInstance()->Insert_ID();
</code>```

method.

Title: PrestaShop, get ID when insert in DB

Body:
PrestaShop's DB class provides the last inserted id via

Db::getInstance()->Insert_ID();

method.


问:
shuffle action in ranges-v3
Since the ranges-library is up for inclusion into the standard I was toying around with it for a while and I have some problems with very basic concepts.

The toy example I am struggling with is this:

```<code>#include <iostream>
#include <range/v3/all.hpp>
using namespace ranges;

int main (int argc, char const* argv[]) {
    auto v = view::iota(1, 10);
    std::default_random_engine gen;
    auto t = action::push_back(view::iota(0, 10)) | action::shuffle(gen);
    std::cout << t << "\n";
}
</code>```

The fact that it is not printable kind of suggests to me that t is not really a proper range. Unfortunately the documentation (where there is any) really abuses auto, so I do not know what is going on. What do I have to do, why do I have to do it (and in case anyone does know: how is the result type going to be documented (imo proxy objects and auto don't mix well - see the Eigen library as an example)).

My second question is related to the cargo-culted action::push_back. If I omit it I get a concept error telling me that the iota-generated view needs to be mutable. Obviously a view is by design immutable, so I get the problem here, but is "pushing nothing" really the preferred way to lift things into a mutable/stateful object or are there alternatives?

Best,
Richard

答:
Your t instance is an action, not a range. That's the main reason why it isn't <<able.

You can see this by applying it to multiple containers, e.g.

```<code>#include <iostream>
#include <experimental/iterator>
#include <range/v3/all.hpp>
using namespace ranges;

int main (int argc, char const* argv[]) {
    std::default_random_engine gen;
    auto t = action::push_back(view::iota(0, 10)) | action::shuffle(gen);
    auto v1 = std::vector<int>{} | t;
    auto v2 = std::vector<int>{} | t;
    auto v3 = std::vector<int>{} | t;
    auto v4 = std::vector<int>{} | t;
    std::copy(v1.begin(), v1.end(), std::experimental::make_ostream_joiner(std::cout, ", "));
    std::cout << "\n";
    std::copy(v2.begin(), v2.end(), std::experimental::make_ostream_joiner(std::cout, ", "));
    std::cout << "\n";
    std::copy(v3.begin(), v3.end(), std::experimental::make_ostream_joiner(std::cout, ", "));
    std::cout << "\n";
    std::copy(v4.begin(), v4.end(), std::experimental::make_ostream_joiner(std::cout, ", "));
    std::cout << "\n";
}
</code>```

Title: shuffle action in ranges-v3

Body:
Since the ranges-library is up for inclusion into the standard I was toying around with it for a while and I have some problems with very basic concepts.

The toy example I am struggling with is this:

#include <iostream>
#include <range/v3/all.hpp>
using namespace ranges;

int main (int argc, char const* argv[]) {
    auto v = view::iota(1, 10);
    std::default_random_engine gen;
    auto t = action::push_back(view::iota(0, 10)) | action::shuffle(gen);
    std::cout << t << "\n";
}

The fact that it is not printable kind of suggests to me that t is not really a proper range. Unfortunately the documentation (where there is any) really abuses auto, so I do not know what is going on. What do I have to do, why do I have to do it (and in case anyone does know: how is the result type going to be documented (imo proxy objects and auto don't mix well - see the Eigen library as an example)).

My second question is related to the cargo-culted action::push_back. If I omit it I get a concept error telling me that the iota-generated view needs to be mutable. Obviously a view is by design immutable, so I get the problem here, but is "pushing nothing" really the preferred way to lift things into a mutable/stateful object or are there alternatives?

Best,
Richard

Body:
Your t instance is an action, not a range. That's the main reason why it isn't <<able.

You can see this by applying it to multiple containers, e.g.

#include <iostream>
#include <experimental/iterator>
#include <range/v3/all.hpp>
using namespace ranges;

int main (int argc, char const* argv[]) {
    std::default_random_engine gen;
    auto t = action::push_back(view::iota(0, 10)) | action::shuffle(gen);
    auto v1 = std::vector<int>{} | t;
    auto v2 = std::vector<int>{} | t;
    auto v3 = std::vector<int>{} | t;
    auto v4 = std::vector<int>{} | t;
    std::copy(v1.begin(), v1.end(), std::experimental::make_ostream_joiner(std::cout, ", "));
    std::cout << "\n";
    std::copy(v2.begin(), v2.end(), std::experimental::make_ostream_joiner(std::cout, ", "));
    std::cout << "\n";
    std::copy(v3.begin(), v3.end(), std::experimental::make_ostream_joiner(std::cout, ", "));
    std::cout << "\n";
    std::copy(v4.begin(), v4.end(), std::experimental::make_ostream_joiner(std::cout, ", "));
    std::cout << "\n";
}


问:
Android Studio - Can't connect to device (Samsung Galaxy S7)
I've got an issue while trying to run an app on android studio. The list of connected device will always remain empty. Thus I can't deploy my app on the phone. The OS is Windows 10.

I already take these steps:

installed driver from Samsung. The device is shown in device manager and I've got access from windows to it

Swapping USB Ports a dozen times

Developer Setting on

Switched Media Port both Camera (Ptp) and Media Device (MTP)

Does anyone has further tips?

答: Look if USB debugging is enable in the developer options of your smartphone.


问:
Django user registration where username becomes "firstname.lastname"
I want to make a registration page for my django application in order to 'request' access. In other words they submit the form and it creates the user and user.is_active = False. Then as admin I can approve their access.

However I do not want them to be able to put in their username. Instead i want their username to be firstname.lastname. In the unlikely case of the same name people trying to sign up (app is for small number of people) - then a number will need adding on the end.

I do this at the moment using a signup view:

```<code>def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)

        if form.is_valid():
            form.save()

            first_name = form.cleaned_data.get('first_name')
            last_name = form.cleaned_data.get('last_name')
            raw_password = form.cleaned_data.get('password1')
            username = form.cleaned_data.get('username')

            user = authenticate(username=username, password=raw_password)

            user.is_active = False
            user.save()
            return render(request, 'registration/signedup.html', {'user': user})
        else:
            return render(request, 'registration/signup.html', {'form': form, 'invalid': 'Please try again.'})
    else:
        form = SignUpForm()
        return render(request, 'registration/signup.html', {'form': form})
</code>```

and a signup form:

```<code>class SignUpForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
    last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
    email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', )
</code>```

and this as the html for my signup page:

```<code><form method="post"  autocomplete="off">
  {% csrf_token %}

   <table class='login' width='400'>
   {% for field in form %}

   <tr>
     <td width='200' class='loginrow'>{{ field.label_tag }}</td>
     <td width='180' class='loginrow'>{{ field }}</td>
       {% for error in field.errors %}
      <p style="color: red">{{ error }}</p>
       {% endfor %}
   </tr>
   {% endfor %}
</table>

 <button type="submit">Sign up</button>

</form>
</code>```

I have tried to remove username from my form field, and then create username variable as firs_name+'.'+last_name in my view by the user = authenticate() returns none.

Is there a way I can automatically produce a username without the user submitting one? - I was also thinking of using javascript function in the html page, and a hidden 'username' input tag which concats the names, but I can't get this to work either.

Thanks

答:
You could try something like:</p>

```<code>my_data = dict(request.POST.iterlists())
my_data['username'] = my_data['firstname'] + '.' + my_data['lastname']

form = SignUpForm(my_data)

if form.is_valid():
            form.save()
...
</code>```

Body:
I want to make a registration page for my django application in order to 'request' access. In other words they submit the form and it creates the user and user.is_active = False. Then as admin I can approve their access.

However I do not want them to be able to put in their username. Instead i want their username to be firstname.lastname. In the unlikely case of the same name people trying to sign up (app is for small number of people) - then a number will need adding on the end.

I do this at the moment using a signup view:

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)

        if form.is_valid():
            form.save()

            first_name = form.cleaned_data.get('first_name')
            last_name = form.cleaned_data.get('last_name')
            raw_password = form.cleaned_data.get('password1')
            username = form.cleaned_data.get('username')

            user = authenticate(username=username, password=raw_password)

            user.is_active = False
            user.save()
            return render(request, 'registration/signedup.html', {'user': user})
        else:
            return render(request, 'registration/signup.html', {'form': form, 'invalid': 'Please try again.'})
    else:
        form = SignUpForm()
        return render(request, 'registration/signup.html', {'form': form})

and a signup form:

class SignUpForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
    last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
    email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', )

and this as the html for my signup page:

<form method="post"  autocomplete="off">
  {% csrf_token %}

   {% for field in form %}

     {{ field.label_tag }}
     {{ field }}
       {% for error in field.errors %}

{{ error }}

       {% endfor %}

   {% endfor %}

 <button type="submit">Sign up</button>

</form>

I have tried to remove username from my form field, and then create username variable as firs_name+'.'+last_name in my view by the user = authenticate() returns none.

Is there a way I can automatically produce a username without the user submitting one? - I was also thinking of using javascript function in the html page, and a hidden 'username' input tag which concats the names, but I can't get this to work either.

Thanks

Body:
You could try something like:

my_data = dict(request.POST.iterlists())
my_data['username'] = my_data['firstname'] + '.' + my_data['lastname']

form = SignUpForm(my_data)

if form.is_valid():
            form.save()
...


问:
Wait for window to reload when scrolling web page in VBA
I have written a VBA macro to count the (approximate) number of images returned for a Google search of a specific term. By approximate I mean that the program should count the number of images returned, scroll down to load some more (where applicable) up to a max of 400 images counted. Here's the (simplified) code:

```<code>Sub GoogleCount ()

'''
'[Code to construct the URL ('fullUrl')]
'''
    Set objIE = New InternetExplorer
    objIE.navigate fullUrl
    Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop
    Set currPage = objIE.document
    'Count images returned
    newNum = currPage.getElementById("rg_s").getElementsByTagName("IMG").Length
    'Scroll down until count = 400 (max) or no change in value
    Do While newNum >= 100 And newNum < 400 And newNum <> oldNum
        oldNum = newNum
        currPage.parentWindow.scrollBy 0, 100000
        Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop
        newNum = currPage.getElementById("rg_s").getElementsByTagName("IMG").Length
    Loop

'''
'[Code to paste the value of newNum into my workbook, and do some other progress reporting]
'''
End Sub
</code>```

I'm unhappy about scrolling, it feels very 'manual', especially when you are scrolling by a fixed value (any point making it dynamic? i.e. finding the end of the page and scrolling to there).

But the main problem is that it doesn't work: when I execute the code, it counts the first 100 (or fewer) images fine. But when it's supposed to scroll and count some more, I get the value of 100 returned. Slowly stepping through the code with F8 I get the proper numbers (max 400), which leads me to conclude that the code is running through too quickly (I may be wrong).

To slow the code down I tried adding the objIE.readyState check loop, but because I'm only scrolling I don't think it counts as the page 're-loading' so the loop is ineffective in waiting for the new images to load.

I've thought about adding in a time delay instead. I am already employing

```<code>Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
</code>```

elsewhere in the worksheet - so, I could add as small as a millisecond-order delay.

But I really want to avoid using that, as this code runs for c. 50 different searches and takes long enough to execute already, adding in fixed delays that are long enough to accommodate slow connection speeds would not be ideal. Also, internet speeds vary so much that a fixed delay is very unreliable - I could carry out some kind of connection test to get a better ball-park figure, but the best option is obviously only to wait as long as you have to.

Or better still find a different way of counting the images, preferably one which doesn't involve re-loading the page 4 times!
Any ideas?

NB. If you want to debug yourself, a good image search to set fullUrl to might be https://www.google.com/search?q=stack overflow|exchange&tbm=isch&source=lnt&tbs=isz:ex,iszw:312,iszh:390 as it returns >100 images but fewer than 400 so you can test all aspects of the code

答:
Through further research I've come up with this approach:

```<code>Dim myDiv As HTMLDivElement: Set myDiv = currPage.getElementById("fbar")
Dim elemRect As IHTMLRect: Set elemRect = myDiv.getBoundingClientRect
Do Until elemRect.bottom > 0
    currPage.parentWindow.scrollBy 0, 10000
    Set elemRect = myDiv.getBoundingClientRect
Loop
myDiv.ScrollIntoView
</code>```

Where currPage is the HTML webpage (Dim currPage As HTMLDocument) and myDiv is a particular element. The type is not important, but it should be noted that myDiv is always located at the bottom of the document and is only loaded once everything else has been. So for Google images that's the help bar, which you only get to after scrolling through all the image results.

How it works

The code works as follows: myDiv.getBoundingClientRect is a way of checking whether an element is visible in the browser - that's why we need to look at an element at the bottom of the page, as if we scroll until that becomes visible, then everything else must have loaded too.

That's of course where the Do Until...Loop comes from; we loop until the elemRect.bottom value is not zero (as when the element is not in view, it's zero, once it's in view it becomes a non-zero number). More info on that see here

Finally, use a myDiv.ScrollIntoView to get the browser right to the bottom; this is necessary because the BoundingClientRect is visible slightly before the element is on screen, so we need to scroll the last bit in order to load the final images.

Why not just use ScrollIntoView form the start? It doesn't work, since the element hasn't loaded yet.

Body:
I have written a VBA macro to count the (approximate) number of images returned for a Google search of a specific term. By approximate I mean that the program should count the number of images returned, scroll down to load some more (where applicable) up to a max of 400 images counted. Here's the (simplified) code:

Sub GoogleCount ()

'''
'[Code to construct the URL ('fullUrl')]
'''
    Set objIE = New InternetExplorer
    objIE.navigate fullUrl
    Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop
    Set currPage = objIE.document
    'Count images returned
    newNum = currPage.getElementById("rg_s").getElementsByTagName("IMG").Length
    'Scroll down until count = 400 (max) or no change in value
    Do While newNum >= 100 And newNum < 400 And newNum <> oldNum
        oldNum = newNum
        currPage.parentWindow.scrollBy 0, 100000
        Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop
        newNum = currPage.getElementById("rg_s").getElementsByTagName("IMG").Length
    Loop

'''
'[Code to paste the value of newNum into my workbook, and do some other progress reporting]
'''
End Sub

I'm unhappy about scrolling, it feels very 'manual', especially when you are scrolling by a fixed value (any point making it dynamic? i.e. finding the end of the page and scrolling to there).

But the main problem is that it doesn't work: when I execute the code, it counts the first 100 (or fewer) images fine. But when it's supposed to scroll and count some more, I get the value of 100 returned. Slowly stepping through the code with F8 I get the proper numbers (max 400), which leads me to conclude that the code is running through too quickly (I may be wrong).

To slow the code down I tried adding the objIE.readyState check loop, but because I'm only scrolling I don't think it counts as the page 're-loading' so the loop is ineffective in waiting for the new images to load.

I've thought about adding in a time delay instead. I am already employing

Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

elsewhere in the worksheet - so, I could add as small as a millisecond-order delay.

But I really want to avoid using that, as this code runs for c. 50 different searches and takes long enough to execute already, adding in fixed delays that are long enough to accommodate slow connection speeds would not be ideal. Also, internet speeds vary so much that a fixed delay is very unreliable - I could carry out some kind of connection test to get a better ball-park figure, but the best option is obviously only to wait as long as you have to.

Or better still find a different way of counting the images, preferably one which doesn't involve re-loading the page 4 times!
Any ideas?

NB. If you want to debug yourself, a good image search to set fullUrl to might be https://www.google.com/search?q=stack overflow|exchange&tbm=isch&source=lnt&tbs=isz:ex,iszw:312,iszh:390 as it returns >100 images but fewer than 400 so you can test all aspects of the code

Body:
Through further research I've come up with this approach:

Dim myDiv As HTMLDivElement: Set myDiv = currPage.getElementById("fbar")
Dim elemRect As IHTMLRect: Set elemRect = myDiv.getBoundingClientRect
Do Until elemRect.bottom > 0
    currPage.parentWindow.scrollBy 0, 10000
    Set elemRect = myDiv.getBoundingClientRect
Loop
myDiv.ScrollIntoView

Where currPage is the HTML webpage (Dim currPage As HTMLDocument) and myDiv is a particular element. The type is not important, but it should be noted that myDiv is always located at the bottom of the document and is only loaded once everything else has been. So for Google images that's the help bar, which you only get to after scrolling through all the image results.

How it works

The code works as follows: myDiv.getBoundingClientRect is a way of checking whether an element is visible in the browser - that's why we need to look at an element at the bottom of the page, as if we scroll until that becomes visible, then everything else must have loaded too.

That's of course where the Do Until...Loop comes from; we loop until the elemRect.bottom value is not zero (as when the element is not in view, it's zero, once it's in view it becomes a non-zero number). More info on that see here

Finally, use a myDiv.ScrollIntoView to get the browser right to the bottom; this is necessary because the BoundingClientRect is visible slightly before the element is on screen, so we need to scroll the last bit in order to load the final images.

Why not just use ScrollIntoView form the start? It doesn't work, since the element hasn't loaded yet.


问:
Golang convert integer to unicode character
Given the following input:

```<code>intVal := 2612
strVal := "2612"
</code>```

What is a mechanism for mapping to the associated unicode value as a string.

For example, the following code prints "☒"

```<code>fmt.Println("\u2612")
</code>```

But the following does not work:

```<code>fmt.Println("\\u" + strVal)
</code>```

I researched runes, strconv, and unicode/utf8 but was unable to find a suitable conversion strategy.

答:
2612 is not the integer value of the unicode rune, the integer value of \u2612 is 9746. The string "2612" is the hex value of the rune, so parse it as a hex number and convert it to a rune.

```<code>i, err := strconv.ParseInt(strVal, 16, 32)
if err != nil {
    log.Fatal(err)
}
r := rune(i)
fmt.Println(string(r))
</code>```

https://play.golang.org/p/t_e6AfbKQq

Body:
Given the following input:

intVal := 2612
strVal := "2612"

What is a mechanism for mapping to the associated unicode value as a string.

For example, the following code prints "☒"

fmt.Println("\u2612")

But the following does not work:

fmt.Println("\\u" + strVal)

I researched runes, strconv, and unicode/utf8 but was unable to find a suitable conversion strategy.

Body:
2612 is not the integer value of the unicode rune, the integer value of \u2612 is 9746. The string "2612" is the hex value of the rune, so parse it as a hex number and convert it to a rune.

i, err := strconv.ParseInt(strVal, 16, 32)
if err != nil {
    log.Fatal(err)
}
r := rune(i)
fmt.Println(string(r))

https://play.golang.org/p/t_e6AfbKQq


问:
How to add page list in asp.net core MVC application?
I want to add page list in asp.net core MVC application so only 10 result will appear in the first page, to see more result I wanna add next option .I searched  but didn't found any solution for this operation.
There is NuGet package for asp.net but not for  asp.net core application.

PagedList

X.PagedList  (This is forked from PageList)

答:
Use jquery datatable plugin to show data. On pagination button click make ajax call to server method to retrive next data. You can use datatable server side by setting server attribute to true.
Please refer below links.

https://datatables.net/examples/data_sources/server_side.html

https://www.codeproject.com/Tips/1011531/Using-jQuery-DataTables-with-Server-Side-Processin


问:
Second Max Date by ID
I have a table that looks like this

```<code>ID          Date
123        2/1/2017
123        4/1/2017
123        6/5/2017
123        7/8/2017
456        3/8/2017
456        3/9/2017
456        3/10/2017
</code>```

Dates are in American format.
I want to pull a list of IDs, with the SECOND max date. So i would like the results to be:

```<code>ID         Date
123       6/5/2017
456       3/9/2017
</code>```

I do not know how to do this. I have googled, but with no avail. Any help is greatly appreciated.

I have tried this, but its not working

```<code>select *
from (
    select ROW_NUMBER() over (partition by ID order by DATE  desc ) as 'rowNum', ID, DATE
    from table1 ) withRowNum
where rowNum = 2
</code>```

答:
For SQL Server:

If your dates are varchar, and your current date format is not mdy then you could use set dateformat e.g.

```<code>set dateformat mdy;
select *
from (
    select ROW_NUMBER() over (
             partition by ID
             order by convert(date,DATE)  desc
           ) as 'rowNum', ID, DATE
    from table1 ) withRowNum
where rowNum = 2
</code>```

Title: Second Max Date by ID

Body:
I have a table that looks like this

ID          Date
123        2/1/2017
123        4/1/2017
123        6/5/2017
123        7/8/2017
456        3/8/2017
456        3/9/2017
456        3/10/2017

Dates are in American format.
I want to pull a list of IDs, with the SECOND max date. So i would like the results to be:

ID         Date
123       6/5/2017
456       3/9/2017

I do not know how to do this. I have googled, but with no avail. Any help is greatly appreciated.

I have tried this, but its not working

select *
from (
    select ROW_NUMBER() over (partition by ID order by DATE  desc ) as 'rowNum', ID, DATE
    from table1 ) withRowNum
where rowNum = 2

Body:
For SQL Server:

If your dates are varchar, and your current date format is not mdy then you could use set dateformat e.g.

set dateformat mdy;
select *
from (
    select ROW_NUMBER() over (
             partition by ID
             order by convert(date,DATE)  desc
           ) as 'rowNum', ID, DATE
    from table1 ) withRowNum
where rowNum = 2


问:
How to use MagickGetImageHistogram of ImageMagick C API
I have been using ImageMagick's C API using LuaJIT and FFI library and magick lua module for this. Now I want to use MagickGetImageHistogram method. So when it comes to pass an argument check my below code.

```<code>***image.lua***

local len = ffi.new("size_t[?]", 5)
local t = handle_result(self, lib.MagickGetImageHistogram(self.wand, len))

***lib.lua***

local ffi = require("ffi")
local lib
ffi.cdef([[  typedef void MagickWand;
typedef void PixelWand;

typedef int MagickBooleanType;
typedef int ExceptionType;
typedef int ssize_t;
typedef int CompositeOperator;
typedef int GravityType;
typedef int OrientationType;
typedef int InterlaceType;
typedef char DistortMethod[];

void MagickWandGenesis();
MagickWand* NewMagickWand();

PixelWand **MagickGetImageHistogram(MagickWand *wand, size_t *number_colors);
</code>```

So I'm sure that my first argument is correct but not sure about second one.
And it returns the image histogram as an array of PixelWand wands. So how do I convert it to LuaJIT structure?

答:
I'm not sure about the lua parts of the question, but the expected behavior MagickGetImageHistogram is as follows.

Method will return an array of pixel pointers.

Argument size_t *number_colors will be updated with the count of pixels in array.

Each pixel in array will need to invoke method PixelGetColorCount to retrieve the sum of pixels used by image.

Here's a quick example in C.

#include <stdio.h>
#include <wand/MagickWand.h>

int main(int argc, const char * argv[]) {
    // Prototype vars
    MagickWand * wand;
    PixelWand ** histogram;
    size_t histogram_count = 0;
    // Boot environment.
    MagickWandGenesis();
    // Allocate & read image
    wand = NewMagickWand();
    MagickReadImage(wand, "rose:");
    // Get Histogram as array of pixels
    histogram = MagickGetImageHistogram(wand, &histogram_count);
    // Iterate over each pixel & dump info.
    for (int i = 0; i < histogram_count; ++i)
    {
        printf("%s => %zu\n",
               PixelGetColorAsString(histogram[i]),
               PixelGetColorCount(histogram[i]));
    }
    // Clean-up
    histogram = DestroyPixelWands(histogram, histogram_count);
    wand = DestroyMagickWand(wand);
    MagickWandTerminus();
    return 0;
}
```

<p>This example will output the expected text...</p>

<pre class="lang-txt prettyprint-override"><code>// ...
srgb(48,45,43) => 1
srgb(50,45,42) => 2
srgb(50,44,43) => 5
srgb(51,45,43) => 1
// ...
</code>```

So I would guess your lua script would look something like..

***image.lua***

local tlen = ffi.new("size_t[1]")
local t = lib.MagickGetImageHistogram(self.wand, tlen)
for i=0,tlen[0] do
    handle_new_pixel(self, t[i], lib.PixelGetColorCount(t[i]))
end
```

Body:
I have been using ImageMagick's C API using LuaJIT and FFI library and magick lua module for this. Now I want to use MagickGetImageHistogram method. So when it comes to pass an argument check my below code.

***image.lua***

local len = ffi.new("size_t[?]", 5)
local t = handle_result(self, lib.MagickGetImageHistogram(self.wand, len))

***lib.lua***

local ffi = require("ffi")
local lib
ffi.cdef([[  typedef void MagickWand;
typedef void PixelWand;

typedef int MagickBooleanType;
typedef int ExceptionType;
typedef int ssize_t;
typedef int CompositeOperator;
typedef int GravityType;
typedef int OrientationType;
typedef int InterlaceType;
typedef char DistortMethod[];

void MagickWandGenesis();
MagickWand* NewMagickWand();

PixelWand **MagickGetImageHistogram(MagickWand *wand, size_t *number_colors);

So I'm sure that my first argument is correct but not sure about second one.
And it returns the image histogram as an array of PixelWand wands. So how do I convert it to LuaJIT structure?

Body:
I'm not sure about the lua parts of the question, but the expected behavior MagickGetImageHistogram is as follows.

Method will return an array of pixel pointers.

Argument size_t *number_colors will be updated with the count of pixels in array.

Each pixel in array will need to invoke method PixelGetColorCount to retrieve the sum of pixels used by image.

Here's a quick example in C.

#include <stdio.h>
#include <wand/MagickWand.h>

int main(int argc, const char * argv[]) {
    // Prototype vars
    MagickWand * wand;
    PixelWand ** histogram;
    size_t histogram_count = 0;
    // Boot environment.
    MagickWandGenesis();
    // Allocate & read image
    wand = NewMagickWand();
    MagickReadImage(wand, "rose:");
    // Get Histogram as array of pixels
    histogram = MagickGetImageHistogram(wand, &histogram_count);
    // Iterate over each pixel & dump info.
    for (int i = 0; i < histogram_count; ++i)
    {
        printf("%s => %zu\n",
               PixelGetColorAsString(histogram[i]),
               PixelGetColorCount(histogram[i]));
    }
    // Clean-up
    histogram = DestroyPixelWands(histogram, histogram_count);
    wand = DestroyMagickWand(wand);
    MagickWandTerminus();
    return 0;
}

This example will output the expected text...

// ...
srgb(48,45,43) => 1
srgb(50,45,42) => 2
srgb(50,44,43) => 5
srgb(51,45,43) => 1
// ...

So I would guess your lua script would look something like..

***image.lua***

local tlen = ffi.new("size_t[1]")
local t = lib.MagickGetImageHistogram(self.wand, tlen)
for i=0,tlen[0] do
    handle_new_pixel(self, t[i], lib.PixelGetColorCount(t[i]))
end


问:
On coursera R-programming course Assignment 2 Lexical Scoping
I'm Using Win7 64x Rstudio Version 3.3.2.

The following functions is assignmet2 solution that other people submitted.

```<code>makeCacheMatrix <- function(x = matrix()) {
    inv <- NULL
    set <- function(y) {
            x <<- y
            inv <<- NULL
    }
    get <- function() x
    setInverse <- function(inverse) inv <<- inverse
    getInverse <- function() inv
    list(set = set,
         get = get,
         setInverse = setInverse,
         getInverse = getInverse)
}
</code>```

First in the function makeCacheMatrix, why does 'set function' use variable 'y'?

Is it simply used to tell us how to use '<<-'?

Secondly, In 'get function', why is variable 'x' followed by the parentheses of the function? ( 'setInverse function - inv<<-inverse' , 'getInverse function - inv' are the same. )

答:
You know that the goal of this task is to create a super matrix that can store it's content and it's inverse as well. So it has to have 2 variable x the matrix, and inv the inverse. Each variable has 2 functions set and get. So, set is a function that takes an argument and do something inside it, in this code set takes y as an argument (dummy variable could be any other name) and assign it to the matrix x. The same for inv.

This will make the only access for these variables is through set and get.

Note that:(R documentation)
 The operators <<- and ->> are normally only used in functions, and cause a search to be made through parent environments for an existing definition of the variable being assigned

Now, if we want to use this function:

```<code>mat <- makeCacheMatrix()

## set the matrix value
mat$set(matrix(data = (1:10), nrow = 5, ncol = 2))

## Check that we stored it correctly
mat$get()
# [,1] [,2]
# [1,]    1    6
# [2,]    2    7
# [3,]    3    8
# [4,]    4    9
# [5,]    5   10
</code>```

Body:
I'm Using Win7 64x Rstudio Version 3.3.2.

The following functions is assignmet2 solution that other people submitted.

makeCacheMatrix <- function(x = matrix()) {
    inv <- NULL
    set <- function(y) {
            x <<- y
            inv <<- NULL
    }
    get <- function() x
    setInverse <- function(inverse) inv <<- inverse
    getInverse <- function() inv
    list(set = set,
         get = get,
         setInverse = setInverse,
         getInverse = getInverse)
}

First in the function makeCacheMatrix, why does 'set function' use variable 'y'?

Is it simply used to tell us how to use '<<-'?

Secondly, In 'get function', why is variable 'x' followed by the parentheses of the function? ( 'setInverse function - inv<<-inverse' , 'getInverse function - inv' are the same. )

Body:
You know that the goal of this task is to create a super matrix that can store it's content and it's inverse as well. So it has to have 2 variable x the matrix, and inv the inverse. Each variable has 2 functions set and get. So, set is a function that takes an argument and do something inside it, in this code set takes y as an argument (dummy variable could be any other name) and assign it to the matrix x. The same for inv.

This will make the only access for these variables is through set and get.

Note that:(R documentation)
 The operators <<- and ->> are normally only used in functions, and cause a search to be made through parent environments for an existing definition of the variable being assigned

Now, if we want to use this function:

mat <- makeCacheMatrix()

## set the matrix value
mat$set(matrix(data = (1:10), nrow = 5, ncol = 2))

## Check that we stored it correctly
mat$get()
# [,1] [,2]
# [1,]    1    6
# [2,]    2    7
# [3,]    3    8
# [4,]    4    9
# [5,]    5   10


问:
General thoughts about one Rest Endpoint and two Consumers
Consider the following situation:

You have one Endpoint, for example ../api/Samples

All Samples have the Attributes: Name, App.

You have two Apps which will consume the Samples Endpoint

The First App (A1) wants all Samples.

The Second App (A2) wants only a Subset of the Samples. To be exact only the Samples which have 'A2' standing in the 'App' Attribute.

What is the most REST-conform and common sense way to realize this?

So far I thought of three ways:

Create two Endpoints: ../api/A1Samples and ../api/A2Samples

This seems like overhead. What if more Apps come later? The Controller must be duplicated even if most of the code is identical.

Send the App Type within the URL: ../api/Samples/A1 or A2

Would be easier to maintain if more Apps come later. But doesn't this reject the thought of REST?

Send the App Type within the Accept Header: ../api/Samples and in the Header: App-Type: A1 or A2

In my case it seems this isn't easy to implement in ASP.NET Core v1.1 but should be the most syntactically correct way.

Can someone approve or reject my thoughts? Maybe even extend the list or state the usually used solution for this case?

答:
If one of the applications requires all samples, it could simply consume /api/Samples directly; for the other one, have an extensible way to specify filters (even if that is just a few GET parameters) - if this is really an "App" attribute that exists on the Sample object then ?App=A2 would make sense, if it is some other attribute then specify those attributes directly.

This is more REST-ful than your /Samples/A1 and /Samples/A2 idea because it directly specifies the attribute being queried for (A1 doesn't use ?App=A1 because as you said Application 1 consumes the entire list of sample objects) rather than knowledge of what application is querying it, any similarity is simply due to the (I suspect contrived) structure of the example.

REST isn't just about something as simple as "use path parameters in all cases" - filtering a result list is a clear case for using query parameters instead.