问:
python - Generate a random binary tree with n vertices
I am debugging an algorithms task, and for the purpose of testing I want to generate a binary tree with n vertices rooted at 0, in other words, generate a sequence of pairs so that if the i-th pair in the sequence is (a,b), then the left child of i-th node is a, and the right child is b, except when a (or b) = -1, then i-th node has no left (or right) child. (e. g. a sequence: (1, 2), (-1, -1), (-1, -1) is a tree with the root (0), and two children (1 and 2))
I wrote the following python recursive function, where listAdd is the desired pair list, listDel is all vertices not yet generated, and n is the node currently being looked at:

``` <code>
def generateTree(listAdd, listDel, n):
    if not listDel:
        return
    ifLeft = bool(randint(0,1))
    ifRight = bool(randint(0,1))
    if ifLeft:
        chosen = choice(listDel)
        listDel.remove(chosen)
        listAdd[n] = (chosen, listAdd[n][1])
        generateTree(listAdd, listDel, chosen)
    else:
        listAdd[n] = (-1, listAdd[n][1])
    if not listDel:
        return
    if ifRight:
        chosen = choice(listDel)
        listDel.remove(chosen)
        listAdd[n] = (listAdd[n][0], chosen)
        generateTree(listAdd, listDel, chosen)
    else:
        listAdd[n] = (listAdd[n][0], -1)
</code>```

However, upon writing it, I noticed that this does not work correctly, as it is possible for the function to stop after just one vertex, if ifLeft and ifRight both come out as false.

So my question is, what is a good way to generate such a tree? I don't need it to be in python, as it's only for generating an input file, all I need is a good algorithm, or another method of representing the tree so that it's easier to generate and can be converted into the desired format.

答:
You must not get a double zero when you're on the right end of your tree while still having some free elements, is that correct?

So I think you need to determine when this happens, AND force a recheck. There are 2 approaches that I can think of.

Make a function that checks where you are if you give it the root.

Create an array and populate it with 0,1 or "L","R". If you have

ifLeft == ifRight == 0

len(listDel) > 0 And

Checking the array, either:

If "L" not in check_array

if len(check_array) == sum(check_array)

Re-load the whole thing.

And by the way, you have to add the check to your array at the beginning of your function and remove it at the end. So its length will be like this:

0, 1, 2, 3, 4, 3, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 2, 1, 0

```<code>check_array = []

def generateTree(listAdd, listDel, n):
    if not listDel:
        return
    ifLeft = bool(randint(0,1))
    ifRight = bool(randint(0,1))

    if (ifLeft + ifRight == 0) and (
        "L" not in checked_array) and (
        len(listDel) > 0):
        // Force a 1, or use randint (you need a while-loop for it)
        ifLeft = 1

    if ifLeft:
        check_array.push("L")
        chosen = choice(listDel)
        listDel.remove(chosen)
        listAdd[n] = (chosen, listAdd[n][1])
        generateTree(listAdd, listDel, chosen)
        check_array = check_array[:-1]
    else:
        listAdd[n] = (-1, listAdd[n][1])
    if not listDel:
        return
    if ifRight:
        check_array.push("R")
        chosen = choice(listDel)
        listDel.remove(chosen)
        listAdd[n] = (listAdd[n][0], chosen)
        generateTree(listAdd, listDel, chosen)
        check_array = check_array[:-1]
    else:
        listAdd[n] = (listAdd[n][0], -1)
</code>```

Body:
I am debugging an algorithms task, and for the purpose of testing I want to generate a binary tree with n vertices rooted at 0, in other words, generate a sequence of pairs so that if the i-th pair in the sequence is (a,b), then the left child of i-th node is a, and the right child is b, except when a (or b) = -1, then i-th node has no left (or right) child. (e. g. a sequence: (1, 2), (-1, -1), (-1, -1) is a tree with the root (0), and two children (1 and 2))
I wrote the following python recursive function, where listAdd is the desired pair list, listDel is all vertices not yet generated, and n is the node currently being looked at:

def generateTree(listAdd, listDel, n):
    if not listDel:
        return
    ifLeft = bool(randint(0,1))
    ifRight = bool(randint(0,1))
    if ifLeft:
        chosen = choice(listDel)
        listDel.remove(chosen)
        listAdd[n] = (chosen, listAdd[n][1])
        generateTree(listAdd, listDel, chosen)
    else:
        listAdd[n] = (-1, listAdd[n][1])
    if not listDel:
        return
    if ifRight:
        chosen = choice(listDel)
        listDel.remove(chosen)
        listAdd[n] = (listAdd[n][0], chosen)
        generateTree(listAdd, listDel, chosen)
    else:
        listAdd[n] = (listAdd[n][0], -1)

However, upon writing it, I noticed that this does not work correctly, as it is possible for the function to stop after just one vertex, if ifLeft and ifRight both come out as false.

So my question is, what is a good way to generate such a tree? I don't need it to be in python, as it's only for generating an input file, all I need is a good algorithm, or another method of representing the tree so that it's easier to generate and can be converted into the desired format.

Body:
You must not get a double zero when you're on the right end of your tree while still having some free elements, is that correct?

So I think you need to determine when this happens, AND force a recheck. There are 2 approaches that I can think of.

Make a function that checks where you are if you give it the root.

Create an array and populate it with 0,1 or "L","R". If you have

ifLeft == ifRight == 0

len(listDel) > 0 And

Checking the array, either:

If "L" not in check_array

if len(check_array) == sum(check_array)

Re-load the whole thing.

And by the way, you have to add the check to your array at the beginning of your function and remove it at the end. So its length will be like this:

0, 1, 2, 3, 4, 3, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 2, 1, 0

check_array = []

def generateTree(listAdd, listDel, n):
    if not listDel:
        return
    ifLeft = bool(randint(0,1))
    ifRight = bool(randint(0,1))

    if (ifLeft + ifRight == 0) and (
        "L" not in checked_array) and (
        len(listDel) > 0):
        // Force a 1, or use randint (you need a while-loop for it)
        ifLeft = 1

    if ifLeft:
        check_array.push("L")
        chosen = choice(listDel)
        listDel.remove(chosen)
        listAdd[n] = (chosen, listAdd[n][1])
        generateTree(listAdd, listDel, chosen)
        check_array = check_array[:-1]
    else:
        listAdd[n] = (-1, listAdd[n][1])
    if not listDel:
        return
    if ifRight:
        check_array.push("R")
        chosen = choice(listDel)
        listDel.remove(chosen)
        listAdd[n] = (listAdd[n][0], chosen)
        generateTree(listAdd, listDel, chosen)
        check_array = check_array[:-1]
    else:
        listAdd[n] = (listAdd[n][0], -1)


来源: stackexchange

问:
How to properly assert that an exception gets raised in pytest?

Code:

```<code># coding=utf-8
import pytest

def whatever():
    return 9/0

def test_whatever():
    try:
        whatever()
    except ZeroDivisionError as exc:
        pytest.fail(exc, pytrace=True)
</code>```

Output:

```<code>================================ test session starts =================================
platform linux2 -- Python 2.7.3 -- py-1.4.20 -- pytest-2.5.2
plugins: django, cov
collected 1 items

pytest_test.py F

====================================== FAILURES ======================================
___________________________________ test_whatever ____________________________________

    def test_whatever():
        try:
            whatever()
        except ZeroDivisionError as exc:
>           pytest.fail(exc, pytrace=True)
E           Failed: integer division or modulo by zero

pytest_test.py:12: Failed
============================== 1 failed in 1.16 seconds ==============================
</code>```

How to make pytest print traceback, so I would see where in the whatever function an exception was raised?

答:
There are two ways to handle these kind of cases in pytest:

Using pytest.raises function

Using pytest.mark.xfail decorator

As the documentation says:

Using pytest.raises is likely to be better for cases where you are testing exceptions your own code is deliberately raising, whereas using @pytest.mark.xfail with a check function is probably better for something like documenting unfixed bugs (where the test describes what “should” happen) or bugs in dependencies.

Usage of pytest.raises:

```<code>def whatever():
    return 9/0
def test_whatever():
    with pytest.raises(ZeroDivisionError):
        whatever()
</code>```

Usage of pytest.mark.xfail:

```<code>@pytest.mark.xfail(raises=ZeroDivisionError)
def test_whatever():
    whatever()
</code>```

Output of pytest.raises:

```<code>============================= test session starts ============================
platform linux2 -- Python 2.7.10, pytest-3.2.3, py-1.4.34, pluggy-0.4.0 --
/usr/local/python_2.7_10/bin/python
cachedir: .cache
rootdir: /home/user, inifile:
collected 1 item

test_fun.py::test_whatever PASSED

======================== 1 passed in 0.01 seconds =============================
</code>```

Output of pytest.xfail marker:

```<code>============================= test session starts ============================
platform linux2 -- Python 2.7.10, pytest-3.2.3, py-1.4.34, pluggy-0.4.0 --
/usr/local/python_2.7_10/bin/python
cachedir: .cache
rootdir: /home/user, inifile:
collected 1 item

test_fun.py::test_whatever xfail

======================== 1 xfailed in 0.03 seconds=============================
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Code:

# coding=utf-8
import pytest

def whatever():
    return 9/0

def test_whatever():
    try:
        whatever()
    except ZeroDivisionError as exc:
        pytest.fail(exc, pytrace=True)

Output:

================================ test session starts =================================
platform linux2 -- Python 2.7.3 -- py-1.4.20 -- pytest-2.5.2
plugins: django, cov
collected 1 items

pytest_test.py F

====================================== FAILURES ======================================
___________________________________ test_whatever ____________________________________

    def test_whatever():
        try:
            whatever()
        except ZeroDivisionError as exc:
>           pytest.fail(exc, pytrace=True)
E           Failed: integer division or modulo by zero

pytest_test.py:12: Failed
============================== 1 failed in 1.16 seconds ==============================

How to make pytest print traceback, so I would see where in the whatever function an exception was raised?

Body:
There are two ways to handle these kind of cases in pytest:

Using pytest.raises function

Using pytest.mark.xfail decorator

As the documentation says:

Using pytest.raises is likely to be better for cases where you are testing exceptions your own code is deliberately raising, whereas using @pytest.mark.xfail with a check function is probably better for something like documenting unfixed bugs (where the test describes what “should” happen) or bugs in dependencies.

Usage of pytest.raises:

def whatever():
    return 9/0
def test_whatever():
    with pytest.raises(ZeroDivisionError):
        whatever()

Usage of pytest.mark.xfail:

@pytest.mark.xfail(raises=ZeroDivisionError)
def test_whatever():
    whatever()

Output of pytest.raises:

============================= test session starts ============================
platform linux2 -- Python 2.7.10, pytest-3.2.3, py-1.4.34, pluggy-0.4.0 --
/usr/local/python_2.7_10/bin/python
cachedir: .cache
rootdir: /home/user, inifile:
collected 1 item

test_fun.py::test_whatever PASSED

======================== 1 passed in 0.01 seconds =============================

Output of pytest.xfail marker:

============================= test session starts ============================
platform linux2 -- Python 2.7.10, pytest-3.2.3, py-1.4.34, pluggy-0.4.0 --
/usr/local/python_2.7_10/bin/python
cachedir: .cache
rootdir: /home/user, inifile:
collected 1 item

test_fun.py::test_whatever xfail

======================== 1 xfailed in 0.03 seconds=============================

ContentLicense: CC BY-SA 4.0


问:
Provide default arguments for subscript operator and function call operator
In the following code, I have provided default arguments for array subscript operator.

```<code>struct st
{
    int operator[](int x = 0)
    {
        // code here
    }
};
</code>```

But, compiler generated an error :

```<code>error: 'int st::operator[](int)' cannot have default arguments
     int operator[](int x = 0)
</code>```

But, If I provide default arguments for function call operator.

```<code>struct st
{
    int operator()(int x = 0)
    {
        // code here
    }
};
</code>```

It's working fine.

So, I have a questions:

Why doesn't allowed default arguments for the array subscript operator?

Why does allowed default arguments for the function call operator?

答:
The standard states it quite clearly.

The default arguments are not allowed in operator overloading of subscripting operator.

An operator function cannot have default arguments, except where explicitly stated below. Operator functions cannot have more or fewer parameters than the number required for the corresponding operator, as described in the rest of this subclause.

and

operator[] shall be a non-static member function with exactly one parameter.

While for function call operator

operator() shall be a non-static member function with an arbitrary number of parameters. It can have default arguments.

Overloaded operators try to follow the same behavior of the built-in ones; with the built-in subscript operator the (only one) index is always required, it doesn't have default arguments. Then the overloaded operator is not allowed to have default arguments either. On the other hand, functions are always fine to take arbitrary number of parameters and have default arguments.

Body:
In the following code, I have provided default arguments for array subscript operator.

struct st
{
    int operator[](int x = 0)
    {
        // code here
    }
};

But, compiler generated an error :

error: 'int st::operator[](int)' cannot have default arguments
     int operator[](int x = 0)

But, If I provide default arguments for function call operator.

struct st
{
    int operator()(int x = 0)
    {
        // code here
    }
};

It's working fine.

So, I have a questions:

Why doesn't allowed default arguments for the array subscript operator?

Why does allowed default arguments for the function call operator?


问:
Table structure for user activity feed - relational or not?
So I am stuck on a decision:

I am deciding wether to do something like this for a user activity feed:

```<code>id | userID | typeID | contentID | time
</code>```

OR something more relational with foreign keys and proper indexing like this:

```<code>id | userID | postID | postCommentID | photoID | photoCommentID | time
</code>```

Or along those lines.

I am looking for an answer which doesn't just say which one but also why and the advantages/disadvantages.

EDIT:

Another thing this applies to is wether using 1 comment table with type | contentID or postID | photoID is better OR 2 separate tables; one for photo comments and one for post comments??

EDIT 2:

How the data would be used:

It could be used in 2 scenarios - For displaying in a time line feed for the user themselves or other users around them.

EDIT 3:

The reason for choosing this method to create activity feeds even though all the detailed info is stored in other tables is for speed when loading feeds, although I understand I am sacrificing write performance. It also allows for me to add new data/post types later and reduces the number joins in my query to 0.

Thanks for your time!

-Stefan

答:
When you say feed - you mean for someone else's consumption?  Or for storing someone else's feed?  Or just a person's activity in your system?

I would normalize first, denormalize as you need to later, but neither of your options show the full story of the scope of what you are modeling.

ContentLicense: CC BY-SA 2.5

Body:
So I am stuck on a decision:

I am deciding wether to do something like this for a user activity feed:

id | userID | typeID | contentID | time

OR something more relational with foreign keys and proper indexing like this:

id | userID | postID | postCommentID | photoID | photoCommentID | time

Or along those lines.

I am looking for an answer which doesn't just say which one but also why and the advantages/disadvantages.

EDIT:

Another thing this applies to is wether using 1 comment table with type | contentID or postID | photoID is better OR 2 separate tables; one for photo comments and one for post comments??

EDIT 2:

How the data would be used:

It could be used in 2 scenarios - For displaying in a time line feed for the user themselves or other users around them.

EDIT 3:

The reason for choosing this method to create activity feeds even though all the detailed info is stored in other tables is for speed when loading feeds, although I understand I am sacrificing write performance. It also allows for me to add new data/post types later and reduces the number joins in my query to 0.

Thanks for your time!

-Stefan


问:
Simple: what's the CSS selector for this item?
sorry for this trivial question, but i just don't get it. I would like to set the witdh of this image:

```<code><img class='icon weather/mostlycloudy'
src="/fhem/images/default/weather/mostlycloudy.png" alt="mostlycloudy"
title="mostlycloudy">
</code>```

I've tried things like

```<code>[class~="weather"] {
    witdh:50px;
}

.img.icon {
    witdh:50px;
}
</code>```

and everything I could imagine, but the width attribute never appears if I check it with chromes inspect tool. I'm sure that I edit the correct .css file, because I can see the influence for other elements of that page. I surely am no html or css expert and maybe a bit dumb... Could you please help me?

答:
img is tag, so you dont use coma before it. icon is class, so before class you use coma

```<code>img.icon
</code>```

Body:
sorry for this trivial question, but i just don't get it. I would like to set the witdh of this image:

I've tried things like

[class~="weather"] {
    witdh:50px;
}

.img.icon {
    witdh:50px;
}

and everything I could imagine, but the width attribute never appears if I check it with chromes inspect tool. I'm sure that I edit the correct .css file, because I can see the influence for other elements of that page. I surely am no html or css expert and maybe a bit dumb... Could you please help me?

Body:
img is tag, so you dont use coma before it. icon is class, so before class you use coma

img.icon


问:
Java - Write and save data to txt file
I am writing a file writer that writes an ID and name, both of String to a text file. This asks for user input then stored the data in a txt file. But when I run this again any new data overrides the previous, therefore the data never save to a txt file.

Could anyone tell me how I would save this data so that any new data added is stored on the next line and not override the previous?

Thanks

答:
Activate append mode to the FileWritterby addig trueas second paremeter:

FileWriter write = new FileWriter(newTextFile, true);

Check FileWriter usage

Title: Java - Write and save data to txt file


问:
custom value in custom attribute jquery select option
i have this select option html with custom attribute

```<code><select id='voucher_dealer' name='voucher_dealer' class='form-control'><option value=''>اختر موزع</option>
        @foreach($dealers as $dealer)
            <option dealername='awad' value='{{$dealer->id}}'>{{$dealer->dealer_name}}</option>
        @endforeach
</select>
</code>```

now i want to get the value of dealername i did this

```<code> $("#voucher_dealer").change(function(){
    var dealer = $(this).val();
    var dealername = $(this).attr("dealername");
    alert(dealername);
});
</code>```

i get undefined how i can get the value of the attribute dealername

答:
Your selector is wrong.

Try this:

$("#voucher_dealer").change(function(){
  var dealer = $(this).val();
  var dealername = $('#voucher_dealer option:selected').attr("dealername");
  alert(dealername);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='voucher_dealer' name='voucher_dealer' class='form-control'>
  <option dealername='dsf' value=''>اختر موزع</option>
  <option selected dealername='awad' value='{{$dealer->id}}'>ajhbjkasdb</option>
</select></code>```

Body:
i have this select option html with custom attribute

<select id='voucher_dealer' name='voucher_dealer' class='form-control'><option value=''>اختر موزع</option>
        @foreach($dealers as $dealer)
            <option dealername='awad' value='{{$dealer->id}}'>{{$dealer->dealer_name}}</option>
        @endforeach
</select>

now i want to get the value of dealername i did this

 $("#voucher_dealer").change(function(){
    var dealer = $(this).val();
    var dealername = $(this).attr("dealername");
    alert(dealername);
});

i get undefined how i can get the value of the attribute dealername

Body:
Your selector is wrong.

Try this:

$("#voucher_dealer").change(function(){
  var dealer = $(this).val();
  var dealername = $('#voucher_dealer option:selected').attr("dealername");
  alert(dealername);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='voucher_dealer' name='voucher_dealer' class='form-control'>
  <option dealername='dsf' value=''>اختر موزع</option>
  <option selected dealername='awad' value='{{$dealer->id}}'>ajhbjkasdb</option>
</select>


问:
Convert date from milliseconds to ISODate object
I am trying to aggregate records in a MongoDB collection by hour and need to convert date stored as timestamp (milliseconds) to ISODate so that I can use aggregate framework's built-in date operators ($hour, $month, etc.)

Records are stored as

```<code>{
"data" : { "UserId" : "abc", "ProjId" : "xyz"},
"time" : NumberLong("1395140780706"),
"_id" : ObjectId("532828ac338ed9c33aa8eca7")
}
</code>```

I am trying to use an aggregate query of following type:

```<code>db.events.aggregate(
    {
       $match : {
         "time" : { $gte : 1395186209804, $lte : 1395192902825 }
       }
    },
    {
       $project : {
         _id : "$_id",
         dt : {$concat : (Date("$time")).toString()} // need to project as ISODate
       }
    },
    // process records further in $project or $group clause
)
</code>```

which produces results of the form:

```<code>{
    "result" : [
        {
            "_id" : ObjectId("5328da21fd207d9c3567d3ec"),
            "dt" : "Fri Mar 21 2014 17:35:46 GMT-0400 (EDT)"
        },
        {
            "_id" : ObjectId("5328da21fd207d9c3567d3ed"),
            "dt" : "Fri Mar 21 2014 17:35:46 GMT-0400 (EDT)"
        },
            ...
}
</code>```

I want to extract hour, day, month, and year from the date but since time is projected forward as string I am unable to use aggregate framework's built-in date operators ($hour, etc.).

How can I convert time from milliseconds to ISO date to do sometime like the following:

```<code>db.events.aggregate(
    {
        $match : {
            "time" : { $gte : 1395186209804, $lte : 1395192902825 }
        }
    },
    {
        $project : {
            _id : "$_id",
            dt : <ISO date from "$time">
        }
    },
    {
        $project : {
            _id : "$_id",
            date : {
                hour : {$hour : "$dt"}
            }
        }
    }
)
</code>```

答:
use this if {$add: [new Date(0), "$time"]} function returning string type not an ISO date type

I use all of that option but still fail, because my new date from $project return a string type like '2000-11-2:xxxxxxx' not date type like ISO('2000-11-2:xxxxxxx') for anyone who have same problem with me use this.

```<code>db.events.aggregate(
    {
        $project : {
            _id : "$_id",
            dt : {$add: [new Date(0), "$time"]}
        }
    },
    {
        $project : {
            _id : "$_id",
            "year": { $substr: [ "$dt", 0, 4 ] },
            "month": { $substr: [ "$dt", 5, 2] },
            "day": { $substr: [ "$dt", 8, 2 ] }
        }
    }
);
</code>```

the result will be

```<code> { _id: '59f940eaea87453b30f42cf5',
    year: '2017',
    month: '07',
    day: '04'
},
</code>```

you can get hours or minute if you want depending on which string you want to subset, then you can group that again according to same date,month or year

Body:
I am trying to aggregate records in a MongoDB collection by hour and need to convert date stored as timestamp (milliseconds) to ISODate so that I can use aggregate framework's built-in date operators ($hour, $month, etc.)

Records are stored as

{
"data" : { "UserId" : "abc", "ProjId" : "xyz"},
"time" : NumberLong("1395140780706"),
"_id" : ObjectId("532828ac338ed9c33aa8eca7")
}

I am trying to use an aggregate query of following type:

db.events.aggregate(
    {
       $match : {
         "time" : { $gte : 1395186209804, $lte : 1395192902825 }
       }
    },
    {
       $project : {
         _id : "$_id",
         dt : {$concat : (Date("$time")).toString()} // need to project as ISODate
       }
    },
    // process records further in $project or $group clause
)

which produces results of the form:

{
    "result" : [
        {
            "_id" : ObjectId("5328da21fd207d9c3567d3ec"),
            "dt" : "Fri Mar 21 2014 17:35:46 GMT-0400 (EDT)"
        },
        {
            "_id" : ObjectId("5328da21fd207d9c3567d3ed"),
            "dt" : "Fri Mar 21 2014 17:35:46 GMT-0400 (EDT)"
        },
            ...
}

I want to extract hour, day, month, and year from the date but since time is projected forward as string I am unable to use aggregate framework's built-in date operators ($hour, etc.).

How can I convert time from milliseconds to ISO date to do sometime like the following:

db.events.aggregate(
    {
        $match : {
            "time" : { $gte : 1395186209804, $lte : 1395192902825 }
        }
    },
    {
        $project : {
            _id : "$_id",
            dt : <ISO date from "$time">
        }
    },
    {
        $project : {
            _id : "$_id",
            date : {
                hour : {$hour : "$dt"}
            }
        }
    }
)

Body:
use this if {$add: [new Date(0), "$time"]} function returning string type not an ISO date type

I use all of that option but still fail, because my new date from $project return a string type like '2000-11-2:xxxxxxx' not date type like ISO('2000-11-2:xxxxxxx') for anyone who have same problem with me use this.

db.events.aggregate(
    {
        $project : {
            _id : "$_id",
            dt : {$add: [new Date(0), "$time"]}
        }
    },
    {
        $project : {
            _id : "$_id",
            "year": { $substr: [ "$dt", 0, 4 ] },
            "month": { $substr: [ "$dt", 5, 2] },
            "day": { $substr: [ "$dt", 8, 2 ] }
        }
    }
);

the result will be

 { _id: '59f940eaea87453b30f42cf5',
    year: '2017',
    month: '07',
    day: '04'
},

you can get hours or minute if you want depending on which string you want to subset, then you can group that again according to same date,month or year


问:
How to setup Kubernetes & Docker local environment for GCE on Windows 10 Home Edition?
I am new to Kubernetes and Docker, and trying to setup a good environment for working with GCE using the gcloud cli.

Since I am using Windows 10 Home Edition, I realized my only option to use Docker is installing Docker Toolbox, so any Docker commands can be run only from a VM (docker-machine, a boot2docker).
It also means, every time I want to create a docker image, I have to copy my local project folder to a share folder which the docker-machine would see, in order to build its image.

The docker-machine is a light version of linux, so it's not very user-friendly and difficult to use gcloud cli from.

I managed to work it all out up to the point where I want push my local docker image to my google's private registry.

gcloud cli is installed on my actual machine, can't be installed on the light-weight linux VM, so when I try to push the image from my Windows Powershell using:

```<code>gcloud docker -- push gcr.io/..../..
</code>```

I receive the following error:

ERROR: Docker CLI operation failed:

unknown flag: --email

See 'docker login --help'.

ERROR: (gcloud.docker) Docker login failed.

First, I'm not even sure if the image would be recognized, since it has been created on the docker-machine.

Second, I could not login to docker on my actual machine, since docker could not be installed, and any docker command should be made from inside the docker-machine.

So basically, now I'm stuck without being able to push my image. I feel like the whole process from the start has been very complicated, so it all made me wonder about my whole setup.

My question is, what would be the appropriate way to setup my environment for a smooth flow?

If you think the flow I described, given the fact I've been using Windows 10 Home, is the best I can achieve, I would appreciate your help with solving the pushing issue with the google cli.

答:
Do you have option of using  cloud shell? it works in browser and comes with all the tools pre-installed. https://cloud.google.com/shell/docs/quickstart.

if you want to use your laptop. install virutalbox and create centos Linux, then you can install all the tool on it. you should be able login using putty for your centos Linux.

Body:
I am new to Kubernetes and Docker, and trying to setup a good environment for working with GCE using the gcloud cli.

Since I am using Windows 10 Home Edition, I realized my only option to use Docker is installing Docker Toolbox, so any Docker commands can be run only from a VM (docker-machine, a boot2docker).
It also means, every time I want to create a docker image, I have to copy my local project folder to a share folder which the docker-machine would see, in order to build its image.

The docker-machine is a light version of linux, so it's not very user-friendly and difficult to use gcloud cli from.

I managed to work it all out up to the point where I want push my local docker image to my google's private registry.

gcloud cli is installed on my actual machine, can't be installed on the light-weight linux VM, so when I try to push the image from my Windows Powershell using:

gcloud docker -- push gcr.io/..../..

I receive the following error:

ERROR: Docker CLI operation failed:

unknown flag: --email

See 'docker login --help'.

ERROR: (gcloud.docker) Docker login failed.

First, I'm not even sure if the image would be recognized, since it has been created on the docker-machine.

Second, I could not login to docker on my actual machine, since docker could not be installed, and any docker command should be made from inside the docker-machine.

So basically, now I'm stuck without being able to push my image. I feel like the whole process from the start has been very complicated, so it all made me wonder about my whole setup.

My question is, what would be the appropriate way to setup my environment for a smooth flow?

If you think the flow I described, given the fact I've been using Windows 10 Home, is the best I can achieve, I would appreciate your help with solving the pushing issue with the google cli.


问:
Should I avoid Alternative Control Syntax?
As a mostly self-taught programmer, I have never really had anyone explain why certain things should or should not be used. One example (which I picked up years ago and use quite often) is the alternative control structure syntax:

```<code>x = (y == true) ? "foo" : "bar";
</code>```

I personally find this syntax easy to follow, especially for short, concise code, but I don't see it get a lot of use "in the wild" so I'd like to know if it's bad practice to use this over a more traditional if ... else structure?

Thanks in advance.

答: Except for when it's used in the most basic scenarios, I'll say avoid it. If 2 constructs are compiled to the same exact MSIL, why use the one that's difficult to understand?</p>

OwnerDisplayName: Chris

Body:
As a mostly self-taught programmer, I have never really had anyone explain why certain things should or should not be used. One example (which I picked up years ago and use quite often) is the alternative control structure syntax:

x = (y == true) ? "foo" : "bar";

I personally find this syntax easy to follow, especially for short, concise code, but I don't see it get a lot of use "in the wild" so I'd like to know if it's bad practice to use this over a more traditional if ... else structure?

Thanks in advance.

OwnerDisplayName: Tundey


问:
Question about adding three variables C++
Hey so im making a program to figure out a energy cost my program so far is, but I want the watt-hours to be for all three appliances not just one how do i do that?:</p>

```<code>#include <iostream>
using namespace std;

int main ()
{
   double watts, hours_per_day, watt_hours, dollars_per_wh;

   dollars_per_wh= .00008;

   cout << " How many Watts for the Air conditioner? ";
   cin >> watts;
   cout << " How many hours/day do you run the Air Conditioner? ";
   cin >> hours_per_day;

   cout << "How many Watts for the Television? " ;
   cin >> watts;
   cout << "How many hours/day do you run the Television? " ;
   cin >> hours_per_day;

   cout << "How many Watts for the Washer? " ;
   cin >> watts;
   cout << "How many hours/day do you run the Washer? " ;
   cin >> hours_per_day;

   watt_hours = watts * hours_per_day * 30;
   cout << "You have used " << watt_hours << " Watts-Hours of electricity." << endl;
</code>```

答:
I guess you could do the following with triple variables:

```<code>#include <iostream>
using namespace std;

int main ()
{
   double watts_ac, watts_tv, watts_wa;
   double hours_per_day_ac, hours_per_day_tv, hours_per_day_wa;
   double watt_hours, dollars_per_wh;

   dollars_per_wh= .00008;

   cout << " How many Watts for the Air conditioner? ";
   cin >> watts_ac;
   cout << " How many hours/day do you run the Air Conditioner? ";
   cin >> hours_per_day_ac;

   cout << "How many Watts for the Television? " ;
   cin >> watts_tv;
   cout << "How many hours/day do you run the Television? " ;
   cin >> hours_per_day_tv;

   cout << "How many Watts for the Washer? " ;
   cin >> watts_wa;
   cout << "How many hours/day do you run the Washer? " ;
   cin >> hours_per_day_wa;

   watt_hours = (watts_ac * hours_per_day_ac + watts_tv * hours_per_day_tv + watts_wa * hours_per_day_wa) * 30; //I'm not sure what this 30 factor is due to though.
   cout << "You have used " << watt_hours << " Watts-Hours of electricity." << endl;
}
</code>```

or just aggregate data:

```<code>#include <iostream>
using namespace std;

int main ()
{
   double watts, hours_per_day_ac, watt_hours, dollars_per_wh;

   dollars_per_wh= .00008;

   cout << " How many Watts for the Air conditioner? ";
   cin >> watts;
   cout << " How many hours/day do you run the Air Conditioner? ";
   cin >> hours_per_day;
   watts_hours = watts*hours_per_day;

   cout << "How many Watts for the Television? " ;
   cin >> watts;
   cout << "How many hours/day do you run the Television? " ;
   cin >> hours_per_day;
   watts_hours += watts*hours_per_day;

   cout << "How many Watts for the Washer? " ;
   cin >> watts;
   cout << "How many hours/day do you run the Washer? " ;
   cin >> hours_per_day;
   watts_hours += watts*hours_per_day;

   watt_hours *= 30; //I'm not sure what this 30 factor is due to though.
   cout << "You have used " << watt_hours << " Watts-Hours of electricity." << endl;
}
</code>```

Body:
Hey so im making a program to figure out a energy cost my program so far is, but I want the watt-hours to be for all three appliances not just one how do i do that?:

#include <iostream>
using namespace std;

int main ()
{
   double watts, hours_per_day, watt_hours, dollars_per_wh;

   dollars_per_wh= .00008;

   cout << " How many Watts for the Air conditioner? ";
   cin >> watts;
   cout << " How many hours/day do you run the Air Conditioner? ";
   cin >> hours_per_day;

   cout << "How many Watts for the Television? " ;
   cin >> watts;
   cout << "How many hours/day do you run the Television? " ;
   cin >> hours_per_day;

   cout << "How many Watts for the Washer? " ;
   cin >> watts;
   cout << "How many hours/day do you run the Washer? " ;
   cin >> hours_per_day;

   watt_hours = watts * hours_per_day * 30;
   cout << "You have used " << watt_hours << " Watts-Hours of electricity." << endl;

Body:
I guess you could do the following with triple variables:

#include <iostream>
using namespace std;

int main ()
{
   double watts_ac, watts_tv, watts_wa;
   double hours_per_day_ac, hours_per_day_tv, hours_per_day_wa;
   double watt_hours, dollars_per_wh;

   dollars_per_wh= .00008;

   cout << " How many Watts for the Air conditioner? ";
   cin >> watts_ac;
   cout << " How many hours/day do you run the Air Conditioner? ";
   cin >> hours_per_day_ac;

   cout << "How many Watts for the Television? " ;
   cin >> watts_tv;
   cout << "How many hours/day do you run the Television? " ;
   cin >> hours_per_day_tv;

   cout << "How many Watts for the Washer? " ;
   cin >> watts_wa;
   cout << "How many hours/day do you run the Washer? " ;
   cin >> hours_per_day_wa;

   watt_hours = (watts_ac * hours_per_day_ac + watts_tv * hours_per_day_tv + watts_wa * hours_per_day_wa) * 30; //I'm not sure what this 30 factor is due to though.
   cout << "You have used " << watt_hours << " Watts-Hours of electricity." << endl;
}

or just aggregate data:

#include <iostream>
using namespace std;

int main ()
{
   double watts, hours_per_day_ac, watt_hours, dollars_per_wh;

   dollars_per_wh= .00008;

   cout << " How many Watts for the Air conditioner? ";
   cin >> watts;
   cout << " How many hours/day do you run the Air Conditioner? ";
   cin >> hours_per_day;
   watts_hours = watts*hours_per_day;

   cout << "How many Watts for the Television? " ;
   cin >> watts;
   cout << "How many hours/day do you run the Television? " ;
   cin >> hours_per_day;
   watts_hours += watts*hours_per_day;

   cout << "How many Watts for the Washer? " ;
   cin >> watts;
   cout << "How many hours/day do you run the Washer? " ;
   cin >> hours_per_day;
   watts_hours += watts*hours_per_day;

   watt_hours *= 30; //I'm not sure what this 30 factor is due to though.
   cout << "You have used " << watt_hours << " Watts-Hours of electricity." << endl;
}


问:
Execute a shell command with python variables
I had script on bash where I generated username, password, ssh-key for user.
Part for creating of ssh-key:

```<code>su $user -c "ssh-keygen -f /home/$user/.ssh/id_rsa -t rsa -b 4096 -N ''"
</code>```

How can I do the same in Python with os.system? I tried this:

```<code>os.system('su %s -c "ssh-keygen -f /home/%s/.ssh/id_rsa -t rsa -b 4096 -N ''"', user)
TypeError: system() takes at most 1 argument (2 given)
</code>```

Also I tried:

```<code>os.system('su user -c "ssh-keygen -f /home/user/.ssh/id_rsa -t rsa -b 4096 -N ''"')
</code>```

Of course, it doesn't work either.

答:
Format your instructions with the os package; for instance:

```<code>import os

user = 'joe'
ssh_dir = "/home/{}/.ssh/id_rsa".format(user)
os.system("ssh-keygen -f {} -t rsa -b 4096 -N ''".format(ssh_dir))
</code>```

Body:
I had script on bash where I generated username, password, ssh-key for user.
Part for creating of ssh-key:

su $user -c "ssh-keygen -f /home/$user/.ssh/id_rsa -t rsa -b 4096 -N ''"

How can I do the same in Python with os.system? I tried this:

os.system('su %s -c "ssh-keygen -f /home/%s/.ssh/id_rsa -t rsa -b 4096 -N ''"', user)
TypeError: system() takes at most 1 argument (2 given)

Also I tried:

os.system('su user -c "ssh-keygen -f /home/user/.ssh/id_rsa -t rsa -b 4096 -N ''"')

Of course, it doesn't work either.

Body:
Format your instructions with the os package; for instance:

import os

user = 'joe'
ssh_dir = "/home/{}/.ssh/id_rsa".format(user)
os.system("ssh-keygen -f {} -t rsa -b 4096 -N ''".format(ssh_dir))


问:
phpmailer script on godaddy is not working
SMTP ERROR: Failed to connect to server: php_network_getaddresses: getaddrinfo failed: Name or service not known (0) 2017-11-15 13:11:07    SMTP connect() failed.

```<code><?php
require 'PHPMailerAutoload.php';
//echo !extension_loaded('openssl')?"Not Available":"Available <br/>";

$email = $_POST['email'];
$number = $_POST['phone'];
$client = $_POST['client'];

$to = 'myemailid@gmail.com';
$subject = 'user registration';
$phone = "phone number:".$number;
$message = "client details:"."\n"."email:".$email."\n"."phone number:".$number."\n"."client:".$client;
$headers = "From:".$email;

$mail = new PHPMailer;

$mail->SMTPDebug = 0;                               // Enable verbose debug output

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'hosting.secureserver.net';       //  ssl://smtp.gmail.com          // Specify main and backup SMTP servers
$mail->SMTPAuth = false;                               // Enable SMTP authentication
$mail->Username = '';                      // SMTP username
$mail->Password = '';                    // SMTP password

$mail->From = 'myemailid@gmail.com';

$mail->SMTPSecure = 'none';  //TLS                      // Enable TLS encryption, `ssl` also accepted
$mail->Port = 25;          //587                          // TCP port to connect to

$mail->setFrom($email);
$mail->addAddress($to);
$mail->Subject = $subject;
$mail->Body    = $message;

if($mail->send()) {
    header("Location: ../../thankyou.html");
}
else {
    echo $mail->ErrorInfo;
    //header("Location: ../../error.html");
}
?>
</code>```

this is the error i am receiving, as i am new to this php any detailed explanation would be highly appreciated. thank you

答: The host hosting.secureserver.net does not exist. You need to set the correct server and credentials for the outbound SMTP server. This information should be provided by whoever is hosting your email services - probably your web host.

Body:
SMTP ERROR: Failed to connect to server: php_network_getaddresses: getaddrinfo failed: Name or service not known (0) 2017-11-15 13:11:07    SMTP connect() failed.

<?php
require 'PHPMailerAutoload.php';
//echo !extension_loaded('openssl')?"Not Available":"Available
";

$email = $_POST['email'];
$number = $_POST['phone'];
$client = $_POST['client'];

$to = 'myemailid@gmail.com';
$subject = 'user registration';
$phone = "phone number:".$number;
$message = "client details:"."\n"."email:".$email."\n"."phone number:".$number."\n"."client:".$client;
$headers = "From:".$email;

$mail = new PHPMailer;

$mail->SMTPDebug = 0;                               // Enable verbose debug output

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'hosting.secureserver.net';       //  ssl://smtp.gmail.com          // Specify main and backup SMTP servers
$mail->SMTPAuth = false;                               // Enable SMTP authentication
$mail->Username = '';                      // SMTP username
$mail->Password = '';                    // SMTP password

$mail->From = 'myemailid@gmail.com';

$mail->SMTPSecure = 'none';  //TLS                      // Enable TLS encryption, `ssl` also accepted
$mail->Port = 25;          //587                          // TCP port to connect to

$mail->setFrom($email);
$mail->addAddress($to);
$mail->Subject = $subject;
$mail->Body    = $message;

if($mail->send()) {
    header("Location: ../../thankyou.html");
}
else {
    echo $mail->ErrorInfo;
    //header("Location: ../../error.html");
}
?>

this is the error i am receiving, as i am new to this php any detailed explanation would be highly appreciated. thank you


问:
Javascript formdata is empty when trying to append values in it
following is my code when i do console.log(formData);  its empty. Cannot see a reason for it to fail down.

```<code>$("#add_meal_item").on('click', '#save_meal_item', function () {
                var meal_name = $("#add_meal_item_form").find('#meal_name').val();
                var meal_type = $("#add_meal_item_form").find('#meal_type').val();
                var logoImg = $("#add_meal_item_form").find('#meal_image').get(0).files[0];
                var formData = new FormData();
                formData.append('logo', logoImg);
                formData.append('meal_type', meal_type);
                formData.append('meal_name', meal_name);
                console.log(formData);
                var ajax_url = baseurl + '/save_meal_item';
                $.ajax({
                    url: ajax_url,
                    type: 'POST',
                    data: formData,
                    success: function (response) {

                    }
                });

            });
</code>```

答:
FormData.append() doesn't create enumerable properties for formData, you need to use the iterator from FormData.entries to iterate the values.

Demo

var formData = new FormData();
formData.append('logo', "11");
formData.append('meal_type', "22");
formData.append('meal_name', "33");

console.log(Object.keys(formData)); //[]
console.log(JSON.stringify(formData)); //{}

//use iterator
var formEntries = formData.entries();
//console.log(formEntries.next().value);
//console.log(formEntries.next().value);
//console.log(formEntries.next().value);

//or simply use Array.from
var formEntries = Array.from(formData.entries());
console.log("formEntries " , formEntries); ```

Body:
following is my code when i do console.log(formData);  its empty. Cannot see a reason for it to fail down.

$("#add_meal_item").on('click', '#save_meal_item', function () {
                var meal_name = $("#add_meal_item_form").find('#meal_name').val();
                var meal_type = $("#add_meal_item_form").find('#meal_type').val();
                var logoImg = $("#add_meal_item_form").find('#meal_image').get(0).files[0];
                var formData = new FormData();
                formData.append('logo', logoImg);
                formData.append('meal_type', meal_type);
                formData.append('meal_name', meal_name);
                console.log(formData);
                var ajax_url = baseurl + '/save_meal_item';
                $.ajax({
                    url: ajax_url,
                    type: 'POST',
                    data: formData,
                    success: function (response) {

                    }
                });

            });


答:
Little change in your code

[class~="weather"] {
    width:50px;
}

img.icon {
    width:50px;
}```

Title: Simple: what's the CSS selector for this item?


问:
How to correctly configure the property "sonar.java.binaries"?
We are using SonarQube 5.1.2 using Ant runner 2.2 and Java pluging 3.12 for the analysis. I can succesfully analyse my project. I just keep getting this error:

```<code>Java bytecode has not been made available to the analyzer. The org.sonar.java.bytecode.visitor.DependenciesVisitor@d678716, org.sonar.java.checks.unused.UnusedPrivateMethodCheck@58e28efd, CycleBetweenPackages rule are disabled.
</code>```

So I need to configure my sonar.java.binaries and sonar.java.test.binaries properties (following http://docs.sonarqube.org/display/PLUG/Java+Plugin+and+Bytecode).

Which I think I have done correctly:

```<code><property name="project.dir" value="${basedir}/xalg.prj/h3_service_fo" />
<property name="sonar.java.binaries" location="${project.build.dir}/classes/main" />
<property name="sonar.java.test.binaries" value="${project.build.dir}/classes/test" />
</code>```

Which resolve to the following valid directories for the above properties:

```<code>basedir=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj
project.dir=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/xalg.prj/h3_service_fo
sonar.java.binaries=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\xalg.prj\\h3_service_fo\\build\\classes\\main
sonar.java.test.binaries=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/xalg.prj/h3_service_fo/build/classes/test
</code>```

But I keep getting:

```<code>Java bytecode has not been made available to the analyzer. The org.sonar.java.bytecode.visitor.DependenciesVisitor@d678716, org.sonar.java.checks.unused.UnusedPrivateMethodCheck@58e28efd, CycleBetweenPackages rule are disabled.
</code>```

And for the life of me, I can not figure out what values I need to give the sonar.java.binaries and sonar.java.test.binaries properties. I even tried using sonar.binaries, which gave me the following output:

```<code>Binary dirs: xalg.prj/h3_service_fo/build/classes
</code>```

Which I did not get using either sonar.java.binaries or sonar.java.test.binaries. I also got:

```<code>JavaClasspath initialization...
sonar.binaries and sonar.libraries are deprecated since version 2.5 of sonar-java-plugin, please use sonar.java.binaries and sonar.java.libraries instead
</code>```

Which is to be expected for a deprecated property. But using the sonar.java.binaries property I did not get the "Binary dirs" line in my log.

Using sonar.java.binaries:

```<code>Language is forced to java
Load rules
Load rules (done) | time=761ms
Code colorizer, supported languages: cs,plsql
Initializers :
Base dir: D:\appl\BuildAgent\work\H3\src.prj\java.prj
Working dir: D:\appl\BuildAgent\work\H3\src.prj\java.prj\.sonar
Source paths: xalg.prj/h3_service_fo/src/main/java
Test paths: xalg.prj/h3_service_fo/src/test/java
Source encoding: windows-1252, default locale: en_US
Index files
</code>```

Versus using sonar.binaries:

```<code>Language is forced to java
Load rules
Load rules (done) | time=736ms
Code colorizer, supported languages: cs,plsql
Initializers :
Base dir: D:\appl\BuildAgent\work\H3\src.prj\java.prj
Working dir: D:\appl\BuildAgent\work\H3\src.prj\java.prj\.sonar
Source paths: xalg.prj/h3_service_fo/src/main/java
Test paths: xalg.prj/h3_service_fo/src/test/java
Binary dirs: xalg.prj/h3_service_fo/build/classes
Source encoding: windows-1252, default locale: en_US
Index files
</code>```

I also looked into the source code of SonarQube, SonarQube Java Plugin and the SonarQube Scanner for instances of either "Java bytecode has not been made available to the analyzer." or sonar.java.binaries. I found plenty on sonar.java.binaries, but nothing on "Java bytecode has not been made available to the analyzer." So I have no clue what conditions exactly trigger that error.

I also tried the following permutations on sonar.java.binaries:

```<code><property name="sonar.java.binaries" location="${project.build.dir}/classes" />
<property name="sonar.java.binaries" location="${project.build.dir}/classes/main/nl" />
</code>```

But that did nothing either.

What is weird is that Squid seems to resolve the classpath just fine:

```<code>----- Classpath analyzed by Squid:
D:\appl\BuildAgent\work\H3\src.prj\java.prj\xalg.prj\h3_service_fo\build\classes\main
</code>```

So, what am I missing? What am I doing wrong? Thanks in advance.

Update 2016-09-08:

Removed the entire log, the post become to long.

A subset with the (I think) relevant paths:

```<code><property name="project.dir" value="${basedir}/xalg.prj/h3_service_fo" />
<property name="sonar.java.binaries" location="${project.build.dir}/classes/main" />
<property name="sonar.java.test.binaries" value="${project.build.dir}/classes/test" />
</code>```0

The paths have exactly the same format as in my post. Could it be that the Sonar Ant runner can't figure out a path with both backslashes and slashes?

Update 2016-09-16:

Removed the entire log, the post become to long.

A subset with the (I think) relevant paths:

```<code><property name="project.dir" value="${basedir}/xalg.prj/h3_service_fo" />
<property name="sonar.java.binaries" location="${project.build.dir}/classes/main" />
<property name="sonar.java.test.binaries" value="${project.build.dir}/classes/test" />
</code>```1

Some paths have become relative, but I think that is because TeamCity changed the Ant file to the file in SVN.
The sonar.java.binaries is absolute and it definitely points to the correct directory.

But I still get this error:

```<code><property name="project.dir" value="${basedir}/xalg.prj/h3_service_fo" />
<property name="sonar.java.binaries" location="${project.build.dir}/classes/main" />
<property name="sonar.java.test.binaries" value="${project.build.dir}/classes/test" />
</code>```2

The classpath is still interpreted just fine:

```<code>[sonar:sonar] 09:17:51.971 DEBUG - ----- Classpath analyzed by Squid:
[sonar:sonar] 09:17:51.972 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\xalg.prj\h3_service_fo\build\classes\main
[sonar:sonar] 09:17:51.973 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\batch.daemon.jar
[sonar:sonar] 09:17:51.974 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\buildinfo.jar
[sonar:sonar] 09:17:51.975 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h2_shared.jar
[sonar:sonar] 09:17:51.975 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_generator.jar
[sonar:sonar] 09:17:51.976 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_loadtest.jar
[sonar:sonar] 09:17:51.977 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_common.jar
[sonar:sonar] 09:17:51.977 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xalg.jar
[sonar:sonar] 09:17:51.978 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xalg_dao.jar
[sonar:sonar] 09:17:51.979 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xalg_mappers.jar
[sonar:sonar] 09:17:51.979 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xalg_procedures.jar
[sonar:sonar] 09:17:51.980 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xcare.jar
[sonar:sonar] 09:17:51.981 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xcare_dao.jar
[sonar:sonar] 09:17:51.982 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xcare_mappers.jar
[sonar:sonar] 09:17:51.982 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xcare_procedures.jar
</code>```

Could the Sonar Ant runner have a problem with the escaped back slashes?

答:
This is what I use, and it works.

```<code>sonar-scanner -Dsonar.projectKey=projectName
-Dsonar.gitlab.commit_sha=$CI_BUILD_REF
-Dsonar.gitlab.ref_name=$CI_BUILD_REF_NAME -Dsonar.sources=directory\src\
-Dsonar.java.binaries=.build\libs\
</code>```

You need to point sonar.java.binaries to a directory that contains jars. I would't try to get fancy with wildcards and file extensions, that's not the same thing. You need a directory as an argument, not a regular expression for files.

I don't know everything about sonar scanner, but my configuration works.

Take my example into context, I use it in a gitlab runner pipeline. Your double backslashes should be fine, but you can always substitute them for forwards slashes in your config files.

Body:
We are using SonarQube 5.1.2 using Ant runner 2.2 and Java pluging 3.12 for the analysis. I can succesfully analyse my project. I just keep getting this error:

Java bytecode has not been made available to the analyzer. The org.sonar.java.bytecode.visitor.DependenciesVisitor@d678716, org.sonar.java.checks.unused.UnusedPrivateMethodCheck@58e28efd, CycleBetweenPackages rule are disabled.

So I need to configure my sonar.java.binaries and sonar.java.test.binaries properties (following http://docs.sonarqube.org/display/PLUG/Java+Plugin+and+Bytecode).

Which I think I have done correctly:

<property name="project.dir" value="${basedir}/xalg.prj/h3_service_fo" />
<property name="sonar.java.binaries" location="${project.build.dir}/classes/main" />
<property name="sonar.java.test.binaries" value="${project.build.dir}/classes/test" />

Which resolve to the following valid directories for the above properties:

basedir=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj
project.dir=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/xalg.prj/h3_service_fo
sonar.java.binaries=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\xalg.prj\\h3_service_fo\\build\\classes\\main
sonar.java.test.binaries=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/xalg.prj/h3_service_fo/build/classes/test

But I keep getting:

Java bytecode has not been made available to the analyzer. The org.sonar.java.bytecode.visitor.DependenciesVisitor@d678716, org.sonar.java.checks.unused.UnusedPrivateMethodCheck@58e28efd, CycleBetweenPackages rule are disabled.

And for the life of me, I can not figure out what values I need to give the sonar.java.binaries and sonar.java.test.binaries properties. I even tried using sonar.binaries, which gave me the following output:

Binary dirs: xalg.prj/h3_service_fo/build/classes

Which I did not get using either sonar.java.binaries or sonar.java.test.binaries. I also got:

JavaClasspath initialization...
sonar.binaries and sonar.libraries are deprecated since version 2.5 of sonar-java-plugin, please use sonar.java.binaries and sonar.java.libraries instead

Which is to be expected for a deprecated property. But using the sonar.java.binaries property I did not get the "Binary dirs" line in my log.

Using sonar.java.binaries:

Language is forced to java
Load rules
Load rules (done) | time=761ms
Code colorizer, supported languages: cs,plsql
Initializers :
Base dir: D:\appl\BuildAgent\work\H3\src.prj\java.prj
Working dir: D:\appl\BuildAgent\work\H3\src.prj\java.prj\.sonar
Source paths: xalg.prj/h3_service_fo/src/main/java
Test paths: xalg.prj/h3_service_fo/src/test/java
Source encoding: windows-1252, default locale: en_US
Index files

Versus using sonar.binaries:

Language is forced to java
Load rules
Load rules (done) | time=736ms
Code colorizer, supported languages: cs,plsql
Initializers :
Base dir: D:\appl\BuildAgent\work\H3\src.prj\java.prj
Working dir: D:\appl\BuildAgent\work\H3\src.prj\java.prj\.sonar
Source paths: xalg.prj/h3_service_fo/src/main/java
Test paths: xalg.prj/h3_service_fo/src/test/java
Binary dirs: xalg.prj/h3_service_fo/build/classes
Source encoding: windows-1252, default locale: en_US
Index files

I also looked into the source code of SonarQube, SonarQube Java Plugin and the SonarQube Scanner for instances of either "Java bytecode has not been made available to the analyzer." or sonar.java.binaries. I found plenty on sonar.java.binaries, but nothing on "Java bytecode has not been made available to the analyzer." So I have no clue what conditions exactly trigger that error.

I also tried the following permutations on sonar.java.binaries:

<property name="sonar.java.binaries" location="${project.build.dir}/classes" />
<property name="sonar.java.binaries" location="${project.build.dir}/classes/main/nl" />

But that did nothing either.

What is weird is that Squid seems to resolve the classpath just fine:

----- Classpath analyzed by Squid:
D:\appl\BuildAgent\work\H3\src.prj\java.prj\xalg.prj\h3_service_fo\build\classes\main

So, what am I missing? What am I doing wrong? Thanks in advance.

Update 2016-09-08:

Removed the entire log, the post become to long.

A subset with the (I think) relevant paths:

project.build.dir=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/xalg.prj/h3_service_fo/build
project.dir=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/xalg.prj/h3_service_fo
project.src.dir=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/xalg.prj/h3_service_fo/src

sonar.dir=D\:/appl/sonarqube-5.1.2
sonar.working.directory=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\.sonar
sonar.projectBaseDir=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj

sonar.jacoco.reportPath=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/xalg.prj/h3_service_fo/build/jacoco/test.exec
sonar.junit.reportsPath=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/xalg.prj/h3_service_fo/build/test-results

sonar.sources=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/xalg.prj/h3_service_fo/src/main/java
sonar.java.binaries=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\xalg.prj\\h3_service_fo\\build\\classes\\main

sonar.java.libraries=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/_deploy/*.jar,D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/_repos/lib/*.jar,D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/_repos/provided/*.jar

sonar.tests=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/xalg.prj/h3_service_fo/src/test/java
sonar.java.test.binaries=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/xalg.prj/h3_service_fo/build/classes/test
sonar.java.test.libraries=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/_deploy/*.jar,D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/_repos/lib/*.jar,D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj/_repos/provided/*.jar

The paths have exactly the same format as in my post. Could it be that the Sonar Ant runner can't figure out a path with both backslashes and slashes?

Update 2016-09-16:

Removed the entire log, the post become to long.

A subset with the (I think) relevant paths:

project.build.dir=xalg.prj\\\\h3_service_fo\\\\build
project.dir=xalg.prj\\\\h3_service_fo
project.src.dir=xalg.prj\\\\h3_service_fo\\\\src

sonar.dir=D\:\\\\appl\\\\sonarqube-5.1.2
sonar.working.directory=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\.sonar
sonar.projectBaseDir=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj

sonar.jacoco.reportPath=xalg.prj\\\\h3_service_fo\\\\build\\\\jacoco/test.exec
sonar.junit.reportsPath=xalg.prj\\\\h3_service_fo\\\\build\\\\test-results

sonar.sources=xalg.prj\\\\h3_service_fo\\\\src\\\\main\\\\java
sonar.java.binaries=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\xalg.prj\\h3_service_fo\\build\\classes\\main
sonar.java.libraries=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\\\_deploy\\\\*.jar,D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\\\_repos\\\\lib\\\\*.jar,D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\\\_repos\\\\provided\\\\*.jar

sonar.tests=xalg.prj\\\\h3_service_fo\\\\src\\\\test\\\\java
sonar.java.test.binaries=xalg.prj\\\\h3_service_fo\\\\build\\\\classes\\\\test
sonar.java.test.libraries=D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\\\_deploy\\\\*.jar,D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\\\_repos\\\\lib\\\\*.jar,D\:\\appl\\BuildAgent\\work\\H3\\src.prj\\java.prj\\\\_repos\\\\provided\\\\*.jar

Some paths have become relative, but I think that is because TeamCity changed the Ant file to the file in SVN.
The sonar.java.binaries is absolute and it definitely points to the correct directory.

But I still get this error:

09:17:52.299 INFO  - Java Main Files AST scan done: 1579 ms
09:17:52.301 INFO  - 2/2 source files have been analyzed
09:17:52.305 WARN  - Java bytecode has not been made available to the analyzer. The org.sonar.java.bytecode.visitor.DependenciesVisitor@757a48f9, org.sonar.java.checks.unused.UnusedPrivateMethodCheck@1adf492b, CycleBetweenPackages rule are disabled.

The classpath is still interpreted just fine:

[sonar:sonar] 09:17:51.971 DEBUG - ----- Classpath analyzed by Squid:
[sonar:sonar] 09:17:51.972 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\xalg.prj\h3_service_fo\build\classes\main
[sonar:sonar] 09:17:51.973 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\batch.daemon.jar
[sonar:sonar] 09:17:51.974 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\buildinfo.jar
[sonar:sonar] 09:17:51.975 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h2_shared.jar
[sonar:sonar] 09:17:51.975 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_generator.jar
[sonar:sonar] 09:17:51.976 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_loadtest.jar
[sonar:sonar] 09:17:51.977 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_common.jar
[sonar:sonar] 09:17:51.977 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xalg.jar
[sonar:sonar] 09:17:51.978 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xalg_dao.jar
[sonar:sonar] 09:17:51.979 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xalg_mappers.jar
[sonar:sonar] 09:17:51.979 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xalg_procedures.jar
[sonar:sonar] 09:17:51.980 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xcare.jar
[sonar:sonar] 09:17:51.981 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xcare_dao.jar
[sonar:sonar] 09:17:51.982 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xcare_mappers.jar
[sonar:sonar] 09:17:51.982 DEBUG - D:\appl\BuildAgent\work\H3\src.prj\java.prj\_deploy\h3_model_xcare_procedures.jar

Could the Sonar Ant runner have a problem with the escaped back slashes?

Body:
This is what I use, and it works.

sonar-scanner -Dsonar.projectKey=projectName
-Dsonar.gitlab.commit_sha=$CI_BUILD_REF
-Dsonar.gitlab.ref_name=$CI_BUILD_REF_NAME -Dsonar.sources=directory\src\
-Dsonar.java.binaries=.build\libs\

You need to point sonar.java.binaries to a directory that contains jars. I would't try to get fancy with wildcards and file extensions, that's not the same thing. You need a directory as an argument, not a regular expression for files.

I don't know everything about sonar scanner, but my configuration works.

Take my example into context, I use it in a gitlab runner pipeline. Your double backslashes should be fine, but you can always substitute them for forwards slashes in your config files.


问:
Generating 'customers also bought' from table
I've got a 'cart' table as follows:

```<code>+----+---------+-----------+----------+----------+
| id | orderID | productID | quantity |  status  |
+----+---------+-----------+----------+----------+
|  1 |    3443 |       333 |        2 | complete |
|  2 |    3443 |       202 |        4 | complete |
+----+---------+-----------+----------+----------+
</code>```

And so foreach order, a new row gets added for each item in the cart.

So I want to get an 'customers also bought' from this table.  I'm using MySQL.

How can I do this? This is what I came up with at first:

```<code>SELECT * FROM `cart` WHERE `status` = 'complete' AND `productID` = '333' ORDER BY `ts` DESC
</code>```

But of course this only shows me the the rows with that productID in.  What I really want is the other products of orders that contain that productID.

How can I go about doing this?

答:
I'd probably do this with a self-join on the cart table:

```<code>Select Distinct mapped.productID
  From cart main
  Join cart mapped On main.orderID = mapped.orderID
 Where main.productID != mapped.productID
   And main.productID = 333
</code>```

Body:
I've got a 'cart' table as follows:

+----+---------+-----------+----------+----------+
| id | orderID | productID | quantity |  status  |
+----+---------+-----------+----------+----------+
|  1 |    3443 |       333 |        2 | complete |
|  2 |    3443 |       202 |        4 | complete |
+----+---------+-----------+----------+----------+

And so foreach order, a new row gets added for each item in the cart.

So I want to get an 'customers also bought' from this table.  I'm using MySQL.

How can I do this? This is what I came up with at first:

SELECT * FROM `cart` WHERE `status` = 'complete' AND `productID` = '333' ORDER BY `ts` DESC

But of course this only shows me the the rows with that productID in.  What I really want is the other products of orders that contain that productID.

How can I go about doing this?

Body:
I'd probably do this with a self-join on the cart table:

Select Distinct mapped.productID
  From cart main
  Join cart mapped On main.orderID = mapped.orderID
 Where main.productID != mapped.productID
   And main.productID = 333


答: You have to check if file with the same name exists already. If it does use that file. Because right now you create new file and overwrite old one every time.</p>

Title: Java - Write and save data to txt file

Body:
I am writing a file writer that writes an ID and name, both of String to a text file. This asks for user input then stored the data in a txt file. But when I run this again any new data overrides the previous, therefore the data never save to a txt file.

Could anyone tell me how I would save this data so that any new data added is stored on the next line and not override the previous?

Thanks


问:
git gui branch management
Hi I am an inexperienced Git user on Windows. I am using Git Gui.
I am interested in Branch Management.

My repo has a branch called 'leafy', how do I check this branch out to my local machine, and them cherry pick a commit from master into leafy?

Thanks a LOT

--MB

答:
To switch to the "leafy" branch:

```<code>git checkout leafy
</code>```

To cherry-pick a commit, given its SHA1 identifier:

```<code>git cherry-pick abc123
</code>```

Title: git gui branch management

Body:
To switch to the "leafy" branch:

git checkout leafy

To cherry-pick a commit, given its SHA1 identifier:

git cherry-pick abc123


问:
OOP design: class inherit class that contains field of class that inherit another class
Take a look at this code snippet:

```<code>public static class A {

    public void doA() {

    }

}

public static class B extends A {

    public void doB() {

    }

}

public static class AE {
    protected A field;

    public AE(A field) {
        this.field = field;
    }

    public void doStuff() {
        field.doA();
    }

}

public static class BE extends AE {

    // wanna have B field;

    public BE(B field) {
        super(field);
    }

    public void doAnotherStuff() {
        field.doA();
        field.doB(); // error here
    }

}
</code>```

What is the best solution for such design problem?
I see two options:
1) cast to B type field everytime when you need to call doB()

```<code>((B) field).doB();
</code>```

2) save B as another field fo BE class, and call this field when you need doB() functionality:

```<code>protected B field2;

    public BE(B field) {
        super(field);
        field2 = field;
    }
</code>```

Both solutions are obvious and isn't nice. In case 1) you lost performance on runtime casts, and cast field everytime looks like an error.
In case 2) we have two fields in class BE that contains pointers to exact same object B, differs only in type (field of class A and field2 of class B);
Is there any better solutions for this problem?

答:
You can use generics:</p>

```<code>public static class AE<T extends A> {
    protected T field;

    public AE(T field) {
        this.field = field;
    }

    public void doStuff() {
        field.doA();
    }

}

public static class BE extends AE<B> {

    // wanna have B field;

    public BE(B field) {
        super(field);
    }

    public void doAnotherStuff() {
        field.doA();
        field.doB();
    }

}
</code>```

Body:
Take a look at this code snippet:

public static class A {

    public void doA() {

    }

}

public static class B extends A {

    public void doB() {

    }

}

public static class AE {
    protected A field;

    public AE(A field) {
        this.field = field;
    }

    public void doStuff() {
        field.doA();
    }

}

public static class BE extends AE {

    // wanna have B field;

    public BE(B field) {
        super(field);
    }

    public void doAnotherStuff() {
        field.doA();
        field.doB(); // error here
    }

}

What is the best solution for such design problem?
I see two options:
1) cast to B type field everytime when you need to call doB()

((B) field).doB();

2) save B as another field fo BE class, and call this field when you need doB() functionality:

protected B field2;

    public BE(B field) {
        super(field);
        field2 = field;
    }

Both solutions are obvious and isn't nice. In case 1) you lost performance on runtime casts, and cast field everytime looks like an error.
In case 2) we have two fields in class BE that contains pointers to exact same object B, differs only in type (field of class A and field2 of class B);
Is there any better solutions for this problem?

Body:
You can use generics:

public static class AE<T extends A> {
    protected T field;

    public AE(T field) {
        this.field = field;
    }

    public void doStuff() {
        field.doA();
    }

}

public static class BE extends AE<B> {

    // wanna have B field;

    public BE(B field) {
        super(field);
    }

    public void doAnotherStuff() {
        field.doA();
        field.doB();
    }

}


问:
Getting Unknown host URL exception for Corda Doorman
I am planning to generate a certificate and register the identity of the node in Corda network. I have used this URL http://testnet.certificate.corda.net but it throws an exception if I trigger the command (java -jar corda.jar) with --initial-registration.

This is the stack trace:

```<code>Submitting certificate signing request to Corda certificate signing server.
Exception in thread "main" java.net.UnknownHostException: cordaci-netperm.corda.
r3cev.com
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
    at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
    at sun.net.NetworkClient.doConnect(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewH
ttpClient(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(Unknown Sou
rce)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Sour
ce)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect
(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(Unknown
Source)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown S
ource)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Unk
nown Source)
    at net.corda.node.utilities.registration.HTTPNetworkRegistrationService.
submitRequest(HTTPNetworkRegistrationService.kt:51)
    at net.corda.node.utilities.registration.NetworkRegistrationHelper.submi
tOrResumeCertificateSigningRequest(NetworkRegistrationHelper.kt:142)
    at net.corda.node.utilities.registration.NetworkRegistrationHelper.build
Keystore(NetworkRegistrationHelper.kt:61)
    at net.corda.node.internal.NodeStartup.maybeRegisterWithNetworkAndExit(N
odeStartup.kt:148)
    at net.corda.node.internal.NodeStartup.run(NodeStartup.kt:69)
    at net.corda.node.Corda.main(Corda.kt:11)
</code>```

答: Please try following the instructions here instead: https://docs.corda.net/permissioning.html#starting-the-registration.</p>

Body:
I am planning to generate a certificate and register the identity of the node in Corda network. I have used this URL http://testnet.certificate.corda.net but it throws an exception if I trigger the command (java -jar corda.jar) with --initial-registration.

This is the stack trace:

Submitting certificate signing request to Corda certificate signing server.
Exception in thread "main" java.net.UnknownHostException: cordaci-netperm.corda.
r3cev.com
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
    at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
    at sun.net.NetworkClient.doConnect(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewH
ttpClient(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(Unknown Sou
rce)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Sour
ce)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect
(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(Unknown
Source)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown S
ource)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Unk
nown Source)
    at net.corda.node.utilities.registration.HTTPNetworkRegistrationService.
submitRequest(HTTPNetworkRegistrationService.kt:51)
    at net.corda.node.utilities.registration.NetworkRegistrationHelper.submi
tOrResumeCertificateSigningRequest(NetworkRegistrationHelper.kt:142)
    at net.corda.node.utilities.registration.NetworkRegistrationHelper.build
Keystore(NetworkRegistrationHelper.kt:61)
    at net.corda.node.internal.NodeStartup.maybeRegisterWithNetworkAndExit(N
odeStartup.kt:148)
    at net.corda.node.internal.NodeStartup.run(NodeStartup.kt:69)
    at net.corda.node.Corda.main(Corda.kt:11)


问:
Working with decimals in Ruby on Rails 3
I'm trying to calculate the average net price of a product. I have, in my Product model :total_sold and :total_net_revenue. Doing straight division in the method seems to always result in 0. I resorted to using BigDecimal as I figured that was the problem ... but with my latest iteration of the code below, I'm still getting zero when the answer comes out to a decimal.

```<code>def avg_price
  BigDecimal(total_sold.to_s) / (BigDecimal(total_net_revenue.to_s) / 100)
end
</code>```

Net revenue is in cents, which is why I divide by 100. Can someone point out what I'm doing wrong or should do?

答:
```<code>total_net_revenue / total_sold
</code>```

or

```<code>total_net_revenue / total_sold / 100.0
</code>```

or

```<code>total_net_revenue.to_f / total_sold / 100
</code>```

These three methods give an increasing amount of precision, if you want it. Remember that "average price" is "average price / sale. That's money-per-item so you will want to do the division in that specific order.

Body:
I'm trying to calculate the average net price of a product. I have, in my Product model :total_sold and :total_net_revenue. Doing straight division in the method seems to always result in 0. I resorted to using BigDecimal as I figured that was the problem ... but with my latest iteration of the code below, I'm still getting zero when the answer comes out to a decimal.

def avg_price
  BigDecimal(total_sold.to_s) / (BigDecimal(total_net_revenue.to_s) / 100)
end

Net revenue is in cents, which is why I divide by 100. Can someone point out what I'm doing wrong or should do?

Body:
total_net_revenue / total_sold

or

total_net_revenue / total_sold / 100.0

or

total_net_revenue.to_f / total_sold / 100

These three methods give an increasing amount of precision, if you want it. Remember that "average price" is "average price / sale. That's money-per-item so you will want to do the division in that specific order.