问:
Cannot pass immutable value of type 'NSLayoutConstraint' as inout argument
I try to reassign an referecend NSLayoutConstraint.

```<code>class ViewController: UIViewController {
    @IBOutlet weak var myConstraint: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()
        exchangeConstraint(&myConstraint)
    }
}

extension UIViewController {
    func exchangeConstraint(_ constraint: inout NSLayoutConstraint) {
        let spacing = constraint.constant
        view.removeConstraint(constraint)
        constraint = view.topAnchor.constraint(equalTo: anotherView.topAnchor, constant: spacing)
        view.addConstraint(constraint)
    }
}
</code>```

But here it gives me the error:

```<code>exchangeConstraint(&myConstraint)
-------------------^
Cannot pass immutable value of type 'NSLayoutConstraint' as inout argument
</code>```

What i don't understand is why it says immutable value, whereas the constraint is declared as a variable, not a constant.

答:
I solved it by simply declaring the constraint parameter as an explicitly unwraped NSLayoutConstraint.

```<code>func exchangeConstraint(_ constraint: inout NSLayoutConstraint!) {
    ...
}
</code>```

UPDATE

Here is a project where I use it: https://github.com/truffls/compatible-layout-anchors-ios

Body:
I try to reassign an referecend NSLayoutConstraint.

class ViewController: UIViewController {
    @IBOutlet weak var myConstraint: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()
        exchangeConstraint(&myConstraint)
    }
}

extension UIViewController {
    func exchangeConstraint(_ constraint: inout NSLayoutConstraint) {
        let spacing = constraint.constant
        view.removeConstraint(constraint)
        constraint = view.topAnchor.constraint(equalTo: anotherView.topAnchor, constant: spacing)
        view.addConstraint(constraint)
    }
}

But here it gives me the error:

exchangeConstraint(&myConstraint)
-------------------^
Cannot pass immutable value of type 'NSLayoutConstraint' as inout argument

What i don't understand is why it says immutable value, whereas the constraint is declared as a variable, not a constant.

Body:
I solved it by simply declaring the constraint parameter as an explicitly unwraped NSLayoutConstraint.

func exchangeConstraint(_ constraint: inout NSLayoutConstraint!) {
    ...
}

UPDATE

Here is a project where I use it: https://github.com/truffls/compatible-layout-anchors-ios


来源: stackexchange

问:
Roman numerals to integers
In data sometimes the same product will be named with a roman numeral while other times it will be a digit.

Example Samsung Galaxy SII verses Samsung Galaxy S2

How can the II be converted to the value 2?

答:
I landed here searching for a small implementation of a Roman Numerals parser but wasn't satisfied by the provided answers in terms of size and elegance. I leave my final, recursive implementation here, to help others searching a small implementation.

Convert Roman Numerals by Recursion

The algorithm is able to handle numerals in irregular subtractive notation (f.e. XIIX).

This implementation may only work with well-formed (strings matching /[mdclxvi]*/i) roman numerals.

The implementation is not optimized for speed.

// returns the value for a roman literal
private static int romanValue(int index)
{
    int basefactor = ((index % 2) * 4 + 1); // either 1 or 5...
    // ...multiplied with the exponentation of 10, if the literal is `x` or higher
    return index > 1 ? (int) (basefactor * System.Math.Pow(10.0, index / 2)) : basefactor;
}

public static int FromRoman(string roman)
{
    roman = roman.ToLower();
    string literals = "mdclxvi";
    int value = 0, index = 0;
    foreach (char literal in literals)
    {
        value = romanValue(literals.Length - literals.IndexOf(literal) - 1);
        index = roman.IndexOf(literal);
        if (index > -1)
            return FromRoman(roman.Substring(index + 1)) + (index > 0 ? value - FromRoman(roman.Substring(0, index)) : value);
    }
    return 0;
}
```
<blockquote>
<p><strong>Try it</strong> using this .Netfiddle: https://dotnetfiddle.net/veaNk3</p>
</blockquote>
<h3>How does it work?</h3>
<p>This algorithm calculates the value of a Roman Numeral by taking the highest value from the Roman Numeral and adding/subtracting recursively the value of the remaining left/right parts of the literal.</p>
```ii X iiv # Pick the greatest value in the literal `iixiiv` (symbolized by uppercase)
```
<p>Then recursively reevaluate and subtract the lefthand-side and add the righthand-side:</p>
```(iiv) + x - (ii) # Subtract the lefthand-side, add the righthand-side
(V - (ii)) + x - ((I) + i) # Pick the greatest values, again
(v - ((I) + i)) + x - ((i) + i) # Pick the greatest value of the last numeral compound
```
<p>Finally the numerals are substituted by their integer values:</p>
```(5 - ((1) + 1)) + 10 - ((1) + 1)
(5 - (2)) + 10 - (2)
3 + 10 - 2
= 11
```

ContentLicense: CC BY-SA 4.0

Title: Roman numerals to integers

Body:
I landed here searching for a small implementation of a Roman Numerals parser but wasn't satisfied by the provided answers in terms of size and elegance. I leave my final, recursive implementation here, to help others searching a small implementation.

Convert Roman Numerals by Recursion

The algorithm is able to handle numerals in irregular subtractive notation (f.e. XIIX).

This implementation may only work with well-formed (strings matching /[mdclxvi]*/i) roman numerals.

The implementation is not optimized for speed.

// returns the value for a roman literal
private static int romanValue(int index)
{
    int basefactor = ((index % 2) * 4 + 1); // either 1 or 5...
    // ...multiplied with the exponentation of 10, if the literal is `x` or higher
    return index > 1 ? (int) (basefactor * System.Math.Pow(10.0, index / 2)) : basefactor;
}

public static int FromRoman(string roman)
{
    roman = roman.ToLower();
    string literals = "mdclxvi";
    int value = 0, index = 0;
    foreach (char literal in literals)
    {
        value = romanValue(literals.Length - literals.IndexOf(literal) - 1);
        index = roman.IndexOf(literal);
        if (index > -1)
            return FromRoman(roman.Substring(index + 1)) + (index > 0 ? value - FromRoman(roman.Substring(0, index)) : value);
    }
    return 0;
}

Try it using this .Netfiddle: https://dotnetfiddle.net/veaNk3

How does it work?

This algorithm calculates the value of a Roman Numeral by taking the highest value from the Roman Numeral and adding/subtracting recursively the value of the remaining left/right parts of the literal.

ii X iiv # Pick the greatest value in the literal `iixiiv` (symbolized by uppercase)

Then recursively reevaluate and subtract the lefthand-side and add the righthand-side:

(iiv) + x - (ii) # Subtract the lefthand-side, add the righthand-side
(V - (ii)) + x - ((I) + i) # Pick the greatest values, again
(v - ((I) + i)) + x - ((i) + i) # Pick the greatest value of the last numeral compound

Finally the numerals are substituted by their integer values:

(5 - ((1) + 1)) + 10 - ((1) + 1)
(5 - (2)) + 10 - (2)
3 + 10 - 2
= 11


问:
Disassemble x86 code in a program at a specific address
Is there any x86 disassembler framework that can be used to analyze code from a specific address in a program, as in:

```<code>info = disassemble(  startAddress , stopAddress)
</code>```

It should show every instruction and its operands and any other info that is good for analysis but it should have also fast mode where it isn't so important to obtain that much info for each instruction, but only for some of them that can be specified.

答:
Is GNU binutils not good enough?  Here's how to do that with the objdump utility:</p>

```<code># Disassemble from virtual addresses 0x80000000 to 80000100
objdump -d program --start-address=0x80000000 --stop-address=0x80000100
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Is there any x86 disassembler framework that can be used to analyze code from a specific address in a program, as in:

info = disassemble(  startAddress , stopAddress)

It should show every instruction and its operands and any other info that is good for analysis but it should have also fast mode where it isn't so important to obtain that much info for each instruction, but only for some of them that can be specified.

Body:
Is GNU binutils not good enough?  Here's how to do that with the objdump utility:

# Disassemble from virtual addresses 0x80000000 to 80000100
objdump -d program --start-address=0x80000000 --stop-address=0x80000100


问:
How to split a array to some sub-arrays with objective minimizing sum of square?
I have a array [a1, a2, a3,..., an], I want to split this array into some sub-arrays(i.e 3 sub-arrays) with constraints that each sub-array must be continuous.For example, sub-arr1=[a1, a2,..., a8], sub-arr2=[a9, a10,..., a17],sub-arr1=[a18, a19,..., an],  and I want to minimize sum of each aub-array's variance, say

```<code>min sum(sum((some element in sub_i - avg_value in sub_i)^2)) and the outer sum is to sum all sub-arrays.
</code>```

Now, I don't know how to solve this problem efficiently, Thx.

答: I find a paper to solve my problem, solver</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a array [a1, a2, a3,..., an], I want to split this array into some sub-arrays(i.e 3 sub-arrays) with constraints that each sub-array must be continuous.For example, sub-arr1=[a1, a2,..., a8], sub-arr2=[a9, a10,..., a17],sub-arr1=[a18, a19,..., an],  and I want to minimize sum of each aub-array's variance, say

min sum(sum((some element in sub_i - avg_value in sub_i)^2)) and the outer sum is to sum all sub-arrays.

Now, I don't know how to solve this problem efficiently, Thx.


问:
Sum all the child level data
I have a requirement where I need to sum up all the child of a node.

And the Output should be

```<code>D023343 120
D022959 120
D023375 50
D035738 10
D024481 0
</code>```

I tried using diff queries but it is not getting the required . Kindly help

```<code>SELECT * FROM (SELECT a.child achild,b.child bchild,a.parent aparent,b.parent bparent,a.sales,b.sales
 FROM TEST a,TEST b
WHERE a.CHILD='D023375')
where aparent!=bchild
and achild=bparent
</code>```

Kindly help.

Thanks

答:
You can use a recursive common table expression as defined in the SQL-99 standard. Oracle calls this recursive subquery factoring. You'll also need to do something to get the last record with 0 sales in the result, since there is no record that explicitly defines that sales amount.

Here is how such a query would look:

```<code>with base(parent, child, sales) as (
    select parent, child, sales
    from   tbl
    union all -- add the 0 sales records
    select child, null, 0
    from   tbl
),
rec(parent,child,sales) as ( -- recursive query
    select parent, child, sales
    from   base
    union all
    select rec.parent, base.child, base.sales
    from   base
    inner join rec on base.parent = rec.child
)
select   parent, sum(sales)
from     rec
group by parent
order by 1
</code>```

NB: this syntax is supported as of Oracle 11g Release 2.

Title: Sum all the child level data

Body:
I have a requirement where I need to sum up all the child of a node.

And the Output should be

D023343 120
D022959 120
D023375 50
D035738 10
D024481 0

I tried using diff queries but it is not getting the required . Kindly help

SELECT * FROM (SELECT a.child achild,b.child bchild,a.parent aparent,b.parent bparent,a.sales,b.sales
 FROM TEST a,TEST b
WHERE a.CHILD='D023375')
where aparent!=bchild
and achild=bparent

Kindly help.

Thanks

Body:
You can use a recursive common table expression as defined in the SQL-99 standard. Oracle calls this recursive subquery factoring. You'll also need to do something to get the last record with 0 sales in the result, since there is no record that explicitly defines that sales amount.

Here is how such a query would look:

with base(parent, child, sales) as (
    select parent, child, sales
    from   tbl
    union all -- add the 0 sales records
    select child, null, 0
    from   tbl
),
rec(parent,child,sales) as ( -- recursive query
    select parent, child, sales
    from   base
    union all
    select rec.parent, base.child, base.sales
    from   base
    inner join rec on base.parent = rec.child
)
select   parent, sum(sales)
from     rec
group by parent
order by 1

NB: this syntax is supported as of Oracle 11g Release 2.


问:
Is it possible to create HTML element attribute only in case of some condition?
Is it possible to decide on html element creation time excluding or including an elements attribute like setup a callback or not?

When using the ng-repeat flow I have some condition where I want to create the html element with a close-callback handler and in some cases the element should not contain a close handler definition.

```<code><div ng-repeat="item in ctrl.items"
close="ctrl.close()">XYZ</div>
</code>```

... or without callback ..

```<code><div ng-repeat="item in ctrl.items">XYZ</div>
</code>```

... maybe something like ng-if? Is something like that possible? The check condition is in the item itself. So during ng-repeat I need to check some items internal state like:

```<code>item.state === 'state1' ? add close handler : do nothing ...
</code>```

Where I can add this condition check and how i perform the close handler adding or not?

Cheers

答:
You can use a custom directive to solve this, here is an example :

Closable items are colored and have an onclick event listener (try to click on it).

To be closable, an item state must match closable-state attribute value.

You must use single quotes around value when using closable-state="'value'" to prevent value beeing evaluated as an expression.

If value is a hard-coded string, then you can remove state: "=closableState" from directive and simply use attrs.closableState to retrieve the attribute value.

Hope that helps.

angular.module('app', []);

angular
    .module('app')
    .controller('ExampleController', ['$scope', function ($scope) {
        $scope.items = [
            { label: "item1", state: "state1" },
            { label: "item2", state: "state2" },
            { label: "item3", state: "state1" },
        ];
    }])
    .directive('closable', function () {
        return {
            restrict: 'A',
            scope: {
                item: "=closable",
                state: "=closableState",
            },
            link: function (scope, element, attrs) {

                var clickListener = function (event) {
                    alert("I'm closable !");
                }

                if (scope.item && scope.item.state === scope.state) {
                  element.addClass("colored");
                  element.bind("click", clickListener);
                }
            }
        };
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.colored { color: red }</code>```

<!doctype html>

  <meta charset="utf-8">

{{item.label}}

```

Body:
Is it possible to decide on html element creation time excluding or including an elements attribute like setup a callback or not?

When using the ng-repeat flow I have some condition where I want to create the html element with a close-callback handler and in some cases the element should not contain a close handler definition.

XYZ

... or without callback ..

XYZ

... maybe something like ng-if? Is something like that possible? The check condition is in the item itself. So during ng-repeat I need to check some items internal state like:

item.state === 'state1' ? add close handler : do nothing ...

Where I can add this condition check and how i perform the close handler adding or not?

Cheers

Body:
You can use a custom directive to solve this, here is an example :

Closable items are colored and have an onclick event listener (try to click on it).

To be closable, an item state must match closable-state attribute value.

You must use single quotes around value when using closable-state="'value'" to prevent value beeing evaluated as an expression.

If value is a hard-coded string, then you can remove state: "=closableState" from directive and simply use attrs.closableState to retrieve the attribute value.

Hope that helps.

angular.module('app', []);

angular
    .module('app')
    .controller('ExampleController', ['$scope', function ($scope) {
        $scope.items = [
            { label: "item1", state: "state1" },
            { label: "item2", state: "state2" },
            { label: "item3", state: "state1" },
        ];
    }])
    .directive('closable', function () {
        return {
            restrict: 'A',
            scope: {
                item: "=closable",
                state: "=closableState",
            },
            link: function (scope, element, attrs) {

                var clickListener = function (event) {
                    alert("I'm closable !");
                }

                if (scope.item && scope.item.state === scope.state) {
                  element.addClass("colored");
                  element.bind("click", clickListener);
                }
            }
        };
    });

.colored { color: red }

<!doctype html>
<html lang="en" ng-app="app">
<head>
  <meta charset="utf-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>
  <script src="script.js"></script>
</head>
<body ng-controller="ExampleController">
  <ul>
    <li ng-repeat="item in items" closable="item" closable-state="'state1'">{{item.label}}</li>
  </ul>
</body>
</html>


问:
Can you have multiple grids on the same page with different themes?
I have a master/detail setup using jqGrid and jQuery. Is it possible to have the detail grid use a different theme/skin than the master grid?

I see a setting to change the images folder, but it looks to me like grid.css would have to be the same for the entire page. Has anyone tried? Or do you have any suggestions for a workaround?

答: I had a quick look at the documentation and it seems as though you can't because if you had multiple grids they would all use the same CSS rules by default. If you load in another grid.css stylesheet then it will just take precedence over the previous one. They don't seem to provide a mechanism to choose the theme for each grid.</p>

OwnerDisplayName: nshaw

OwnerDisplayName: jonhobbs


问:
Find objects between two dates MongoDB
I've been playing around storing tweets inside mongodb, each object looks like this:

```<code>{
"_id" : ObjectId("4c02c58de500fe1be1000005"),
"contributors" : null,
"text" : "Hello world",
"user" : {
    "following" : null,
    "followers_count" : 5,
    "utc_offset" : null,
    "location" : "",
    "profile_text_color" : "000000",
    "friends_count" : 11,
    "profile_link_color" : "0000ff",
    "verified" : false,
    "protected" : false,
    "url" : null,
    "contributors_enabled" : false,
    "created_at" : "Sun May 30 18:47:06 +0000 2010",
    "geo_enabled" : false,
    "profile_sidebar_border_color" : "87bc44",
    "statuses_count" : 13,
    "favourites_count" : 0,
    "description" : "",
    "notifications" : null,
    "profile_background_tile" : false,
    "lang" : "en",
    "id" : 149978111,
    "time_zone" : null,
    "profile_sidebar_fill_color" : "e0ff92"
},
"geo" : null,
"coordinates" : null,
"in_reply_to_user_id" : 149183152,
"place" : null,
"created_at" : "Sun May 30 20:07:35 +0000 2010",
"source" : "web",
"in_reply_to_status_id" : {
    "floatApprox" : 15061797850
},
"truncated" : false,
"favorited" : false,
"id" : {
    "floatApprox" : 15061838001
}
</code>```

How would I write a query which checks the created_at and finds all objects between 18:47 and 19:00? Do I need to update my documents so the dates are stored in a specific format?

答:
use $gte and $lte to find between date data's in mongodb

```<code>var tomorrowDate = moment(new Date()).add(1, 'days').format("YYYY-MM-DD");
db.collection.find({"plannedDeliveryDate":{ $gte: new Date(tomorrowDate +"T00:00:00.000Z"),$lte: new Date(tomorrowDate + "T23:59:59.999Z")}})
</code>```

Title: Find objects between two dates MongoDB

Body:
I've been playing around storing tweets inside mongodb, each object looks like this:

{
"_id" : ObjectId("4c02c58de500fe1be1000005"),
"contributors" : null,
"text" : "Hello world",
"user" : {
    "following" : null,
    "followers_count" : 5,
    "utc_offset" : null,
    "location" : "",
    "profile_text_color" : "000000",
    "friends_count" : 11,
    "profile_link_color" : "0000ff",
    "verified" : false,
    "protected" : false,
    "url" : null,
    "contributors_enabled" : false,
    "created_at" : "Sun May 30 18:47:06 +0000 2010",
    "geo_enabled" : false,
    "profile_sidebar_border_color" : "87bc44",
    "statuses_count" : 13,
    "favourites_count" : 0,
    "description" : "",
    "notifications" : null,
    "profile_background_tile" : false,
    "lang" : "en",
    "id" : 149978111,
    "time_zone" : null,
    "profile_sidebar_fill_color" : "e0ff92"
},
"geo" : null,
"coordinates" : null,
"in_reply_to_user_id" : 149183152,
"place" : null,
"created_at" : "Sun May 30 20:07:35 +0000 2010",
"source" : "web",
"in_reply_to_status_id" : {
    "floatApprox" : 15061797850
},
"truncated" : false,
"favorited" : false,
"id" : {
    "floatApprox" : 15061838001
}

How would I write a query which checks the created_at and finds all objects between 18:47 and 19:00? Do I need to update my documents so the dates are stored in a specific format?

Body:
use $gte and $lte to find between date data's in mongodb

var tomorrowDate = moment(new Date()).add(1, 'days').format("YYYY-MM-DD");
db.collection.find({"plannedDeliveryDate":{ $gte: new Date(tomorrowDate +"T00:00:00.000Z"),$lte: new Date(tomorrowDate + "T23:59:59.999Z")}})


问:
How to make a table with dynamic columns in Jaspersoft Studio?
I need to make this table in Jaspersoft Studio:

My table sometimes have one test, two, n test or nothing.
Is it possible? How can I solve this task?

答:
I do not know if you still need it but just for the reference. In Jasper Report, you can use 'printWhenExpression' where you can print a particular row/column/value based on a certain condition.
If you know the max no. of columns then add those columns in your design and then hide them using printWhenExpression.
Or else you can also go for DynamicJasper or DynamicReports for this purpose.</p>


问:
Short writing in Matlab for getting the minimum of two vectors at each position
I have the following code:

```<code>for i=1:length(Z1)
    if Z1(i) < Z2(i)
        min_vec(i) = Z1(i)
    else
        min_vec(i) = Z2(i)
    end
end
</code>```

I am wondering if there is a more "matlab" short writing way to achieve the same goal?

答:
You can use min function:

If you are only interest only to the minimum value, you can simply use Z1 and Z2 as input:

```<code>min_Z1_Z2=min(Z1,Z2)
</code>```

if you are also interested to know in which of the two array the minimun value is, you can call min with two parameters as output and passing as input the two array as a matrix

```<code>[min_val,Z1_Z2]=min([Z1;Z2])
</code>```

In min_val you have the minimum value, in Z1_Z2 the values 1 or 2 according if the min value is in the first or the second row, that is Z1 or Z2

```<code>Z1=randi([1 33],1,10)
Z2=randi([1 33],1,10)
min_Z1_Z2=min(Z1,Z2)
[min_val,Z1_Z2]=min([Z1;Z2])

>> Z1
Z1 =

   24   12   16   21   22   15   28    7   17   29

>> Z2
Z2 =

   27   26   23    2    5   10   25   23   29    9

>> min_val
min_val =

   24   12   16    2    5   10   25    7   17    9

>> Z1_Z2
Z1_Z2 =

   1   1   1   2   2   2   2   1   1   2
</code>```

Body:
I have the following code:

for i=1:length(Z1)
    if Z1(i) < Z2(i)
        min_vec(i) = Z1(i)
    else
        min_vec(i) = Z2(i)
    end
end

I am wondering if there is a more "matlab" short writing way to achieve the same goal?

Body:
You can use min function:

If you are only interest only to the minimum value, you can simply use Z1 and Z2 as input:

min_Z1_Z2=min(Z1,Z2)

if you are also interested to know in which of the two array the minimun value is, you can call min with two parameters as output and passing as input the two array as a matrix

[min_val,Z1_Z2]=min([Z1;Z2])

In min_val you have the minimum value, in Z1_Z2 the values 1 or 2 according if the min value is in the first or the second row, that is Z1 or Z2

Z1=randi([1 33],1,10)
Z2=randi([1 33],1,10)
min_Z1_Z2=min(Z1,Z2)
[min_val,Z1_Z2]=min([Z1;Z2])

>> Z1
Z1 =

   24   12   16   21   22   15   28    7   17   29

>> Z2
Z2 =

   27   26   23    2    5   10   25   23   29    9

>> min_val
min_val =

   24   12   16    2    5   10   25    7   17    9

>> Z1_Z2
Z1_Z2 =

   1   1   1   2   2   2   2   1   1   2


问:
Azure VM - linking the *.cloudapp.azure.com URL to godaddy?
I am trying to figure out how to link my *.cloudapp.azure.com VM's DNS info to a GoDaddy subdomain off my company's site. I am not able to wrap my head around the directions on Azure.

The second part is we have a purchased wildcard SSL cert for our main domain on GoDaddy that we need to install. I can see you can purchase certs from Azure, however we have our own.

Thanks for any assistance anyone can provide in this matter.

答:
You can use CNames to link Azure domains to your existing domain. Just créate a CName that point to your Azure DNS Name. Example:

you need vm.company.com to point to your vm called myvm in Azure.
créate CNAME vm that point to myvm.location.cloudapp.azure.com

As for the cert, copy it to the vm and import like you normally would.


问:
Cloning a PHP PDO recordset object to count the rows returned by a select statement
I'm refactoring part of a PHP application which uses adodb as db library, in order to start using PDO.

I need something which provides me the number of rows included in a select recordset, something that can easily replace the old $rs->RecordCount() adodb method that I used before. It should work for sqlite3.

I can't simply re-execute the query (or re-execute the query using a select count(*) ) because I can't change so much the original application, the application calls in many parts a function get_num_rows($rs) (which contains just $rs->RecordCount() ) and I can just change the content of that function.

I tried cloning the recordset object and counting the records fetched:

```<code>function get_num_rows($rs)
{
    $rs_copy = clone $rs;
    return (count($rs_copy->fetchAll()));
}
</code>```

but it doesn't work, because $rs_copy->fetchAll() returns me false. I can't do it on the original recordset because later in the applicaiton I need to fetch it again and I think there is no way in PDO sqlite to reuse the recordset (correct me if I'm wrong).

Do you have any solutions?

答:
Thanks to all.
I have found an easier, quick and dirty solution, my new get_num_rows() will be something like:

```<code>$temp_ar = explode("FROM", $rs->queryString);

$sql = "SELECT COUNT(*) FROM ".$temp_ar[1];

$conn->query($sql);

...
</code>```

Body:
I'm refactoring part of a PHP application which uses adodb as db library, in order to start using PDO.

I need something which provides me the number of rows included in a select recordset, something that can easily replace the old $rs->RecordCount() adodb method that I used before. It should work for sqlite3.

I can't simply re-execute the query (or re-execute the query using a select count(*) ) because I can't change so much the original application, the application calls in many parts a function get_num_rows($rs) (which contains just $rs->RecordCount() ) and I can just change the content of that function.

I tried cloning the recordset object and counting the records fetched:

function get_num_rows($rs)
{
    $rs_copy = clone $rs;
    return (count($rs_copy->fetchAll()));
}

but it doesn't work, because $rs_copy->fetchAll() returns me false. I can't do it on the original recordset because later in the applicaiton I need to fetch it again and I think there is no way in PDO sqlite to reuse the recordset (correct me if I'm wrong).

Do you have any solutions?

Body:
Thanks to all.
I have found an easier, quick and dirty solution, my new get_num_rows() will be something like:

$temp_ar = explode("FROM", $rs->queryString);

$sql = "SELECT COUNT(*) FROM ".$temp_ar[1];

$conn->query($sql);

...


问:
what is the reason to have <header> <footer> tags in html5
why to use     tags in html5 even though we can achieve that functionality by html4  by adding css styles,
Other than every technology with latest version will have more flexibility or features. please help me to understand..</p>

答: The main advantage is while loading your code the web browser knows the header and footer portion. It helps in prioritizing on the things to be loaded first and which has to be loaded later. In addition this will be much easily understood by a Google Bot or a screen reader due to its logical markup.</p>


问:
What are the standard naming conventions for global objects in Javascript?
In Javascript, objects 'window' and 'document' start with a small letter, but global object 'Math' starts with a capital object.

Do these objects follow a standardised naming convention?

答:
In Javascript, objects 'window' and 'document' start with a small letter, but global object 'Math' starts with a capital object.

Math is "in JavaScript." The other two are browser-specified, not part of JavaScript.

Do these objects follow a standardised naming convention?

The JavaScript ones do (a convention followed by the specification, that is; programmers are free to do their own thing elsewhere): Constructor functions (like Date) and objects whose primary purpose is to host utility functions (like Math) are initially-capped can CamelCase. Other functions are lower-case camelCase. Symbol is also capped; it creates things (symbols, which are primitives) although you don't call it via new (because symbols are primitives).

Browser global objects referring to specific things (like window and document) have tended to follow the lower-case camelCase convention for variables which is common in JavaScript. And browser-defined constructors like XMLHttpRequest have tended to match JavaScript's CamelCase for such things as well. (In both cases, I wouldn't be surprised to find exceptions; much of this stuff happened organically rather than by overall design.)


问:
python 3.x kivy: dynamically adding widgets to scrollview

I´m new to kivy and trying to create a scrollview that gets filled with several widgets live. That kind of works..
BUT the line items themselves often loose their own widgets and I often get this error:

[CRITICAL] [Clock       ] Warning, too much iteration done before the next frame. Check your code, or increase the Clock.max_iteration attribute

I read a lot of "clock", blocking the mainthread etc.. I tried to resolve it by using a different thread.. but still widgets are missing.

Attached the code and a picture. help is very much appreciated!! thx!

widgets missing..

my controller.kv

```<code>#:kivy 1.0

<Controller>:

    size_hint: 1., 1.
    pos_hint: {'center_x': .5, 'center_y': .5}
    do_default_tab: False

    tab1_pgbar: tab1_pgbar
    layout_content: layout_content
    tab1_refresh_btn: tab1_refresh_btn

    TabbedPanelItem:
        id: tab1
        text: 'Browse'

        BoxLayout:
            id: bl
            orientation: 'vertical'

            ScrollView:
                size_hint: 1.0,0.7

                GridLayout:
                    id: layout_content
                    size_hint_y: None
                    height: self.minimum_height
                    cols: 1
                    row_default_height: '100dp'
                    row_force_default: True
                    spacing: 0, 5

            BoxLayout:
                size_hint: 1.0,None
                height: 25

                ProgressBar:
                    size_hint: 1.0,1.0
                    id: tab1_pgbar
                    max: 1000

                Button:
                    id: tab1_refresh_btn
                    text: 'Refresh'
                    size: 100,25
                    on_release: root.refresh()
</code>```

my kivyMain.py

```<code>import kivy
kivy.require('1.10.0')

from kivy.uix.boxlayout import BoxLayout
from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.clock import mainthread

import time
import threading

class myJobEntry(BoxLayout):
    def __init__(self):
        super(myJobEntry, self).__init__()

    def addStuff(self,runindex,program):
        b1 = Button(text=runindex,size_hint=(None,1.0),width=100)
        b2 = TextInput(text=program,height=80)

        hbox1 = BoxLayout(orientation='horizontal')
        for i in range(10):
            hbox1.add_widget(Button(text='{}'.format(i)))

        vbox1 = BoxLayout(orientation='vertical')
        vbox1.add_widget(hbox1)
        vbox1.add_widget(b2)

        self.add_widget(b1)
        self.add_widget(vbox1)

class Controller(TabbedPanel):
    '''Create a controller that receives a custom widget from the kv lang file.
    Add an action to be called from the kv lang file.
    '''
    layout_content = ObjectProperty()
    tab1_refresh_btn = ObjectProperty()
    tab1_pgbar = ObjectProperty()
    text_input = ObjectProperty()

    def addSeveralObjects(self):
        self.tab1_pgbar.value = 0
        self.layout_content.enabled=False

        for i in range(100):
            myObj = myJobEntry()
            myObj.addStuff('{}'.format(i),'i')
            self.layout_content.add_widget(myObj)
            self.updateBar()

    def refresh(self):
        self.tab1_refresh_btn.enabled = False
        self.tab1_pgbar.value = 1

        mythread = threading.Thread(target=self.addSeveralObjects)
        mythread.start()

        self.resetRefreshButton()

    def resetRefreshButton(self):
        self.tab1_refresh_btn.text = 'Last Refresh: {}'.format(time.ctime())
        self.tab1_refresh_btn.enabled = True

    def updateBar(self):
        self.tab1_pgbar.value += 1

class ControllerApp(App):

    def build(self):
        return Controller()

if __name__ == '__main__':
    ControllerApp().run()
</code>```

答:
I guess the problem is your thread, a better option is to use the kivy Clock object:

```<code>...
from kivy.clock import Clock
from kivy.properties import NumericProperty
from kivy.metrics import dp
...

class Controller(TabbedPanel):
    '''Create a controller that receives a custom widget from the kv lang file.
    Add an action to be called from the kv lang file.
    '''
    layout_content = ObjectProperty()
    tab1_refresh_btn = ObjectProperty()
    tab1_pgbar = ObjectProperty()
    text_input = ObjectProperty()
    i = 0
    h = NumericProperty(0)

    def addSeveralObjects(self, *args):
        self.layout_content.enabled = False
        myObj = myJobEntry()
        myObj.addStuff('{}'.format(self.i), '{}'.format(self.i))
        self.layout_content.add_widget(myObj)
        if self.i % 4 == 0:
            self.h += dp(420)
        self.updateBar()
        self.i += 1
        if self.i >= 100:
            self.clock.cancel()

    def refresh(self):
        self.tab1_refresh_btn.enabled = False
        self.clock =Clock.schedule_interval(self.addSeveralObjects, .05)
        self.resetRefreshButton()

    def resetRefreshButton(self):
        self.tab1_refresh_btn.text = 'Last Refresh: {}'.format(time.ctime())
        self.tab1_refresh_btn.enabled = True

    def updateBar(self):
        self.tab1_pgbar.value += 1
...
</code>```

In your kv:

```<code><Controller>:
    ...
    TabbedPanelItem:
        ...
        BoxLayout:
            ...
            ScrollView:
                size_hint: 1.0,0.7
                GridLayout:
                    id: layout_content
                    height: root.h
                    size_hint_y: None
                    cols: 1
                    row_default_height: '100dp'
                    row_force_default: True
                    spacing: 0, 5
            ...
        ...
     ...
 ...
</code>```

Body:
I´m new to kivy and trying to create a scrollview that gets filled with several widgets live. That kind of works..
BUT the line items themselves often loose their own widgets and I often get this error:

[CRITICAL] [Clock       ] Warning, too much iteration done before the next frame. Check your code, or increase the Clock.max_iteration attribute

I read a lot of "clock", blocking the mainthread etc.. I tried to resolve it by using a different thread.. but still widgets are missing.

Attached the code and a picture. help is very much appreciated!! thx!

widgets missing..

my controller.kv

#:kivy 1.0

<Controller>:

    size_hint: 1., 1.
    pos_hint: {'center_x': .5, 'center_y': .5}
    do_default_tab: False

    tab1_pgbar: tab1_pgbar
    layout_content: layout_content
    tab1_refresh_btn: tab1_refresh_btn

    TabbedPanelItem:
        id: tab1
        text: 'Browse'

        BoxLayout:
            id: bl
            orientation: 'vertical'

            ScrollView:
                size_hint: 1.0,0.7

                GridLayout:
                    id: layout_content
                    size_hint_y: None
                    height: self.minimum_height
                    cols: 1
                    row_default_height: '100dp'
                    row_force_default: True
                    spacing: 0, 5

            BoxLayout:
                size_hint: 1.0,None
                height: 25

                ProgressBar:
                    size_hint: 1.0,1.0
                    id: tab1_pgbar
                    max: 1000

                Button:
                    id: tab1_refresh_btn
                    text: 'Refresh'
                    size: 100,25
                    on_release: root.refresh()

my kivyMain.py

import kivy
kivy.require('1.10.0')

from kivy.uix.boxlayout import BoxLayout
from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.clock import mainthread

import time
import threading

class myJobEntry(BoxLayout):
    def __init__(self):
        super(myJobEntry, self).__init__()

    def addStuff(self,runindex,program):
        b1 = Button(text=runindex,size_hint=(None,1.0),width=100)
        b2 = TextInput(text=program,height=80)

        hbox1 = BoxLayout(orientation='horizontal')
        for i in range(10):
            hbox1.add_widget(Button(text='{}'.format(i)))

        vbox1 = BoxLayout(orientation='vertical')
        vbox1.add_widget(hbox1)
        vbox1.add_widget(b2)

        self.add_widget(b1)
        self.add_widget(vbox1)

class Controller(TabbedPanel):
    '''Create a controller that receives a custom widget from the kv lang file.
    Add an action to be called from the kv lang file.
    '''
    layout_content = ObjectProperty()
    tab1_refresh_btn = ObjectProperty()
    tab1_pgbar = ObjectProperty()
    text_input = ObjectProperty()

    def addSeveralObjects(self):
        self.tab1_pgbar.value = 0
        self.layout_content.enabled=False

        for i in range(100):
            myObj = myJobEntry()
            myObj.addStuff('{}'.format(i),'i')
            self.layout_content.add_widget(myObj)
            self.updateBar()

    def refresh(self):
        self.tab1_refresh_btn.enabled = False
        self.tab1_pgbar.value = 1

        mythread = threading.Thread(target=self.addSeveralObjects)
        mythread.start()

        self.resetRefreshButton()

    def resetRefreshButton(self):
        self.tab1_refresh_btn.text = 'Last Refresh: {}'.format(time.ctime())
        self.tab1_refresh_btn.enabled = True

    def updateBar(self):
        self.tab1_pgbar.value += 1

class ControllerApp(App):

    def build(self):
        return Controller()

if __name__ == '__main__':
    ControllerApp().run()

Body:
I guess the problem is your thread, a better option is to use the kivy Clock object:

...
from kivy.clock import Clock
from kivy.properties import NumericProperty
from kivy.metrics import dp
...

class Controller(TabbedPanel):
    '''Create a controller that receives a custom widget from the kv lang file.
    Add an action to be called from the kv lang file.
    '''
    layout_content = ObjectProperty()
    tab1_refresh_btn = ObjectProperty()
    tab1_pgbar = ObjectProperty()
    text_input = ObjectProperty()
    i = 0
    h = NumericProperty(0)

    def addSeveralObjects(self, *args):
        self.layout_content.enabled = False
        myObj = myJobEntry()
        myObj.addStuff('{}'.format(self.i), '{}'.format(self.i))
        self.layout_content.add_widget(myObj)
        if self.i % 4 == 0:
            self.h += dp(420)
        self.updateBar()
        self.i += 1
        if self.i >= 100:
            self.clock.cancel()

    def refresh(self):
        self.tab1_refresh_btn.enabled = False
        self.clock =Clock.schedule_interval(self.addSeveralObjects, .05)
        self.resetRefreshButton()

    def resetRefreshButton(self):
        self.tab1_refresh_btn.text = 'Last Refresh: {}'.format(time.ctime())
        self.tab1_refresh_btn.enabled = True

    def updateBar(self):
        self.tab1_pgbar.value += 1
...

In your kv:

<Controller>:
    ...
    TabbedPanelItem:
        ...
        BoxLayout:
            ...
            ScrollView:
                size_hint: 1.0,0.7
                GridLayout:
                    id: layout_content
                    height: root.h
                    size_hint_y: None
                    cols: 1
                    row_default_height: '100dp'
                    row_force_default: True
                    spacing: 0, 5
            ...
        ...
     ...
 ...


问:
Passing multiple variables not files to jq command
I have two variables in shell script, each one contains a JSON data.

I wanted to merge these using command

```<code>jq '.' $var1 $var2
</code>```

where echo $var1 => {"key1": "value1"}

```<code>echo $var2 => {"key2": "value2"}
</code>```

but it does not work, however when i write contents of these variables into file1 and file2 respectively, It works fine jq '.' file1.json file2.json
it works perfectly.
Any help regarding how to pass multiple variables to jq command will be appreciated.

答:
If by "merge" you mean something like jq's add, then you could simply write:

```<code>jq -n "$var1 + $var2"
</code>```

More generally, if your jq supports the --argson command-line option, then you could use it; otherwise, you could use —arg but some care would then be needed to do any required conversions. In either case, you will probably also want to use the -n command-line option.

If you are using a shell such as bash, another set of options is based on process substitution, e.g.

```<code>jq -s add <(echo "$var1") <(echo "$var2")
</code>```

If your echo is unsuitable, you could use some other alternative (e.g. printf).

If process substitution is overkill, then another option, as @chepner pointed out, is simply to use "$var1 $var2", e.g.

```<code>jq -s add "$var1 $var2"
</code>```

Finally, if the shell variables have been exported (i.e., if they are available as "environment" variables), then you can use jq's env function: env.var1 + env.var2

Body:
I have two variables in shell script, each one contains a JSON data.

I wanted to merge these using command

jq '.' $var1 $var2

where echo $var1 => {"key1": "value1"}

echo $var2 => {"key2": "value2"}

but it does not work, however when i write contents of these variables into file1 and file2 respectively, It works fine jq '.' file1.json file2.json
it works perfectly.
Any help regarding how to pass multiple variables to jq command will be appreciated.

Body:
If by "merge" you mean something like jq's add, then you could simply write:

jq -n "$var1 + $var2"

More generally, if your jq supports the --argson command-line option, then you could use it; otherwise, you could use —arg but some care would then be needed to do any required conversions. In either case, you will probably also want to use the -n command-line option.

If you are using a shell such as bash, another set of options is based on process substitution, e.g.

jq -s add <(echo "$var1") <(echo "$var2")

If your echo is unsuitable, you could use some other alternative (e.g. printf).

If process substitution is overkill, then another option, as @chepner pointed out, is simply to use "$var1 $var2", e.g.

jq -s add "$var1 $var2"

Finally, if the shell variables have been exported (i.e., if they are available as "environment" variables), then you can use jq's env function: env.var1 + env.var2


问:
Function Now: Tdatetime for Perpetual Calendar
I am trying to write a function for Tdatetime (but when I open my program, he must show now data)

Below i have a function for TDatetime but I have an error in that:

((((''DecodeDateTime(data, rok, miesiac, dzien, godzina, minuta, sekunda, milisekunda);''))))

```<code>unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Spin, Buttons;

type
  TForm1 = class(TForm)
    edRok: TSpinEdit;
    edMiesiac: TSpinEdit;
    edDzien: TSpinEdit;
    lbRok: TLabel;
    lbMiesiac: TLabel;
    lbDzien: TLabel;
    lbDT: TLabel;
    btnZamknij: TBitBtn;
    procedure edRokChange(Sender: TObject);
    procedure edDzienChange(Sender: TObject);
    procedure DecodeDate(Date: TDateTime);
    function DT(Dzien, Miesiac: Byte; Rok: Integer): Byte;
    function GetDzienText(Dt: Byte): String;
    function Now: TDateTime;

  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.edRokChange(Sender: TObject);
begin
 case edMiesiac.Value of
  1,3,5,7,8,10,12: edDzien.MaxValue:=31;
  4,6,9,11: edDzien.MaxValue:=30;
 else
  if edRok.Value mod 4=0 then edDzien.MaxValue:=29
  else edDzien.MaxValue:=28;
 end;{case}
 if edDzien.Value>edDzien.MaxValue then
  edDzien.Value:=edDzien.MaxValue;
  edDzienChange(Sender);
end;

procedure TForm1.edDzienChange(Sender: TObject);
begin
 lbDt.Caption:='Dzień tygodnia: '+GetDzienText(DT(eddzien.value, edmiesiac.value, edrok.value));
end;

procedure TForm1.DecodeDate(Date: TDateTime);
var
 Now, Rok, Miesiac, Dzien: Word;
begin
DecodeDate(Now);
DecodeDate(Rok);
DecodeDate(Miesiac);
DecodeDate(Dzien);
edRok.Value:=Rok;
edMiesiac.Value:=Miesiac;
edDzien.Value:=Dzien;
end;

function TForm1.DT(Dzien, Miesiac: Byte; Rok: Integer): Byte;
var m,r,w: Byte; {deklaracja zmiennych}
begin
 if Miesiac>2 then m:=miesiac-2
 else
  begin
   m:=miesiac+10;
   rok:=rok-1;
  end;
  r:=rok mod 100;
  w:=rok div 100;
 Result:=((13*m-1) div 5+dzien+r div 4+w div 4+r+5*w) mod 7;
end;

function TForm1.GetDzienText(Dt: Byte): String;
const Dni: array[0..6] of String=
      ('Niedziela','Poniedziałek','Wtorek','Środa',
       'Czwartek','Piątek','Sobota');
begin
 Result:=Dni[dt];
end;

function TForm1.Now: TDateTime;
var
  dzien, miesiac, rok: Word;
  godzina, minuta, sekunda, milisekunda: Word;
  data: TDateTime;

begin
  data := Now;
  DecodeDateTime(data, rok, miesiac, dzien, godzina, minuta, sekunda, milisekunda);
  MessageBox(0,PAnsiChar(Format('Data: %d/%d/%d %d:%d:%d:%d',[rok, miesiac, dzien, godzina, minuta, sekunda, milisekunda])), 'Data', MB_ICONINFORMATION);
end;

end.
</code>```

答:
Change

```<code>data := Now;
</code>```

to

```<code>data := SysUtils.Now;
</code>```

You are calling Now recursively.

Body:
I am trying to write a function for Tdatetime (but when I open my program, he must show now data)

Below i have a function for TDatetime but I have an error in that:

((((''DecodeDateTime(data, rok, miesiac, dzien, godzina, minuta, sekunda, milisekunda);''))))

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Spin, Buttons;

type
  TForm1 = class(TForm)
    edRok: TSpinEdit;
    edMiesiac: TSpinEdit;
    edDzien: TSpinEdit;
    lbRok: TLabel;
    lbMiesiac: TLabel;
    lbDzien: TLabel;
    lbDT: TLabel;
    btnZamknij: TBitBtn;
    procedure edRokChange(Sender: TObject);
    procedure edDzienChange(Sender: TObject);
    procedure DecodeDate(Date: TDateTime);
    function DT(Dzien, Miesiac: Byte; Rok: Integer): Byte;
    function GetDzienText(Dt: Byte): String;
    function Now: TDateTime;

  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.edRokChange(Sender: TObject);
begin
 case edMiesiac.Value of
  1,3,5,7,8,10,12: edDzien.MaxValue:=31;
  4,6,9,11: edDzien.MaxValue:=30;
 else
  if edRok.Value mod 4=0 then edDzien.MaxValue:=29
  else edDzien.MaxValue:=28;
 end;{case}
 if edDzien.Value>edDzien.MaxValue then
  edDzien.Value:=edDzien.MaxValue;
  edDzienChange(Sender);
end;

procedure TForm1.edDzienChange(Sender: TObject);
begin
 lbDt.Caption:='Dzień tygodnia: '+GetDzienText(DT(eddzien.value, edmiesiac.value, edrok.value));
end;

procedure TForm1.DecodeDate(Date: TDateTime);
var
 Now, Rok, Miesiac, Dzien: Word;
begin
DecodeDate(Now);
DecodeDate(Rok);
DecodeDate(Miesiac);
DecodeDate(Dzien);
edRok.Value:=Rok;
edMiesiac.Value:=Miesiac;
edDzien.Value:=Dzien;
end;

function TForm1.DT(Dzien, Miesiac: Byte; Rok: Integer): Byte;
var m,r,w: Byte; {deklaracja zmiennych}
begin
 if Miesiac>2 then m:=miesiac-2
 else
  begin
   m:=miesiac+10;
   rok:=rok-1;
  end;
  r:=rok mod 100;
  w:=rok div 100;
 Result:=((13*m-1) div 5+dzien+r div 4+w div 4+r+5*w) mod 7;
end;

function TForm1.GetDzienText(Dt: Byte): String;
const Dni: array[0..6] of String=
      ('Niedziela','Poniedziałek','Wtorek','Środa',
       'Czwartek','Piątek','Sobota');
begin
 Result:=Dni[dt];
end;

function TForm1.Now: TDateTime;
var
  dzien, miesiac, rok: Word;
  godzina, minuta, sekunda, milisekunda: Word;
  data: TDateTime;

begin
  data := Now;
  DecodeDateTime(data, rok, miesiac, dzien, godzina, minuta, sekunda, milisekunda);
  MessageBox(0,PAnsiChar(Format('Data: %d/%d/%d %d:%d:%d:%d',[rok, miesiac, dzien, godzina, minuta, sekunda, milisekunda])), 'Data', MB_ICONINFORMATION);
end;

end.

Body:
Change

data := Now;

to

data := SysUtils.Now;

You are calling Now recursively.


问:
How to copy file from host to container using Dockerfile
I have written a Dockerfile which looks like this

```<code>FROM ubuntu:12.04

RUN apt-get update
RUN apt-get install -y wget
</code>```

Now I'm having a file called abc.txt in my host machine. How can I copy it to this container. Is there any step that I can add in Dockerfile which copy from Host to Container.

答:
I faced this issue, I was not able to copy zeppelin [1GB] directory into docker container and was getting issue

COPY failed: stat
/var/lib/docker/tmp/docker-builder977188321/zeppelin-0.7.2-bin-all: no
such file or directory

I am using docker Version: 17.09.0-ce and resolved the issue with the following steps.

Step 1: copy zeppelin directory [which i want to copy into docker package]into directory contain "Dockfile"

Step 2: edit Dockfile and add command [location where we want to copy]
ADD ./zeppelin-0.7.2-bin-all /usr/local/

Step 3: go to directory which contain DockFile and run command [alternatives also available] docker build

Step 4:  docker image created Successfully with logs

Step 5/9 : ADD ./zeppelin-0.7.2-bin-all /usr/local/
---> 3691c902d9fe

Step 6/9 : WORKDIR $ZEPPELIN_HOME
---> 3adacfb024d8 ....
Successfully built b67b9ea09f02

Body:
I have written a Dockerfile which looks like this

FROM ubuntu:12.04

RUN apt-get update
RUN apt-get install -y wget

Now I'm having a file called abc.txt in my host machine. How can I copy it to this container. Is there any step that I can add in Dockerfile which copy from Host to Container.


问:
Bypass order by in subquery for getting recordcount of query
I have a function which executes a datareader with a given commandtext and invokes a given action for every data record returned by the reader.

Since the datareader is a forward-only reader i can not get the count of rows from the datareader. For invoking a progressbar i have to know the count of the records my datareader will return.

My current attempt looks like this:

```<code>protected void RunConversion(string commandText, Action<IDataRecord> actionConversion)
{
    try
    {
        var curIndex = 0;
        var maxIndex = this.Source.ExecuteScalar<int?>($"SELECT COUNT(*) FROM ({commandText}) AS QUERY"); //Here i try to get the count of rows from the result

        OnProgress?.Invoke(0);

        foreach (var dataRecord in this.Source.ExecuteReader(commandText))
        {
            try
            {
                actionConversion?.Invoke(dataRecord);
            }
            catch (Exception e)
            {
                OnReport?.Invoke($"Error: {e}{Environment.NewLine}");
            }
            finally
            {
                OnProgress?.Invoke((int)((double)++curIndex / maxIndex * 100f));
            }
        }
    }
    catch (Exception e)
    {
        OnReport?.Invoke($"Fatal Error: {e}{Environment.NewLine}");
        OnProgress?.Invoke(100);
    }
}
</code>```

The problem is, sometimes the commandText-Parameter contains a query which includes order by... without using top the order by is not allowed in subqueries.

Another attempt would be to provide a thrid parameter which is a query that only counts the result of my current commandText-Parameter. This would be no nice solution, since i have to write two queries and they can be pretty complex.

Any idea for a simple solution?

答:
You mention you can't use the count because you are using a DataReader. Are you showing a Progress Bar for the query? If so, I would suggest that instead of a progress bar, simply show a "wait" icon rather than executing a query twice and extending the time that the user has to wait just to display how long they will be waiting.

With that in mind, you have two options. The first being to do away with the progress bar and the SELECT COUNT(*) FROM (...); and simply pass the query as-is. Then when you execute it and get a result set back, you can count the records if you still need to show a progress bar for record processing. Granted, this has the downside of adding data transfer overhead to your operation if you aren't going to use the actual data, so it is up to you if it is worth that little extra debt.

Your second option would be to simply remove the ORDER BY portion of any queries by doing something like the following:

```<code>public string RemoveOrderBy(string query)
{
    return query.SubString(0, query.IndexOf("ORDER BY"));
}
</code>```

This would get rid of any ORDER BY statements, but if you have any other things that may not work in a sub-query you would have to account for them in the same way as above.

Body:
I have a function which executes a datareader with a given commandtext and invokes a given action for every data record returned by the reader.

Since the datareader is a forward-only reader i can not get the count of rows from the datareader. For invoking a progressbar i have to know the count of the records my datareader will return.

My current attempt looks like this:

protected void RunConversion(string commandText, Action<IDataRecord> actionConversion)
{
    try
    {
        var curIndex = 0;
        var maxIndex = this.Source.ExecuteScalar<int?>($"SELECT COUNT(*) FROM ({commandText}) AS QUERY"); //Here i try to get the count of rows from the result

        OnProgress?.Invoke(0);

        foreach (var dataRecord in this.Source.ExecuteReader(commandText))
        {
            try
            {
                actionConversion?.Invoke(dataRecord);
            }
            catch (Exception e)
            {
                OnReport?.Invoke($"Error: {e}{Environment.NewLine}");
            }
            finally
            {
                OnProgress?.Invoke((int)((double)++curIndex / maxIndex * 100f));
            }
        }
    }
    catch (Exception e)
    {
        OnReport?.Invoke($"Fatal Error: {e}{Environment.NewLine}");
        OnProgress?.Invoke(100);
    }
}

The problem is, sometimes the commandText-Parameter contains a query which includes order by... without using top the order by is not allowed in subqueries.

Another attempt would be to provide a thrid parameter which is a query that only counts the result of my current commandText-Parameter. This would be no nice solution, since i have to write two queries and they can be pretty complex.

Any idea for a simple solution?

Body:
You mention you can't use the count because you are using a DataReader. Are you showing a Progress Bar for the query? If so, I would suggest that instead of a progress bar, simply show a "wait" icon rather than executing a query twice and extending the time that the user has to wait just to display how long they will be waiting.

With that in mind, you have two options. The first being to do away with the progress bar and the SELECT COUNT(*) FROM (...); and simply pass the query as-is. Then when you execute it and get a result set back, you can count the records if you still need to show a progress bar for record processing. Granted, this has the downside of adding data transfer overhead to your operation if you aren't going to use the actual data, so it is up to you if it is worth that little extra debt.

Your second option would be to simply remove the ORDER BY portion of any queries by doing something like the following:

public string RemoveOrderBy(string query)
{
    return query.SubString(0, query.IndexOf("ORDER BY"));
}

This would get rid of any ORDER BY statements, but if you have any other things that may not work in a sub-query you would have to account for them in the same way as above.


问:
Redirect parent page from iframe in iOS
I'm embedding an iFrame to an external payment-provider, after the user completes their step the user gets redirected to my domain.
I'm now trying to redirect the parent page to another page located on my domain like so:

iFrame embedded on mydomain.com

```<code><iframe src="example.com/payment" sandbox="allow-top-navigation allow-forms allow-scripts"></iframe>
</code>```

Code to redirect the parent page

```<code>window.top.location.href = "mydomain.com";
</code>```

On Safari in iOS I'm now getting: SecurityError: DOM Exception 18: An attempt was made to break through the security policy of the user agent.

Is this the expected behavior even though I used allow-top-navigation in my sandbox parameter?
If so, are there any existing workarounds?

答:
I found the answer myself.
My iframe sandbox attribute was missing the: allow-same-origin Parameter

Working Example

```<code><iframe src="example.com/payment" sandbox="allow-same-origin allow-top-navigation allow-forms allow-scripts"></iframe>
</code>```

Explanation

From what I understand the problem was the redirect of:
example.com/payment to mydomain.com this gets prevented by some browsers.
Sadly I found no clear explanation on why this particular redirect is prevented.
It seems to be related to: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy

Title: Redirect parent page from iframe in iOS

Body:
I'm embedding an iFrame to an external payment-provider, after the user completes their step the user gets redirected to my domain.
I'm now trying to redirect the parent page to another page located on my domain like so:

iFrame embedded on mydomain.com

Code to redirect the parent page

window.top.location.href = "mydomain.com";

On Safari in iOS I'm now getting: SecurityError: DOM Exception 18: An attempt was made to break through the security policy of the user agent.

Is this the expected behavior even though I used allow-top-navigation in my sandbox parameter?
If so, are there any existing workarounds?

Body:
I found the answer myself.
My iframe sandbox attribute was missing the: allow-same-origin Parameter

Working Example

<iframe src="example.com/payment" sandbox="allow-same-origin allow-top-navigation allow-forms allow-scripts"></iframe>

Explanation

From what I understand the problem was the redirect of:
example.com/payment to mydomain.com this gets prevented by some browsers.
Sadly I found no clear explanation on why this particular redirect is prevented.
It seems to be related to: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy


问:
SCRIPT1002: Syntax error in IE11 with React + Babel + Webpack
I'm trying to get my React App with ES2015 functionalities running in IE >= 11 using Webpack + Babel. The setup is custom, using the inferno-compat layer, so no create-react-app used here.

However - despite applying the latest babel-polyfill and babel-preset-env practices to my .babelrc and webpack config, I still get a SCRIPT1002: Syntax error within my bundle.js when trying to access the app with IE11.

When I follow the syntax error reference in IEs console, this is the part within the generated bundle.js that's conflicting (the arrow-function in particular):

```<code>function add(x, y) {
  if (y === undefined) {
    return yHolder => add(x, yHolder);
  }

  return x + y;
}
</code>```

These are the relevant dependencies within my package.json:

```<code>"dependencies": {
  "inferno-redux": "^3.10.1",
  "react": "^15.6.0",
  "react-dom": "^15.6.0",
  "react-ga": "^2.2.0",
  "react-swipeable": "^4.1.0",
  "redux": "^3.7.2",
  "redux-saga": "^0.16.0",
  "regenerator-runtime": "^0.11.0"
},
"devDependencies": {
  //... stuff

  "babel-cli": "^6.26.0",
  "babel-core": "^6.25.0",
  "babel-eslint": "^7.2.3",
  "babel-loader": "^7.1.1",
  "babel-plugin-inferno": "^3.2.0",
  "babel-plugin-module-resolver": "^2.7.1",
  "babel-plugin-transform-es2015-arrow-functions": "^6.22.0",
  "babel-plugin-transform-es2015-spread": "^6.22.0",
  "babel-plugin-transform-regenerator": "^6.26.0",
  "babel-plugin-transform-runtime": "^6.23.0",
  "babel-polyfill": "^6.26.0",
  "babel-preset-env": "^1.6.1",
  "babel-preset-es2015": "^6.24.1",
  "babel-preset-flow": "^6.23.0",
  "babel-preset-react": "^6.24.1",

  //... some more stuff

  "webpack": "^3.8.1",
  "webpack-bundle-analyzer": "^2.9.1",
  "webpack-dev-middleware": "^1.12.2",
  "webpack-dev-server": "^2.9.5",
  "webpack-manifest-plugin": "^1.3.2",
  "webpack-merge": "^4.1.1",
}
</code>```

This is my .babelrc:

```<code>{
  "presets":
    [
    "react",
    "flow",
    "es2015",
    [
      "env", {
        "modules": "commonjs",
        "targets": {
          "browsers": ["last 2 versions", "ie >= 11"]
        }
      }
    ]
  ]
}
</code>```

I include the babel-polyfill within my webpack.base.config.js here:

```<code>// ... stuff
entry: {
  index: ['babel-polyfill', './index.js'],
},
// ... more stuff
</code>```

Any ideas what's missing to get it running in IE11?

答:
I found the issue. I'm using the module rambdax as one of my devDependencies, which contains source code written in ES6 syntax (not transpiled to ES5) - more specifically arrow-functions => that are directly included within my bundle.js. IE11 of course can't execute arrow-functions or any other ES6 syntax.

Unfortunately neither Babel nor Webpack (UglifyJS Plugin) will touch the source of imported node_modules when compiling the bundle.js, which means: Module source code that gets imported as ES6 will remain ES6 in your webpack bundle.js.

See https://github.com/facebookincubator/create-react-app/issues/1125 for more information on this topic.

I also already filed an issue regarding this problem within the ´rambdax´ repository. You can find out more about it there: https://github.com/selfrefactor/rambdax/issues/4

Body:
I'm trying to get my React App with ES2015 functionalities running in IE >= 11 using Webpack + Babel. The setup is custom, using the inferno-compat layer, so no create-react-app used here.

However - despite applying the latest babel-polyfill and babel-preset-env practices to my .babelrc and webpack config, I still get a SCRIPT1002: Syntax error within my bundle.js when trying to access the app with IE11.

When I follow the syntax error reference in IEs console, this is the part within the generated bundle.js that's conflicting (the arrow-function in particular):

function add(x, y) {
  if (y === undefined) {
    return yHolder => add(x, yHolder);
  }

  return x + y;
}

These are the relevant dependencies within my package.json:

"dependencies": {
  "inferno-redux": "^3.10.1",
  "react": "^15.6.0",
  "react-dom": "^15.6.0",
  "react-ga": "^2.2.0",
  "react-swipeable": "^4.1.0",
  "redux": "^3.7.2",
  "redux-saga": "^0.16.0",
  "regenerator-runtime": "^0.11.0"
},
"devDependencies": {
  //... stuff

  "babel-cli": "^6.26.0",
  "babel-core": "^6.25.0",
  "babel-eslint": "^7.2.3",
  "babel-loader": "^7.1.1",
  "babel-plugin-inferno": "^3.2.0",
  "babel-plugin-module-resolver": "^2.7.1",
  "babel-plugin-transform-es2015-arrow-functions": "^6.22.0",
  "babel-plugin-transform-es2015-spread": "^6.22.0",
  "babel-plugin-transform-regenerator": "^6.26.0",
  "babel-plugin-transform-runtime": "^6.23.0",
  "babel-polyfill": "^6.26.0",
  "babel-preset-env": "^1.6.1",
  "babel-preset-es2015": "^6.24.1",
  "babel-preset-flow": "^6.23.0",
  "babel-preset-react": "^6.24.1",

  //... some more stuff

  "webpack": "^3.8.1",
  "webpack-bundle-analyzer": "^2.9.1",
  "webpack-dev-middleware": "^1.12.2",
  "webpack-dev-server": "^2.9.5",
  "webpack-manifest-plugin": "^1.3.2",
  "webpack-merge": "^4.1.1",
}

This is my .babelrc:

{
  "presets":
    [
    "react",
    "flow",
    "es2015",
    [
      "env", {
        "modules": "commonjs",
        "targets": {
          "browsers": ["last 2 versions", "ie >= 11"]
        }
      }
    ]
  ]
}

I include the babel-polyfill within my webpack.base.config.js here:

// ... stuff
entry: {
  index: ['babel-polyfill', './index.js'],
},
// ... more stuff

Any ideas what's missing to get it running in IE11?


问:
Java equivalent of Perl's hash
I've been using a lot Perl hashes due to super flexibility and convenient.
for instance, in Perl I can do the following:

```<code>$hash{AREA_CODE}->{PHONE}->{STREET_ADDR}
</code>```

I wondering how can I accomplish the same thing with Java, I guess it has something to do with HashMap?

Thanks,

答: If the hash keys are constant, why won't hash.getAreaCode().getPhone().getStreetAddr() do? Keep in mind that either your getters or your constructors will need to handle default value generation.

Title: Java equivalent of Perl's hash

Body:
I've been using a lot Perl hashes due to super flexibility and convenient.
for instance, in Perl I can do the following:

$hash{AREA_CODE}->{PHONE}->{STREET_ADDR}

I wondering how can I accomplish the same thing with Java, I guess it has something to do with HashMap?

Thanks,


问:
Creating a table, dropping it and referencing the results
I'm creating a table using multiple subselects. So I am getting data from multiple places within one SQL Database.

What I want is to 1. Set the above as a table itself and 2. create a new table using the above results.

So I will call the above [table1].

I just want to know how to set this as a (temporary) table so i can then start to add new script which I can use to the data I have now received in my new table to display.

答:
You might be looking for SELECT INTO clause:

```<code>Select (select Project.Number from Project where Project.ProjectID = PurchaseOrder.ProjectID) as [Project],
       PurchaseOrder.Number,
       (Select GoodsReceipt.ReceiptNumber from GoodReceipt where GoodsReceipt.ReferenceID = PurchaseOrder.PurchaseOrderID) as [GReceipt]
INTO TABLE1
From PurchaseOrder
</code>```

Body:
You might be looking for SELECT INTO clause:

Select (select Project.Number from Project where Project.ProjectID = PurchaseOrder.ProjectID) as [Project],
       PurchaseOrder.Number,
       (Select GoodsReceipt.ReceiptNumber from GoodReceipt where GoodsReceipt.ReferenceID = PurchaseOrder.PurchaseOrderID) as [GReceipt]
INTO TABLE1
From PurchaseOrder


问:
Return boolean if one element matches among 2 arrays in postgresql
I have 2 arrays in postgresql and I need to return true if there are at least 1 match of element between these 2 arrays no mather if it is same position.

Follows example below:

```<code>select array(select generate_series(0,10)) =
       any(select array(select generate_series(10,11)))
</code>```

it should return true because I have 10 in both arrays

答:
https://www.postgresql.org/docs/current/static/functions-array.html

=   equal

&&  overlap (have elements in common)

formatting mine. You need other operator

```<code>select array(select generate_series(0,10)) &&
       any(select array(select generate_series(10,11)));
 ?column?
----------
 t
(1 row)
</code>```

Body:
I have 2 arrays in postgresql and I need to return true if there are at least 1 match of element between these 2 arrays no mather if it is same position.

Follows example below:

select array(select generate_series(0,10)) =
       any(select array(select generate_series(10,11)))

it should return true because I have 10 in both arrays

Body:
https://www.postgresql.org/docs/current/static/functions-array.html

=   equal

&&  overlap (have elements in common)

formatting mine. You need other operator

select array(select generate_series(0,10)) &&
       any(select array(select generate_series(10,11)));
 ?column?
----------
 t
(1 row)


问:
vuelidate: validate items list that depend on its values
I need to validate the elements of a list in relation to a value of the element itself.

Is it possible or should I create a validation for each product?

```<code>new Vue({
    el: "#app",
  data: {
    text: '',
    sons: [
      {amount: 20, pending: 50},
      {amount: 30, pending: 150}
    ]
  },
  validations: {
    text: {
      required,
      minLength: minLength(5)
    },
    sons: {
      minLength: 3,
      $each: {
        amount: {
          maxValue: maxValue(this.sons[x].pending) // how to set x?
        }
      }
    }
  }
})
</code>```

https://jsfiddle.net/e0tL4yph/

答:
In the Vuelta repository, I published this question and the answer is:

In that case you want to use the second argument of validation function.

```<code>amount: {
  ltePending: (amount, { pending }) => amount <= pending
}
</code>```

It works as I wanted!

Body:
I need to validate the elements of a list in relation to a value of the element itself.

Is it possible or should I create a validation for each product?

new Vue({
    el: "#app",
  data: {
    text: '',
    sons: [
      {amount: 20, pending: 50},
      {amount: 30, pending: 150}
    ]
  },
  validations: {
    text: {
      required,
      minLength: minLength(5)
    },
    sons: {
      minLength: 3,
      $each: {
        amount: {
          maxValue: maxValue(this.sons[x].pending) // how to set x?
        }
      }
    }
  }
})

https://jsfiddle.net/e0tL4yph/

Body:
In the Vuelta repository, I published this question and the answer is:

In that case you want to use the second argument of validation function.

amount: {
  ltePending: (amount, { pending }) => amount <= pending
}

It works as I wanted!


问:
Is it possible continue a paused async function? (2)
I've made some changes in the previous code, running more tests, and I've run into the same problem again (Is it possible continue a stopped async function?). So this question is related.

Furthermore, the previous solution does not work.

var stop = false;
var pause = false;
var elParrafo = document.getElementById('miParrafo');

function sendPause() {
  pause = true;
}

function sendContinue() {
  pause = false;
}

function sendStop() {
  stop = true;
}

function longWork(ms, char) {
  return new Promise(function(resolve, reject) {
    elParrafo.innerHTML += char;
    setTimeout(resolve, ms);
  });
}

async function doIt() {
  for (var i = 0; i < 666; i++) {
    if (!stop) {
      if (!pause) {
        await longWork(50," > ");
      }
    } else {
      break;
    }
  }
}

doIt();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="" action="index.html" method="post">
  <input type="button" value="Pause" onclick="sendPause()">
  <input type="button" value="Continue" onclick="sendContinue()">
  <input type="button" value="Stop" onclick="sendStop()">
</form>
<p id="miParrafo"></p></code>```

答:
The issue occurs when you set the flags to true.  The async code exhausts the rest of the loop doing nothing by the time you unset the flags.  You can get around it with some promises instead.

let stop = false;
let isPaused = false;
let resolvePause = () => {};
let pauseProm = Promise.resolve();
const elParrafo = document.getElementById('miParrafo');

function sendPause() {
  if(isPaused) return;

  isPaused = true;
  pauseProm = new Promise(resolve => resolvePause = resolve);
}

function sendContinue() {
  isPaused = false;
  resolvePause();
}

function sendStop() {
  stop = true;
}

function longWork(ms, char) {
  return new Promise(function(resolve, reject) {
    elParrafo.innerHTML += char;
    setTimeout(resolve, ms);
  });
}

async function doIt() {
  for (let i = 0; i < 666; i++) {
    if (stop) break;

    await pauseProm;
    await longWork(50," > ");
  }
}

doIt();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="" action="index.html" method="post">
  <input type="button" value="Pause" onclick="sendPause()">
  <input type="button" value="Continue" onclick="sendContinue()">
  <input type="button" value="Stop" onclick="sendStop()">
</form>
<p id="miParrafo"></p></code>```

Body:
I've made some changes in the previous code, running more tests, and I've run into the same problem again (Is it possible continue a stopped async function?). So this question is related.

Furthermore, the previous solution does not work.

var stop = false;
var pause = false;
var elParrafo = document.getElementById('miParrafo');

function sendPause() {
  pause = true;
}

function sendContinue() {
  pause = false;
}

function sendStop() {
  stop = true;
}

function longWork(ms, char) {
  return new Promise(function(resolve, reject) {
    elParrafo.innerHTML += char;
    setTimeout(resolve, ms);
  });
}

async function doIt() {
  for (var i = 0; i < 666; i++) {
    if (!stop) {
      if (!pause) {
        await longWork(50," > ");
      }
    } else {
      break;
    }
  }
}

doIt();

<form class="" action="index.html" method="post">
  <input type="button" value="Pause" onclick="sendPause()">
  <input type="button" value="Continue" onclick="sendContinue()">
  <input type="button" value="Stop" onclick="sendStop()">
</form>

Body:
The issue occurs when you set the flags to true.  The async code exhausts the rest of the loop doing nothing by the time you unset the flags.  You can get around it with some promises instead.

let stop = false;
let isPaused = false;
let resolvePause = () => {};
let pauseProm = Promise.resolve();
const elParrafo = document.getElementById('miParrafo');

function sendPause() {
  if(isPaused) return;

  isPaused = true;
  pauseProm = new Promise(resolve => resolvePause = resolve);
}

function sendContinue() {
  isPaused = false;
  resolvePause();
}

function sendStop() {
  stop = true;
}

function longWork(ms, char) {
  return new Promise(function(resolve, reject) {
    elParrafo.innerHTML += char;
    setTimeout(resolve, ms);
  });
}

async function doIt() {
  for (let i = 0; i < 666; i++) {
    if (stop) break;

    await pauseProm;
    await longWork(50," > ");
  }
}

doIt();

<form class="" action="index.html" method="post">
  <input type="button" value="Pause" onclick="sendPause()">
  <input type="button" value="Continue" onclick="sendContinue()">
  <input type="button" value="Stop" onclick="sendStop()">
</form>
<p id="miParrafo"></p>


问:
Password doesn't hash before being saved into the db
I'm developing an app using Node.js, Mongoose, MongoDb, Express.

I'm trying to hash the password before being saved in the db when the user register, but it doesn't seems to work. The password is saved without hashing, any suggestions?

```<code>'use strict'

  let mongoose = require('mongoose')
  let bcrypt = require('bcrypt-nodejs')
   var Schema = mongoose.Schema

    var userSchema = Schema({
     name: { type: String, required: true, unique: true },
     password: { type: String, required: true },
     createdAt: {
     type: Date,
     require: true,
     default: Date.now
    }
   })
   // check if user already exists
   userSchema.path('name').validate(function (name) {
   User.findOne({name}, function (err, user) {
  if (err) {
  console.log('error')
  } if (user) {
  console.log('The user already exists')
    console.log(user)
  }
  })
}, 'The user already exists')

  // password validation

userSchema.path('password').validate(function (password) {
 return password.length >= 6
 }, 'The password must be of minimum length 6 characters.')
var User = mongoose.model('User', userSchema)

 // hashing and adding salt pre save()

   userSchema.pre('save', function (next) {
    bcrypt.genSalt(10, function (err, salt) {
    if (err) {
     return next(err)
     }
    bcrypt.hash(this.password, salt, null, function (err, hash) {
     // Store hash in your password DB.
    if (err) {
      return next(err)
    }
       // set the password to the hash
      this.password = hash
    })
    next()
 })
 })
  module.exports = User
</code>```

答:
Its because you do next() before bcrypt.hash callback is called. Move next() into bcrypt.hash callback.

```<code> userSchema.pre('save', function(next) {

    bcrypt.genSalt(10, function(err, salt) {

        if (err) {
            return next(err)
        }

        bcrypt.hash(this.password, salt, null, function(err, hash) {
            // Store hash in your password DB.
            if (err) {
                return next(err)
            }
            // set the password to the hash
            this.password = hash
            next()
        })

    })
})
</code>```

Body:
I'm developing an app using Node.js, Mongoose, MongoDb, Express.

I'm trying to hash the password before being saved in the db when the user register, but it doesn't seems to work. The password is saved without hashing, any suggestions?

'use strict'

  let mongoose = require('mongoose')
  let bcrypt = require('bcrypt-nodejs')
   var Schema = mongoose.Schema

    var userSchema = Schema({
     name: { type: String, required: true, unique: true },
     password: { type: String, required: true },
     createdAt: {
     type: Date,
     require: true,
     default: Date.now
    }
   })
   // check if user already exists
   userSchema.path('name').validate(function (name) {
   User.findOne({name}, function (err, user) {
  if (err) {
  console.log('error')
  } if (user) {
  console.log('The user already exists')
    console.log(user)
  }
  })
}, 'The user already exists')

  // password validation

userSchema.path('password').validate(function (password) {
 return password.length >= 6
 }, 'The password must be of minimum length 6 characters.')
var User = mongoose.model('User', userSchema)

 // hashing and adding salt pre save()

   userSchema.pre('save', function (next) {
    bcrypt.genSalt(10, function (err, salt) {
    if (err) {
     return next(err)
     }
    bcrypt.hash(this.password, salt, null, function (err, hash) {
     // Store hash in your password DB.
    if (err) {
      return next(err)
    }
       // set the password to the hash
      this.password = hash
    })
    next()
 })
 })
  module.exports = User

Body:
Its because you do next() before bcrypt.hash callback is called. Move next() into bcrypt.hash callback.

 userSchema.pre('save', function(next) {

    bcrypt.genSalt(10, function(err, salt) {

        if (err) {
            return next(err)
        }

        bcrypt.hash(this.password, salt, null, function(err, hash) {
            // Store hash in your password DB.
            if (err) {
                return next(err)
            }
            // set the password to the hash
            this.password = hash
            next()
        })

    })
})


答:
When you pause the task, you must actually pause it and wait until the user wants to continue, not continue your loop till the end but without doing any work.

var stopped;
var paused;
var waitingContinuations;

function sendStart() {
  stopped = false;
  paused = false;
  waitingContinuations = [];
  doIt();
}

function sendPause() {
  paused = true;
}

function sendContinue() {
  paused = false;
  for (const cont of waitingContinuations)
    cont();
  waitingContinuations.length = 0;
}

function sendStop() {
  stopped = true;
}

async function doIt() {
  document.getElementById('output').textContent = "";
  for (var i = 0; i < 666; i++) {
    // in places where you might want to abort, put this:
    if (stopped) return; // or throw new Error("stopped");
    // in places where you might want to pause, put this:
    if (paused) await new Promise(resolve => waitingContinuations.push(resolve));

    await longWork(50, " > ");
  }
}

function longWork(ms, char) {
  return new Promise(resolve => {
    document.getElementById('output').textContent += char;
    setTimeout(resolve, ms);
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <input type="button" value="Start" onclick="sendStart()">
  <input type="button" value="Pause" onclick="sendPause()">
  <input type="button" value="Continue" onclick="sendContinue()">
  <input type="button" value="Stop" onclick="sendStop()">
</form>
<p id="output"></p></code>```

Title: Is it possible continue a paused async function? (2)

Body:
When you pause the task, you must actually pause it and wait until the user wants to continue, not continue your loop till the end but without doing any work.

var stopped;
var paused;
var waitingContinuations;

function sendStart() {
  stopped = false;
  paused = false;
  waitingContinuations = [];
  doIt();
}

function sendPause() {
  paused = true;
}

function sendContinue() {
  paused = false;
  for (const cont of waitingContinuations)
    cont();
  waitingContinuations.length = 0;
}

function sendStop() {
  stopped = true;
}

async function doIt() {
  document.getElementById('output').textContent = "";
  for (var i = 0; i < 666; i++) {
    // in places where you might want to abort, put this:
    if (stopped) return; // or throw new Error("stopped");
    // in places where you might want to pause, put this:
    if (paused) await new Promise(resolve => waitingContinuations.push(resolve));

    await longWork(50, " > ");
  }
}

function longWork(ms, char) {
  return new Promise(resolve => {
    document.getElementById('output').textContent += char;
    setTimeout(resolve, ms);
  });
}

<form>
  <input type="button" value="Start" onclick="sendStart()">
  <input type="button" value="Pause" onclick="sendPause()">
  <input type="button" value="Continue" onclick="sendContinue()">
  <input type="button" value="Stop" onclick="sendStop()">
</form>
<p id="output"></p>


问:
How can I do "export $(dbus-launch) in booting
I'm using GDbus and make a dbus communication.
It using sesstion bus.

Problem is dbus-launch.

I was running dbus in Yocto with c++11.
And, I have to export $(dbus-launch).

But, I want to export $(dbus-launch) or same thing in booting time.
Because dbus start by systemd.

答:
One solution is to have a recipe that adds environment variable:

```<code>SRC_URI +=  "file://dbus-env.sh"

do_install_append() {
    install -d -m 0755 ${D}${sysconfdir}/profile.d
    install -m 0755 ${WORKDIR}/dbus-env.sh ${D}${sysconfdir}/profile.d/
}

FILES_${PN} += "${sysconfdir}/profile.d/dbus-env.sh"
</code>```

With dbus-env.sh

```<code>#!/bin/sh

export $(dbus-launch)
</code>```

Body:
One solution is to have a recipe that adds environment variable:

SRC_URI +=  "file://dbus-env.sh"

do_install_append() {
    install -d -m 0755 ${D}${sysconfdir}/profile.d
    install -m 0755 ${WORKDIR}/dbus-env.sh ${D}${sysconfdir}/profile.d/
}

FILES_${PN} += "${sysconfdir}/profile.d/dbus-env.sh"

With dbus-env.sh

#!/bin/sh

export $(dbus-launch)


问:
Swift 4: How to asynchronously use URLSessionDataTask but have the requests be in a timed queue?
Basically I have some JSON data that I wish to retrieve from a bunch of URL's (all from the same host), however I can only request this data roughly every 2 seconds at minimum and only one at a time or I'll be "time banned" from the server. As you'll see below; while URLSession is very quick it also gets me time banned almost instantly when I have around 700 urls to get through.

How would I go about creating a queue in URLSession (if its functionality supports it) and while having it work asynchronously to my main thread; have it work serially on its own thread and only attempt each item in the queue after 2 seconds have past since it finished the previous request?

```<code>for url in urls {
    get(url: url)
}

func get(url: URL) {
    let session = URLSession.shared
    let task = session.dataTask(with: url, completionHandler: { (data, response, error) in

        if let error = error {
            DispatchQueue.main.async {
                print(error.localizedDescription)
            }
            return
        }
        let data = data!

        guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
            DispatchQueue.main.async {
                print("Server Error")
            }
            return
        }
        if response.mimeType == "application/json" {
            do {
                let json = try JSONSerialization.jsonObject(with: data) as! [String: Any]
                if json["success"] as! Bool == true {
                    if let count = json["total_count"] as? Int {
                        DispatchQueue.main.async {
                            self.itemsCount.append(count)
                        }
                    }
                }
            } catch {
                print(error.localizedDescription)
            }
        }
    })
    task.resume()
}
</code>```

答:
The easiest way is to perform recursive call:

Imagine you have array with your urls.

In place where you initially perform for loop with, replace it with single call get(url:).
self.get(urls[0])

Then add this line at the and of response closure right after self.itemsCount.append(count):

```<code>self.urls.removeFirst()
Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { (_) in
self.get(url: urls[0])
}
</code>```

Body:
Basically I have some JSON data that I wish to retrieve from a bunch of URL's (all from the same host), however I can only request this data roughly every 2 seconds at minimum and only one at a time or I'll be "time banned" from the server. As you'll see below; while URLSession is very quick it also gets me time banned almost instantly when I have around 700 urls to get through.

How would I go about creating a queue in URLSession (if its functionality supports it) and while having it work asynchronously to my main thread; have it work serially on its own thread and only attempt each item in the queue after 2 seconds have past since it finished the previous request?

for url in urls {
    get(url: url)
}

func get(url: URL) {
    let session = URLSession.shared
    let task = session.dataTask(with: url, completionHandler: { (data, response, error) in

        if let error = error {
            DispatchQueue.main.async {
                print(error.localizedDescription)
            }
            return
        }
        let data = data!

        guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
            DispatchQueue.main.async {
                print("Server Error")
            }
            return
        }
        if response.mimeType == "application/json" {
            do {
                let json = try JSONSerialization.jsonObject(with: data) as! [String: Any]
                if json["success"] as! Bool == true {
                    if let count = json["total_count"] as? Int {
                        DispatchQueue.main.async {
                            self.itemsCount.append(count)
                        }
                    }
                }
            } catch {
                print(error.localizedDescription)
            }
        }
    })
    task.resume()
}

Body:
The easiest way is to perform recursive call:

Imagine you have array with your urls.

In place where you initially perform for loop with, replace it with single call get(url:).
self.get(urls[0])

Then add this line at the and of response closure right after self.itemsCount.append(count):

self.urls.removeFirst()
Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { (_) in
self.get(url: urls[0])
}


问:
How can I use individual json storage keys for use as the text on a button with kivy?
I am trying to take text input, save it to a jsonstore, then use each individual key in the jsonstore as the text on a button. I've read all the relevant documentation that I can think of, I've tried searching google, and I've tried searching on here. I've tried indexing the keys, but that isn't supported. I really just can't figure it out. It's the last main feature that I need to have everything running.

Here is my python script for the part I am talking about.

```<code>class ScreenSix(Screen):

def Create_ShopList(self):
    store = JsonStore('user_meals.json')
    ingredients = store.get(self._name.text)['ingredients']
    return ingredients

def Meal_Options(self):
    store = JsonStore('users_meals.json')
    meals = store.keys()
    return meals
</code>```

Here is the relevant part of my kv file.

```<code><ScreenSix>:
name: 'shoplist'
id: shoplist

FloatLayout:
    canvas:
        Rectangle:
            pos: self.pos
            size: self.size
            source: '20.png'

    Label:
        text: 'Create Shopping List'
        font_size: 60
        pos_hint: {'center_x':.5,'center_y':.8}
        color: 0,0,0,1

    Label:
        text: 'Which meals would you like to add?'
        font_size: 40
        pos_hint: {'center_x':.5,'center_y':.7}
        color: 0,0,0,1

    Button:
        text: 'Menu'
        font_size: 36
        size_hint: .2,.1
        pos_hint: {'left':1,'y':0}
        on_release: app.root.current='menu'

    Button:
        text: 'Quit'
        font_size: 36
        size_hint: .2,.1
        pos_hint: {'right':1,'y':0}
        on_release: app.root.current='open'

    Button:
        text: ''
        font_size: 36
        size_hint: .2,.1
        pos_hint: {'center_x':.18,'center_y':.6}
        on_release: root.Create_ShopList()

    Button:
        text: ''
        font_size: 36
        size_hint: .2,.1
        pos_hint: {'center_x':.39,'center_y':.6}

    Button:
        text: ''
        font_size: 36
        size_hint: .2,.1
        pos_hint: {'center_x':.6,'center_y':.6}

    Button:
        text: ''
        font_size: 36
        size_hint: .2,.1
        pos_hint: {'center_x':.81,'center_y':.6}
</code>```

I want to get the buttons text to be the names which are saved as the keys in my json storage. The last few buttons are the buttons I want the meal names to be on, and I'm using the first one as a test button while I try to figure it out. I'm worried that I might not be able to do it, and if that's the case I don't know what a good alternative would be.

答:
You could use RecycleView for this.

I made a little exapmle of this.

Try this:

```<code>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.uix.recycleview import RecycleView

from kivy.storage.jsonstore import JsonStore

store = JsonStore("buttons.json")

store.put('button1', font_size="40sp", color=(1,.5,.5, 1))
store.put('button2', font_size="20sp", color=(.5,1, 1, 1))
store.put('button3', font_size="30sp", color=(1,.5,.5, 1))
store.put('button4', font_size="10sp", color=(.5,1, 1, 1))

for i in store: store[i]["text"] = i

items = [store[i] for i in store]

class MyButton(Button):

    def print_data(self,data):
        print(data)

class MyRecycleView(RecycleView):

    def __init__(self, **kwargs):
        super(MyRecycleView,self).__init__(**kwargs)
        self.data = items
        self.refresh_from_data()

KV = '''

<MyButton>:
    on_release:
        root.print_data(self.text)

BoxLayout:
    orientation: 'vertical'
    MyRecycleView:
        id: rv
        viewclass: 'MyButton'
        RecycleBoxLayout:
            orientation: 'vertical'
            default_size: None, dp(56)
            default_size_hint: 1, None
            size_hint_y: None
            height: self.minimum_height

'''

class Test(App):
    def build(self):
        root = Builder.load_string(KV)
        return root

Test().run()
</code>```

Body:
I am trying to take text input, save it to a jsonstore, then use each individual key in the jsonstore as the text on a button. I've read all the relevant documentation that I can think of, I've tried searching google, and I've tried searching on here. I've tried indexing the keys, but that isn't supported. I really just can't figure it out. It's the last main feature that I need to have everything running.

Here is my python script for the part I am talking about.

class ScreenSix(Screen):

def Create_ShopList(self):
    store = JsonStore('user_meals.json')
    ingredients = store.get(self._name.text)['ingredients']
    return ingredients

def Meal_Options(self):
    store = JsonStore('users_meals.json')
    meals = store.keys()
    return meals

Here is the relevant part of my kv file.

<ScreenSix>:
name: 'shoplist'
id: shoplist

FloatLayout:
    canvas:
        Rectangle:
            pos: self.pos
            size: self.size
            source: '20.png'

    Label:
        text: 'Create Shopping List'
        font_size: 60
        pos_hint: {'center_x':.5,'center_y':.8}
        color: 0,0,0,1

    Label:
        text: 'Which meals would you like to add?'
        font_size: 40
        pos_hint: {'center_x':.5,'center_y':.7}
        color: 0,0,0,1

    Button:
        text: 'Menu'
        font_size: 36
        size_hint: .2,.1
        pos_hint: {'left':1,'y':0}
        on_release: app.root.current='menu'

    Button:
        text: 'Quit'
        font_size: 36
        size_hint: .2,.1
        pos_hint: {'right':1,'y':0}
        on_release: app.root.current='open'

    Button:
        text: ''
        font_size: 36
        size_hint: .2,.1
        pos_hint: {'center_x':.18,'center_y':.6}
        on_release: root.Create_ShopList()

    Button:
        text: ''
        font_size: 36
        size_hint: .2,.1
        pos_hint: {'center_x':.39,'center_y':.6}

    Button:
        text: ''
        font_size: 36
        size_hint: .2,.1
        pos_hint: {'center_x':.6,'center_y':.6}

    Button:
        text: ''
        font_size: 36
        size_hint: .2,.1
        pos_hint: {'center_x':.81,'center_y':.6}

I want to get the buttons text to be the names which are saved as the keys in my json storage. The last few buttons are the buttons I want the meal names to be on, and I'm using the first one as a test button while I try to figure it out. I'm worried that I might not be able to do it, and if that's the case I don't know what a good alternative would be.

Body:
You could use RecycleView for this.

I made a little exapmle of this.

Try this:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.uix.recycleview import RecycleView

from kivy.storage.jsonstore import JsonStore

store = JsonStore("buttons.json")

store.put('button1', font_size="40sp", color=(1,.5,.5, 1))
store.put('button2', font_size="20sp", color=(.5,1, 1, 1))
store.put('button3', font_size="30sp", color=(1,.5,.5, 1))
store.put('button4', font_size="10sp", color=(.5,1, 1, 1))

for i in store: store[i]["text"] = i

items = [store[i] for i in store]

class MyButton(Button):

    def print_data(self,data):
        print(data)

class MyRecycleView(RecycleView):

    def __init__(self, **kwargs):
        super(MyRecycleView,self).__init__(**kwargs)
        self.data = items
        self.refresh_from_data()

KV = '''

<MyButton>:
    on_release:
        root.print_data(self.text)

BoxLayout:
    orientation: 'vertical'
    MyRecycleView:
        id: rv
        viewclass: 'MyButton'
        RecycleBoxLayout:
            orientation: 'vertical'
            default_size: None, dp(56)
            default_size_hint: 1, None
            size_hint_y: None
            height: self.minimum_height

'''

class Test(App):
    def build(self):
        root = Builder.load_string(KV)
        return root

Test().run()