问:
Why is my navbar and carousel not working?
This is my text for the HTML currently. I am having difficulties with the carousel and can't get it to display images properly. On top of the carousel not working, I have an issue with my nav bar background color. It won't stay at 100% width. Going back to the carousel, When I try live view and click on arrows to go to next or prev, resets it's placement behind the NavBar.

```<code><html>
    <head>
        <title>Funky Munky Arcade</title>

        <meta name="viewport" content="width=device-width, initional-scale=1">

        <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

        <!-- Optional theme -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

        <link rel="stylesheet" type="text/css" href="style.css">

    </head>

    <body>

        <nav class="navbar navbar-default navbar-fixed-top">

            <div class="container nav-container">

                    <ul class="nav nav-justified">
                        <li><a href="#">Parties</a></li>
                    </ul>

                <div class="navbar-header">

                    <a href="/index.html" class="navbar-left"><img src="http://i.imgur.com/UXms4Eq.png" class="logo"></a>

                </div>

                    <ul class="nav nav-justified">
                        <li><a href="#">Contact</a></li>
                    </ul>

            </div>

        </nav>

        <!-- Beginning of Carousel -->

        <div class="carousel slide" id="bannerslides" data-ride="carousel">

            <!-- Indicators -->

            <ol class="carousel-indicators">

                <li data-target="#bannerslides" data-slide-to="0" class="active">
                </li>

                <li data-target="#bannerslides" data-slide-to="1">
                </li>

                <li data-target="#bannerslides" data-slide-to="2">
                </li>

                <li data-target="#bannerslides" data-slide-to="3">
                </li>

            </ol>

            <!-- End of Indicators -->

            <!-- Wrapper for Slides -->

            <div class="carousel-inner">

                <div class="item active">

                    <img src="https://db.tt/W08hePZ53h">

                </div>

                <div class="item">

                    <img src="http://i.imgur.com/t0Y4JDI.png">

                </div>

                <div class="item">

                    <img src="http://i.imgur.com/zaUETSd.png">

                </div>

                <div class="item">

                    <img src="http://i.imgur.com/LRATkRS.png">

                </div>

            </div>

            <!-- End of Wrapper -->

            <!-- Beginning of Carousel Controls -->

            <a class="left carousel-control" href="#bannerslides" data-slide="prev">
                <span class="glyphicon glyphicon-chevron-left"></span>
            </a>

            <a class="right carousel-control" href="#bannerslides" data-slide="next">
                <span class="glyphicon glyphicon-chevron-right"></span>
            </a>

            <!-- End of Carousel Controls -->

        </div>

        <!-- End of Carousel -->
</code>```

Here is my CSS:

```<code>.nav-container {
display: flex;
align-items: center;
background-color: red;
width: 100%;
}
.head {
text-align: center;
}
.intro{
font-size: 48px;
text-align: center;
}
.jumbotron{
background-color: white;
font-size: 24px;
}
.navbar-fixed-top{
background-color: red;
border: 0px;
}
.logo{
background-color: white;
border-radius: 50%;
}
.carousel{
margin-top: 150px;
}
</code>```

答:
You need the CDN for jQuery.

That can be found at the jQuery website: https://code.jquery.com/

So this:

```<code><script
    src="https://code.jquery.com/jquery-3.2.1.js"
    integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
    crossorigin="anonymous"></script>
</code>```

would go in to the head of your page

Body:
This is my text for the HTML currently. I am having difficulties with the carousel and can't get it to display images properly. On top of the carousel not working, I have an issue with my nav bar background color. It won't stay at 100% width. Going back to the carousel, When I try live view and click on arrows to go to next or prev, resets it's placement behind the NavBar.

        <title>Funky Munky Arcade</title>

        <meta name="viewport" content="width=device-width, initional-scale=1">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

        <link rel="stylesheet" type="text/css" href="style.css">

Parties

Contact

Here is my CSS:

.nav-container {
display: flex;
align-items: center;
background-color: red;
width: 100%;
}
.head {
text-align: center;
}
.intro{
font-size: 48px;
text-align: center;
}
.jumbotron{
background-color: white;
font-size: 24px;
}
.navbar-fixed-top{
background-color: red;
border: 0px;
}
.logo{
background-color: white;
border-radius: 50%;
}
.carousel{
margin-top: 150px;
}

Body:
You need the CDN for jQuery.

That can be found at the jQuery website: https://code.jquery.com/

So this:

<script
    src="https://code.jquery.com/jquery-3.2.1.js"
    integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
    crossorigin="anonymous"></script>

would go in to the head of your page


来源: stackexchange

问:
Dynamically assign Database Document Properties
I'm getting this error:

```<code>ERROR: Cast to number failed for value "undefined" at path "floatingPeriodLength"
</code>```

When I POST to addPricingRule I don't pass all the parameters depending on which rule I'm adding.  I'm getting the error when I don't pass the floatingPeriodLength property.  In other words, when floatingPeriodLength is undefined.  Is there any way to add a new pricing rule without setting some of the properties?  I haven't set them as required in the schema...

```<code>app.post('/addPricingRule', async function(req, res){
    console.log("/addPricingRule");
    if(!req.user) {
        handleError(res, "User not logged in", "User not logged in", 403);
    } else {
        var newRule = {};
        var aListingID = req.body.aListingID;
        var _id = req.body._id;
        var title = req.body.title;
        var event = req.body.event;
        var amount = req.body.amount;
        var scale = req.body.scale;
        var floatingPeriodStartDay = req.body.floatingPeriodStartDay;
        var floatingPeriodLength = req.body.floatingPeriodLength;
        var orphanPeriodLength = req.body.orphanPeriodLength;
        var specificDatesStartDate = req.body.specificDatesStartDate;
        var specificDatesEndDate = req.body.specificDatesEndDate;
        try {
            var accounts = await Account.find({userID: req.user._id});
            var accountIDs = [];
            accounts.forEach(function(account) {
                accountIDs.push(account._id);
            });
            var listing = await Listing.findOne({
                accountID: {$in: accountIDs},
                aListingID,
            });
            if(_id) {
                await PriceRule.findByIdAndUpdate(_id,
                    {
                        title,
                        event,
                        amount,
                        scale,
                        floatingPeriodStartDay,
                        floatingPeriodLength,
                        orphanPeriodLength,
                        specificDatesStartDate,
                        specificDatesEndDate,
                    }
                );
            } else {
                await PriceRule.create({
                    listingID: listing._id,
                    title,
                    event,
                    amount,
                    scale,
                    floatingPeriodStartDay,
                    floatingPeriodLength,
                    orphanPeriodLength,
                    specificDatesStartDate,
                    specificDatesEndDate,
                });
            }
        } catch(error) {
            handleError(res, error.message, "/addPricingRule", 400);
        }
        res.status(200).json("success");
    }
});
</code>```

Here's the schema:

```<code>var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var MessageRule = new Schema({
    listingID: {type: mongoose.Schema.Types.ObjectId, ref: 'listing'},
    message: String,
    title: String,
    event: String,
    days: Number,
    time: Number,
    minNights: {type: Number, default: 1},
    lastMinuteMessage: {type: String, default: ""},
    lastMinuteMessageEnabled: {type: Boolean, default: false},
    reviewEnabled: {type: Boolean, default: false},
    reviewMessage: String,
    sendMessageAfterLeavingReview: Boolean,
});

module.exports = mongoose.model('MessageRule', MessageRule);
</code>```

答:
Why not do something like take a copy with Object.assign:

```<code>var aListingID = req.body.aListingID;
var _id = req.body._id;
var fields = Object.assign({}, req.body);  // take a copy rather than assign separately
delete fields._id;                         // discard these properties from the copy
delete fields.aListingID;
</code>```

And then use fields later like

```<code> await PriceRule.findByIdAndUpdate(_id, fields);
</code>```

And when you have additional information, assign another merged copy

```<code> await PriceRule.create(Object.assign({ listingID: listing._id }, fields))
</code>```

In that way if the properties are not there then you simply are not creating a variable for them

ContentLicense: CC BY-SA 3.0

Body:
I'm getting this error:

ERROR: Cast to number failed for value "undefined" at path "floatingPeriodLength"

When I POST to addPricingRule I don't pass all the parameters depending on which rule I'm adding.  I'm getting the error when I don't pass the floatingPeriodLength property.  In other words, when floatingPeriodLength is undefined.  Is there any way to add a new pricing rule without setting some of the properties?  I haven't set them as required in the schema...

app.post('/addPricingRule', async function(req, res){
    console.log("/addPricingRule");
    if(!req.user) {
        handleError(res, "User not logged in", "User not logged in", 403);
    } else {
        var newRule = {};
        var aListingID = req.body.aListingID;
        var _id = req.body._id;
        var title = req.body.title;
        var event = req.body.event;
        var amount = req.body.amount;
        var scale = req.body.scale;
        var floatingPeriodStartDay = req.body.floatingPeriodStartDay;
        var floatingPeriodLength = req.body.floatingPeriodLength;
        var orphanPeriodLength = req.body.orphanPeriodLength;
        var specificDatesStartDate = req.body.specificDatesStartDate;
        var specificDatesEndDate = req.body.specificDatesEndDate;
        try {
            var accounts = await Account.find({userID: req.user._id});
            var accountIDs = [];
            accounts.forEach(function(account) {
                accountIDs.push(account._id);
            });
            var listing = await Listing.findOne({
                accountID: {$in: accountIDs},
                aListingID,
            });
            if(_id) {
                await PriceRule.findByIdAndUpdate(_id,
                    {
                        title,
                        event,
                        amount,
                        scale,
                        floatingPeriodStartDay,
                        floatingPeriodLength,
                        orphanPeriodLength,
                        specificDatesStartDate,
                        specificDatesEndDate,
                    }
                );
            } else {
                await PriceRule.create({
                    listingID: listing._id,
                    title,
                    event,
                    amount,
                    scale,
                    floatingPeriodStartDay,
                    floatingPeriodLength,
                    orphanPeriodLength,
                    specificDatesStartDate,
                    specificDatesEndDate,
                });
            }
        } catch(error) {
            handleError(res, error.message, "/addPricingRule", 400);
        }
        res.status(200).json("success");
    }
});

Here's the schema:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var MessageRule = new Schema({
    listingID: {type: mongoose.Schema.Types.ObjectId, ref: 'listing'},
    message: String,
    title: String,
    event: String,
    days: Number,
    time: Number,
    minNights: {type: Number, default: 1},
    lastMinuteMessage: {type: String, default: ""},
    lastMinuteMessageEnabled: {type: Boolean, default: false},
    reviewEnabled: {type: Boolean, default: false},
    reviewMessage: String,
    sendMessageAfterLeavingReview: Boolean,
});

module.exports = mongoose.model('MessageRule', MessageRule);

Body:
Why not do something like take a copy with Object.assign:

var aListingID = req.body.aListingID;
var _id = req.body._id;
var fields = Object.assign({}, req.body);  // take a copy rather than assign separately
delete fields._id;                         // discard these properties from the copy
delete fields.aListingID;

And then use fields later like

 await PriceRule.findByIdAndUpdate(_id, fields);

And when you have additional information, assign another merged copy

 await PriceRule.create(Object.assign({ listingID: listing._id }, fields))

In that way if the properties are not there then you simply are not creating a variable for them


问:
How to cache page in MVC Core, only in Production environment
Is there an easy way to cache an MVC Core page (View) only when in Production environment?  I tried the code below, but the  tag helper doesn't work since the  ending tag must be within the  tag.

```<code><environment names="Staging,Production">
    <cache expires-after="@TimeSpan.FromMinutes(30)">
</environment>
</code>```

Possibly use the enabled attribute for ?

Thanks.

UPDATE:

If you want to cache the entire page, to avoid having a  section as well as one without it (since you still want that content in a Development environment), I would suppose you could put the entire page into a partial view as noted by some.  That would work.  and you would end up with:

```<code><environment names="Staging,Production">
    <cache expires-after="@TimeSpan.FromMinutes(30)">
        @Html.Partial("_PartialViewName")
        *last updated  @DateTime.Now.ToLongTimeString()
    </cache>
</environment>
<environment names="Development">
    @Html.Partial("_PartialViewName")
</environment>
</code>```

Seem correct?

答:
Simply wrap the contents you want cached with a  tag and the contents of the tag will be cached in memory.</p>

```<code><environment names="Staging,Production">
    <cache expires-after="@TimeSpan.FromMinutes(30)">
        @Html.Partial("_PartialViewName")
        *last updated  @DateTime.Now.ToLongTimeString()
    </cache>
</environment>
</code>```

Body:
Is there an easy way to cache an MVC Core page (View) only when in Production environment?  I tried the code below, but the  tag helper doesn't work since the  ending tag must be within the  tag.

<environment names="Staging,Production">
    <cache expires-after="@TimeSpan.FromMinutes(30)">
</environment>

Possibly use the enabled attribute for ?

Thanks.

UPDATE:

If you want to cache the entire page, to avoid having a  section as well as one without it (since you still want that content in a Development environment), I would suppose you could put the entire page into a partial view as noted by some.  That would work.  and you would end up with:

<environment names="Staging,Production">
    <cache expires-after="@TimeSpan.FromMinutes(30)">
        @Html.Partial("_PartialViewName")
        *last updated  @DateTime.Now.ToLongTimeString()
    </cache>
</environment>
<environment names="Development">
    @Html.Partial("_PartialViewName")
</environment>

Seem correct?

Body:
Simply wrap the contents you want cached with a  tag and the contents of the tag will be cached in memory.

<environment names="Staging,Production">
    <cache expires-after="@TimeSpan.FromMinutes(30)">
        @Html.Partial("_PartialViewName")
        *last updated  @DateTime.Now.ToLongTimeString()
    </cache>
</environment>


问:
Android button open link in background?
I am looking to build a button in my android app that when the user clicks on the button, it'll load a URL in the background without the user seeing the page it loaded.
(the url sets off something in my api, if someone loads the url it triggers my api to do x thing, thats why I need it.)

I looked around and could not find anything useful already.
Thanks for any help.

答: You can load the the page using volley library from service.</p>

Title: Android button open link in background?


问:
How to make an image appear when I hover over a button (No inheritance)
```<code><div class="a">
 <img class="img_c" id="img_id" src="~~">
 <div class="b">
  <div class="c">
   <ul class="d" id="e">
    <li ~~~ >
   </ul>
  </div>
 </div>
</div>
</code>```

I want to display the image by hovering the cursor over the e button.
The b class has a max-width attribute, but the image is not bounded by the width, so it must be outside the class b.
How do I write CSS code in this case?

答:
If you can use jQuery you can use something like this to show/hide the image.

$("#e li").hover(
  function () {
    $("#img_id").show();
  },
  function () {
    $("#img_id").hide();
  }
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#img_id {
   display: none;
}</code>```

item 1

item 2

item 3

item 4

```

Body:
If you can use jQuery you can use something like this to show/hide the image.

$("#e li").hover(
  function () {
    $("#img_id").show();
  },
  function () {
    $("#img_id").hide();
  }
);

#img_id {
   display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a">
 <img class="img_c" id="img_id" src="~~">
 <div class="b">
  <div class="c">
   <ul class="d" id="e">
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
    <li>item 4</li>
   </ul>
  </div>
 </div>
</div>


问:
Count Stored Procedures in Database?
How can i count the number of stored procedures in my database and is it a bad practice to have too many stored procedures?</p>

答:
```<code>Select count(1) from information_schema.routines
where routine_type = 'PROCEDURE'
</code>```

OwnerDisplayName: Jack

Title: Count Stored Procedures in Database?

LastEditorDisplayName: Cade Roux

OwnerDisplayName: cmsjr

ContentLicense: CC BY-SA 2.5


问:
Are MachineBasicBlocks supposed to implicitly fall through to their successors?
I'm debugging an LLVM target backend, and I am chasing a problem where a certain basic block ends up jumping to "nothing", i.e. just after the end of the function, when compiled with optimizations turned on.

One thing I noticed is that after instruction selection, the machine basic block has a successor but no instruction to actually jump there:

```<code>BB#1: derived from LLVM BB %switch.lookup
    Predecessors according to CFG: BB#0
        %vreg5<def> = SEXT %vreg2, %SREG<imp-def,dead>; DLDREGS:%vreg5 GPR8:%vreg2
        %vreg6<def,tied1> = ANDIWRdK %vreg5<tied0>, -2, %SREG<imp-def,dead>; DLDREGS:%vreg6,%vreg5
        %vreg7<def> = LDIWRdK 4; DLDREGS:%vreg7
        %vreg8<def> = LDIRdK 0; LD8:%vreg8
        %vreg9<def> = LDIRdK 1; LD8:%vreg9
        CPWRdRr %vreg6<kill>, %vreg7<kill>, %SREG<imp-def>; DLDREGS:%vreg6,%vreg7
        %vreg0<def> = Select8 %vreg9<kill>, %vreg8<kill>, 1, %SREG<imp-use>; GPR8:%vreg0 LD8:%vreg9,%vreg8
    Successors according to CFG: BB#2(?%)
</code>```

I see similar ISel results from the x86 LLVM backend and the end result doesn't have a jump-to-nothingness, so I assume this, on its own, is not a problem:

```<code>BB#1: derived from LLVM BB %switch.lookup
    Predecessors according to CFG: BB#0
        %vreg7<def> = MOVSX32rr8 %vreg3; GR32:%vreg7 GR8:%vreg3
        %vreg8<def,tied1> = AND32ri %vreg7<tied0>, 65534, %EFLAGS<imp-def,dead>; GR32:%vreg8,%vreg7
        %vreg9<def,tied1> = SUB32ri8 %vreg8<tied0>, 4, %EFLAGS<imp-def>; GR32:%vreg9,%vreg8
        %vreg0<def> = SETNEr %EFLAGS<imp-use>; GR8:%vreg0
    Successors according to CFG: BB#2(?%)
</code>```

So my question is: What is the mechanism by which these CFG-specified successors are supposed to be turned into real jumps? Does the x86 backend implement something special for this to work that the backend I'm debuggig doesn't?

Should I change my ISelLowering class to lower Select8 into something that ends with an explicit jump, or is that unnecessary (maybe potentially even detrimental for some optimization to kick in) and there's some other magic that I need to do so that these implicit successors are correctly lowered?

答:
It is perfectly valid for a MachineBasicBlock to fall through to the next Block:

That is valid. Passes that want to reorder basic blocks should only do
  so if the AnalyzeBranch and related target hooks (Insert/Remove) allow
  it.

Body:
I'm debugging an LLVM target backend, and I am chasing a problem where a certain basic block ends up jumping to "nothing", i.e. just after the end of the function, when compiled with optimizations turned on.

One thing I noticed is that after instruction selection, the machine basic block has a successor but no instruction to actually jump there:

BB#1: derived from LLVM BB %switch.lookup
    Predecessors according to CFG: BB#0
        %vreg5<def> = SEXT %vreg2, %SREG<imp-def,dead>; DLDREGS:%vreg5 GPR8:%vreg2
        %vreg6<def,tied1> = ANDIWRdK %vreg5<tied0>, -2, %SREG<imp-def,dead>; DLDREGS:%vreg6,%vreg5
        %vreg7<def> = LDIWRdK 4; DLDREGS:%vreg7
        %vreg8<def> = LDIRdK 0; LD8:%vreg8
        %vreg9<def> = LDIRdK 1; LD8:%vreg9
        CPWRdRr %vreg6<kill>, %vreg7<kill>, %SREG<imp-def>; DLDREGS:%vreg6,%vreg7
        %vreg0<def> = Select8 %vreg9<kill>, %vreg8<kill>, 1, %SREG<imp-use>; GPR8:%vreg0 LD8:%vreg9,%vreg8
    Successors according to CFG: BB#2(?%)

I see similar ISel results from the x86 LLVM backend and the end result doesn't have a jump-to-nothingness, so I assume this, on its own, is not a problem:

BB#1: derived from LLVM BB %switch.lookup
    Predecessors according to CFG: BB#0
        %vreg7<def> = MOVSX32rr8 %vreg3; GR32:%vreg7 GR8:%vreg3
        %vreg8<def,tied1> = AND32ri %vreg7<tied0>, 65534, %EFLAGS<imp-def,dead>; GR32:%vreg8,%vreg7
        %vreg9<def,tied1> = SUB32ri8 %vreg8<tied0>, 4, %EFLAGS<imp-def>; GR32:%vreg9,%vreg8
        %vreg0<def> = SETNEr %EFLAGS<imp-use>; GR8:%vreg0
    Successors according to CFG: BB#2(?%)

So my question is: What is the mechanism by which these CFG-specified successors are supposed to be turned into real jumps? Does the x86 backend implement something special for this to work that the backend I'm debuggig doesn't?

Should I change my ISelLowering class to lower Select8 into something that ends with an explicit jump, or is that unnecessary (maybe potentially even detrimental for some optimization to kick in) and there's some other magic that I need to do so that these implicit successors are correctly lowered?


问:
What is the rationale for all comparisons returning false for IEEE754 NaN values?
Why do comparisons of NaN values behave differently from all other values?
That is, all comparisons with the operators ==, <=, >=, <, > where one or both values is NaN returns false, contrary to the behaviour of all other values.

I suppose this simplifies numerical computations in some way, but I couldn't find an explicitly stated reason, not even in the Lecture Notes on the Status of IEEE 754 by Kahan which discusses other design decisions in detail.

This deviant behavior is causing trouble when doing simple data processing. For example, when sorting a list of records w.r.t. some real-valued field in a C program I need to write extra code to handle NaN as the maximal element, otherwise the sort algorithm could become confused.

Edit:
The answers so far all argue that it is meaningless to compare NaNs.

I agree, but that doesn't mean that the correct answer is false,
rather it would be a Not-a-Boolean (NaB), which fortunately doesn't exist.

So the choice of returning true or false for comparisons is in my view arbitrary,
and for general data processing it would be advantageous if it obeyed the usual laws
(reflexivity of ==, trichotomy of <, ==, >),
lest data structures which rely on these laws become confused.

So I'm asking for some concrete advantage of breaking these laws, not just philosophical reasoning.

Edit 2:
I think I understand now why making NaN maximal would be a bad idea, it would mess up the computation of upper limits.

NaN != NaN might be desirable to avoid detecting convergence in a loop such as

```<code>while (x != oldX) {
    oldX = x;
    x = better_approximation(x);
}
</code>```

which however should better be written by comparing the absolute difference with a small limit.
So IMHO this is a relatively weak argument for breaking reflexivity at NaN.

答:
Because mathematics is the field where numbers "just exist".
In computing you must initialize those numbers and keep their state according to your needs.
At those old days memory initialization worked in the ways you could never rely on. You never could allow yourself to think about this "oh, that would be initialized with 0xCD all the time, my algo will not broke".

So you need proper non-mixing solvent which is sticky enough to not not letting your algorithm getting sucked into and broken.
Good algorithms involving numbers are mostly going to work with relations, and those if() relations will be omitted.

This is just grease which you can put into new variable at creation, instead of programming random hell from computer memory. And your algorithm whatever it is, will not break.

Next, when you still suddenly finding out that your algorithm is producing NaNs, it is possible to clean it out, looking into every branch one at a time. Again, "always false" rule is helping a lot in this.

Body:
Why do comparisons of NaN values behave differently from all other values?
That is, all comparisons with the operators ==, <=, >=, <, > where one or both values is NaN returns false, contrary to the behaviour of all other values.

I suppose this simplifies numerical computations in some way, but I couldn't find an explicitly stated reason, not even in the Lecture Notes on the Status of IEEE 754 by Kahan which discusses other design decisions in detail.

This deviant behavior is causing trouble when doing simple data processing. For example, when sorting a list of records w.r.t. some real-valued field in a C program I need to write extra code to handle NaN as the maximal element, otherwise the sort algorithm could become confused.

Edit:
The answers so far all argue that it is meaningless to compare NaNs.

I agree, but that doesn't mean that the correct answer is false,
rather it would be a Not-a-Boolean (NaB), which fortunately doesn't exist.

So the choice of returning true or false for comparisons is in my view arbitrary,
and for general data processing it would be advantageous if it obeyed the usual laws
(reflexivity of ==, trichotomy of <, ==, >),
lest data structures which rely on these laws become confused.

So I'm asking for some concrete advantage of breaking these laws, not just philosophical reasoning.

Edit 2:
I think I understand now why making NaN maximal would be a bad idea, it would mess up the computation of upper limits.

NaN != NaN might be desirable to avoid detecting convergence in a loop such as

while (x != oldX) {
    oldX = x;
    x = better_approximation(x);
}

which however should better be written by comparing the absolute difference with a small limit.
So IMHO this is a relatively weak argument for breaking reflexivity at NaN.


问:
Sum variables using R by categories condition
I have a data frame that shows the number of publications by year. But I am interested just in Conference and Journals Publications. I would like to sum all other categories in Others type.

Examples of data frame:

```<code>year    type                n
1994    Conference          2
1994    Journal             3
1995    Conference         10
1995    Editorship          3
1996    Conference         20
1996    Editorship          2
1996    Books and Thesis    3
</code>```

And the result would be:

```<code>year type             n
1994    Conference    2
1994    Journal       3
1995    Conference   10
1995    Other         3
1996    Conference   20
1996    Other         5
</code>```

答:
We can use data.table

```<code>library(data.table)
library(stringr)
setDT(df1)[, .(n = sum(n)), .(year, type = str_replace(type,
       '(Journal|Conference)', 'Other'))]
#   year             type  n
#1: 1994            Other  5
#2: 1995            Other 10
#3: 1995       Editorship  3
#4: 1996            Other 20
#5: 1996       Editorship  2
#6: 1996 Books and Thesis  3
</code>```

Body:
I have a data frame that shows the number of publications by year. But I am interested just in Conference and Journals Publications. I would like to sum all other categories in Others type.

Examples of data frame:

year    type                n
1994    Conference          2
1994    Journal             3
1995    Conference         10
1995    Editorship          3
1996    Conference         20
1996    Editorship          2
1996    Books and Thesis    3

And the result would be:

year type             n
1994    Conference    2
1994    Journal       3
1995    Conference   10
1995    Other         3
1996    Conference   20
1996    Other         5

Body:
We can use data.table

library(data.table)
library(stringr)
setDT(df1)[, .(n = sum(n)), .(year, type = str_replace(type,
       '(Journal|Conference)', 'Other'))]
#   year             type  n
#1: 1994            Other  5
#2: 1995            Other 10
#3: 1995       Editorship  3
#4: 1996            Other 20
#5: 1996       Editorship  2
#6: 1996 Books and Thesis  3


问:
Auto-fill matrix without row-repetitions
I have a series of numbers:

```<code>test = [1 1 1 2 2 2 3 3 3 4 4 4 5 5 5]
</code>```

which I want to randomely fill into a 3x5 matrix without having the same number in the same row.

How can I do this in matlab? Potentially I could randomize the test vector and fill it into the 5x3 matrix but I don't know how to do this without getting the same number in the same row.

答:
You can take the unique matrix of test and pick any three elements out of it and fill in the required 5X3 matrix.

```<code>test = [1 1 1 2 2 2 3 3 3 4 4 4 5 5 5] ;
test_unique = unique(test) ;
A = zeros(5,3) ;
for i = 1:size(A,1)
    A(i,:) = randsample(test_unique,3) ;
end
</code>```

randsample needs a statistics toolbox, if you doesn't have it, you may use randperm as shown below.

```<code>test = [1 1 1 2 2 2 3 3 3 4 4 4 5 5 5] ;
test_unique = unique(test) ;

A = zeros(5,3) ;
for i = 1:size(A,1)
    A(i,:) = test_unique(randperm(length(test_unique),3)) ;
end
</code>```

If you want 3X5 matrix:

```<code>test = [1 1 1 2 2 2 3 3 3 4 4 4 5 5 5] ;
test_unique = unique(test) ;
A = zeros(3,5) ;
for i = 1:size(A,1)
    A(i,:) = randsample(test_unique,5) ;
end
</code>```

Body:
I have a series of numbers:

test = [1 1 1 2 2 2 3 3 3 4 4 4 5 5 5]

which I want to randomely fill into a 3x5 matrix without having the same number in the same row.

How can I do this in matlab? Potentially I could randomize the test vector and fill it into the 5x3 matrix but I don't know how to do this without getting the same number in the same row.

Body:
You can take the unique matrix of test and pick any three elements out of it and fill in the required 5X3 matrix.

test = [1 1 1 2 2 2 3 3 3 4 4 4 5 5 5] ;
test_unique = unique(test) ;
A = zeros(5,3) ;
for i = 1:size(A,1)
    A(i,:) = randsample(test_unique,3) ;
end

randsample needs a statistics toolbox, if you doesn't have it, you may use randperm as shown below.

test = [1 1 1 2 2 2 3 3 3 4 4 4 5 5 5] ;
test_unique = unique(test) ;

A = zeros(5,3) ;
for i = 1:size(A,1)
    A(i,:) = test_unique(randperm(length(test_unique),3)) ;
end

If you want 3X5 matrix:

test = [1 1 1 2 2 2 3 3 3 4 4 4 5 5 5] ;
test_unique = unique(test) ;
A = zeros(3,5) ;
for i = 1:size(A,1)
    A(i,:) = randsample(test_unique,5) ;
end


问:
How can I use variable names other than $it$ in a StringTemplate partial?
How can I use variable names other than $it$ in a StringTemplate partial?</p>

答:
What's a partial?

anyway, if template has one arg the ST sets its value too

$a:t()$

for def

t(v) ::= "$v$"

is same as

t() ::= "$it$"


问:
Class 'Mage_Googlecheckout_Helper_Data' not found
We've just upgraded from Magento version 1.8.0.0 to 1.8.1.0 and now when we go to the configuration section of our site we receive the message:

```<code>Fatal error: Class 'Mage_Googlecheckout_Helper_Data' not found in /home/dir/public_html/guides/setup/app/Mage.php on line 547
</code>```

Any ideas on what might be causing this

答:
If you will delete files then google checkout will not work.

I found this answer useful.

```<code><helpers>
        <googlecheckout>
            <class>Mage_GoogleCheckout_Helper</class>
        </googlecheckout>
    </helpers>
</code>```

Body:
We've just upgraded from Magento version 1.8.0.0 to 1.8.1.0 and now when we go to the configuration section of our site we receive the message:

Fatal error: Class 'Mage_Googlecheckout_Helper_Data' not found in /home/dir/public_html/guides/setup/app/Mage.php on line 547

Any ideas on what might be causing this

Body:
If you will delete files then google checkout will not work.

I found this answer useful.

<helpers>
        <googlecheckout>
            <class>Mage_GoogleCheckout_Helper</class>
        </googlecheckout>
    </helpers>


问:
jruby rails undefined method `empty?' for nil:NilClass
I am trying to run filterrific in jruby rails environment. Initially, there was no errors and was able to run it succesffully. Few days after that I was working on different controller adding some other gems related with charts. When I came to student controller, now it is giving me this error, I have triple verified all the code and also did beyond compare with your demo app and mine. There was no changes in views, controller, model, js, db and config files, but suddenly I am getting this error "undefined method `empty?' for nil:NilClass" in the following line

```<code>.form-group.chardin_box{ :'data-position' => 'top', :'data-intro' => 'Filter by country.' }
  %label Category
  = f.select :with_country_id,
             @filterrific.select_options[:with_country_id],
             { :include_blank => '- Any -' },
             { :class => 'form-control' }
</code>```

Application Trace:

```<code>app/views/students/index.html.haml:22:in block in _app_views_students_index_html_haml___1163931893_2080' app/views/students/index.html.haml:12:in_app_views_students_index_html_haml___1163931893_2080'
</code>```

Full Trace:

```<code>actionview (5.1.1) lib/action_view/helpers/tags/select.rb:36:in grouped_choices?' actionview (5.1.1) lib/action_view/helpers/tags/select.rb:20:inrender'
actionview (5.1.1) lib/action_view/helpers/form_options_helper.rb:163:in select' actionview (5.1.1) lib/action_view/helpers/form_options_helper.rb:817:inselect'
app/views/students/index.html.haml:22:in block in _app_views_students_index_html_haml___1163931893_2080' haml (5.0.1) lib/haml/helpers.rb:382:inblock in capture_haml'
haml (5.0.1) lib/haml/helpers.rb:667:in with_haml_buffer' haml (5.0.1) lib/haml/helpers.rb:378:incapture_haml'
haml (5.0.1) lib/haml/helpers/xss_mods.rb:62:in capture_haml_with_haml_xss' haml (5.0.1) lib/haml/helpers/action_view_mods.rb:45:incapture_with_haml'
actionview (5.1.1) lib/action_view/helpers/form_helper.rb:450:in form_for' haml (5.0.1) lib/haml/helpers/action_view_xss_mods.rb:29:inform_for_with_haml_xss'
filterrific (2.1.2) lib/filterrific/action_view_extension.rb:23:in form_for_filterrific' app/views/students/index.html.haml:12:in_app_views_students_index_html_haml___1163931893_2080'
actionview (5.1.1) lib/action_view/template.rb:157:in block in render' activesupport (5.1.1) lib/active_support/notifications.rb:168:ininstrument'
actionview (5.1.1) lib/action_view/template.rb:352:in instrument_render_template' actionview (5.1.1) lib/action_view/template.rb:155:inrender'
actionview (5.1.1) lib/action_view/renderer/template_renderer.rb:52:in block in render_template' actionview (5.1.1) lib/action_view/renderer/abstract_renderer.rb:42:inblock in instrument'
activesupport (5.1.1) lib/active_support/notifications.rb:166:in block in instrument' activesupport (5.1.1) lib/active_support/notifications/instrumenter.rb:21:ininstrument'
activesupport (5.1.1) lib/active_support/notifications.rb:166:in instrument' actionview (5.1.1) lib/action_view/renderer/abstract_renderer.rb:41:ininstrument'
actionview (5.1.1) lib/action_view/renderer/template_renderer.rb:51:in block in render_template' actionview (5.1.1) lib/action_view/renderer/template_renderer.rb:59:inrender_with_layout'
actionview (5.1.1) lib/action_view/renderer/template_renderer.rb:50:in render_template' actionview (5.1.1) lib/action_view/renderer/template_renderer.rb:14:inrender'
actionview (5.1.1) lib/action_view/renderer/renderer.rb:42:in render_template' actionview (5.1.1) lib/action_view/renderer/renderer.rb:23:inrender'
actionview (5.1.1) lib/action_view/rendering.rb:103:in _render_template' actionpack (5.1.1) lib/action_controller/metal/streaming.rb:217:in_render_template'
actionview (5.1.1) lib/action_view/rendering.rb:83:in render_to_body' actionpack (5.1.1) lib/action_controller/metal/rendering.rb:52:inrender_to_body'
actionpack (5.1.1) lib/action_controller/metal/renderers.rb:141:in render_to_body' actionpack (5.1.1) lib/abstract_controller/rendering.rb:24:inrender'
actionpack (5.1.1) lib/action_controller/metal/rendering.rb:36:in render' actionpack (5.1.1) lib/action_controller/metal/instrumentation.rb:44:inblock in render'
activesupport (5.1.1) lib/active_support/core_ext/benchmark.rb:12:in block in ms' /home/balaji/Documents/balaji/unl/PhD/railswebapp/jruby-9.1.10.0/lib/ruby/stdlib/benchmark.rb:308:inrealtime'
activesupport (5.1.1) lib/active_support/core_ext/benchmark.rb:12:in ms' actionpack (5.1.1) lib/action_controller/metal/instrumentation.rb:44:inblock in render'
actionpack (5.1.1) lib/action_controller/metal/instrumentation.rb:87:in cleanup_view_runtime' activerecord (5.1.1) lib/active_record/railties/controller_runtime.rb:29:incleanup_view_runtime'
actionpack (5.1.1) lib/action_controller/metal/instrumentation.rb:43:in render' actionpack (5.1.1) lib/action_controller/metal/implicit_render.rb:33:indefault_render'
actionpack (5.1.1) lib/action_controller/metal/basic_implicit_render.rb:4:in block in send_action' org/jruby/RubyKernel.java:1747:intap'
actionpack (5.1.1) lib/action_controller/metal/basic_implicit_render.rb:4:in send_action' actionpack (5.1.1) lib/abstract_controller/base.rb:186:inprocess_action'
actionpack (5.1.1) lib/action_controller/metal/rendering.rb:30:in process_action' actionpack (5.1.1) lib/abstract_controller/callbacks.rb:20:inblock in process_action'
activesupport (5.1.1) lib/active_support/callbacks.rb:131:in run_callbacks' actionpack (5.1.1) lib/abstract_controller/callbacks.rb:19:inprocess_action'
actionpack (5.1.1) lib/action_controller/metal/rescue.rb:20:in process_action' actionpack (5.1.1) lib/action_controller/metal/instrumentation.rb:32:inblock in process_action'
activesupport (5.1.1) lib/active_support/notifications.rb:166:in block in instrument' activesupport (5.1.1) lib/active_support/notifications/instrumenter.rb:21:ininstrument'
activesupport (5.1.1) lib/active_support/notifications.rb:166:in instrument' actionpack (5.1.1) lib/action_controller/metal/instrumentation.rb:30:inprocess_action'
actionpack (5.1.1) lib/action_controller/metal/params_wrapper.rb:252:in process_action' activerecord (5.1.1) lib/active_record/railties/controller_runtime.rb:22:inprocess_action'
actionpack (5.1.1) lib/abstract_controller/base.rb:124:in process' actionview (5.1.1) lib/action_view/rendering.rb:30:inprocess'
actionpack (5.1.1) lib/action_controller/metal.rb:189:in dispatch' actionpack (5.1.1) lib/action_controller/metal.rb:253:indispatch'
actionpack (5.1.1) lib/action_dispatch/routing/route_set.rb:49:in dispatch' actionpack (5.1.1) lib/action_dispatch/routing/route_set.rb:31:inserve'
actionpack (5.1.1) lib/action_dispatch/journey/router.rb:46:in block in serve' org/jruby/RubyArray.java:1734:ineach'
actionpack (5.1.1) lib/action_dispatch/journey/router.rb:33:in serve' actionpack (5.1.1) lib/action_dispatch/routing/route_set.rb:832:incall'
rack (2.0.3) lib/rack/etag.rb:25:in call' rack (2.0.3) lib/rack/conditional_get.rb:25:incall'
rack (2.0.3) lib/rack/head.rb:12:in call' torquebox-web-3.2.0 (java) lib/torquebox/session/servlet_store.rb:47:incall'
actionpack (5.1.1) lib/action_dispatch/middleware/cookies.rb:613:in call' activerecord (5.1.1) lib/active_record/migration.rb:556:incall'
actionpack (5.1.1) lib/action_dispatch/middleware/callbacks.rb:26:in block in call' activesupport (5.1.1) lib/active_support/callbacks.rb:97:inrun_callbacks'
actionpack (5.1.1) lib/action_dispatch/middleware/callbacks.rb:24:in call' actionpack (5.1.1) lib/action_dispatch/middleware/executor.rb:12:incall'
actionpack (5.1.1) lib/action_dispatch/middleware/debug_exceptions.rb:59:in call' actionpack (5.1.1) lib/action_dispatch/middleware/show_exceptions.rb:31:incall'
railties (5.1.1) lib/rails/rack/logger.rb:36:in call_app' railties (5.1.1) lib/rails/rack/logger.rb:24:inblock in call'
activesupport (5.1.1) lib/active_support/tagged_logging.rb:69:in block in tagged' activesupport (5.1.1) lib/active_support/tagged_logging.rb:26:intagged'
activesupport (5.1.1) lib/active_support/tagged_logging.rb:69:in tagged' railties (5.1.1) lib/rails/rack/logger.rb:24:incall'
sprockets-rails (3.2.0) lib/sprockets/rails/quiet_assets.rb:13:in call' actionpack (5.1.1) lib/action_dispatch/middleware/remote_ip.rb:79:incall'
actionpack (5.1.1) lib/action_dispatch/middleware/request_id.rb:25:in call' rack (2.0.3) lib/rack/method_override.rb:22:incall'
rack (2.0.3) lib/rack/runtime.rb:22:in call' activesupport (5.1.1) lib/active_support/cache/strategy/local_cache_middleware.rb:27:incall'
actionpack (5.1.1) lib/action_dispatch/middleware/executor.rb:12:in call' actionpack (5.1.1) lib/action_dispatch/middleware/static.rb:125:incall'
rack (2.0.3) lib/rack/sendfile.rb:111:in call' railties (5.1.1) lib/rails/engine.rb:522:incall'
</code>```

Can anyone please help?

答:
After a day of hustling somehow found a workaround, if anyone can better explain what was the issue it would be great. For those who wants the answer see below.

I changed the following line

```<code>= f.select :with_country_id,
             @filterrific.select_options[:with_country_id],
             { :include_blank => '- Any -' },
             { :class => 'form-control' }
</code>```

into the below lines, basically I removed filterrific out of the select option and populated the select options in the form using ruby.

```<code>= f.select :with_country_id, Country.all.collect {|u| [u.name, u.id]},
                                        { :include_blank => '- Any -' },
                                        { :class => 'form-control' }
</code>```

Body:
I am trying to run filterrific in jruby rails environment. Initially, there was no errors and was able to run it succesffully. Few days after that I was working on different controller adding some other gems related with charts. When I came to student controller, now it is giving me this error, I have triple verified all the code and also did beyond compare with your demo app and mine. There was no changes in views, controller, model, js, db and config files, but suddenly I am getting this error "undefined method `empty?' for nil:NilClass" in the following line

.form-group.chardin_box{ :'data-position' => 'top', :'data-intro' => 'Filter by country.' }
  %label Category
  = f.select :with_country_id,
             @filterrific.select_options[:with_country_id],
             { :include_blank => '- Any -' },
             { :class => 'form-control' }

Application Trace:

app/views/students/index.html.haml:22:in block in _app_views_students_index_html_haml___1163931893_2080' app/views/students/index.html.haml:12:in_app_views_students_index_html_haml___1163931893_2080'

Full Trace:

actionview (5.1.1) lib/action_view/helpers/tags/select.rb:36:in grouped_choices?' actionview (5.1.1) lib/action_view/helpers/tags/select.rb:20:inrender'
actionview (5.1.1) lib/action_view/helpers/form_options_helper.rb:163:in select' actionview (5.1.1) lib/action_view/helpers/form_options_helper.rb:817:inselect'
app/views/students/index.html.haml:22:in block in _app_views_students_index_html_haml___1163931893_2080' haml (5.0.1) lib/haml/helpers.rb:382:inblock in capture_haml'
haml (5.0.1) lib/haml/helpers.rb:667:in with_haml_buffer' haml (5.0.1) lib/haml/helpers.rb:378:incapture_haml'
haml (5.0.1) lib/haml/helpers/xss_mods.rb:62:in capture_haml_with_haml_xss' haml (5.0.1) lib/haml/helpers/action_view_mods.rb:45:incapture_with_haml'
actionview (5.1.1) lib/action_view/helpers/form_helper.rb:450:in form_for' haml (5.0.1) lib/haml/helpers/action_view_xss_mods.rb:29:inform_for_with_haml_xss'
filterrific (2.1.2) lib/filterrific/action_view_extension.rb:23:in form_for_filterrific' app/views/students/index.html.haml:12:in_app_views_students_index_html_haml___1163931893_2080'
actionview (5.1.1) lib/action_view/template.rb:157:in block in render' activesupport (5.1.1) lib/active_support/notifications.rb:168:ininstrument'
actionview (5.1.1) lib/action_view/template.rb:352:in instrument_render_template' actionview (5.1.1) lib/action_view/template.rb:155:inrender'
actionview (5.1.1) lib/action_view/renderer/template_renderer.rb:52:in block in render_template' actionview (5.1.1) lib/action_view/renderer/abstract_renderer.rb:42:inblock in instrument'
activesupport (5.1.1) lib/active_support/notifications.rb:166:in block in instrument' activesupport (5.1.1) lib/active_support/notifications/instrumenter.rb:21:ininstrument'
activesupport (5.1.1) lib/active_support/notifications.rb:166:in instrument' actionview (5.1.1) lib/action_view/renderer/abstract_renderer.rb:41:ininstrument'
actionview (5.1.1) lib/action_view/renderer/template_renderer.rb:51:in block in render_template' actionview (5.1.1) lib/action_view/renderer/template_renderer.rb:59:inrender_with_layout'
actionview (5.1.1) lib/action_view/renderer/template_renderer.rb:50:in render_template' actionview (5.1.1) lib/action_view/renderer/template_renderer.rb:14:inrender'
actionview (5.1.1) lib/action_view/renderer/renderer.rb:42:in render_template' actionview (5.1.1) lib/action_view/renderer/renderer.rb:23:inrender'
actionview (5.1.1) lib/action_view/rendering.rb:103:in _render_template' actionpack (5.1.1) lib/action_controller/metal/streaming.rb:217:in_render_template'
actionview (5.1.1) lib/action_view/rendering.rb:83:in render_to_body' actionpack (5.1.1) lib/action_controller/metal/rendering.rb:52:inrender_to_body'
actionpack (5.1.1) lib/action_controller/metal/renderers.rb:141:in render_to_body' actionpack (5.1.1) lib/abstract_controller/rendering.rb:24:inrender'
actionpack (5.1.1) lib/action_controller/metal/rendering.rb:36:in render' actionpack (5.1.1) lib/action_controller/metal/instrumentation.rb:44:inblock in render'
activesupport (5.1.1) lib/active_support/core_ext/benchmark.rb:12:in block in ms' /home/balaji/Documents/balaji/unl/PhD/railswebapp/jruby-9.1.10.0/lib/ruby/stdlib/benchmark.rb:308:inrealtime'
activesupport (5.1.1) lib/active_support/core_ext/benchmark.rb:12:in ms' actionpack (5.1.1) lib/action_controller/metal/instrumentation.rb:44:inblock in render'
actionpack (5.1.1) lib/action_controller/metal/instrumentation.rb:87:in cleanup_view_runtime' activerecord (5.1.1) lib/active_record/railties/controller_runtime.rb:29:incleanup_view_runtime'
actionpack (5.1.1) lib/action_controller/metal/instrumentation.rb:43:in render' actionpack (5.1.1) lib/action_controller/metal/implicit_render.rb:33:indefault_render'
actionpack (5.1.1) lib/action_controller/metal/basic_implicit_render.rb:4:in block in send_action' org/jruby/RubyKernel.java:1747:intap'
actionpack (5.1.1) lib/action_controller/metal/basic_implicit_render.rb:4:in send_action' actionpack (5.1.1) lib/abstract_controller/base.rb:186:inprocess_action'
actionpack (5.1.1) lib/action_controller/metal/rendering.rb:30:in process_action' actionpack (5.1.1) lib/abstract_controller/callbacks.rb:20:inblock in process_action'
activesupport (5.1.1) lib/active_support/callbacks.rb:131:in run_callbacks' actionpack (5.1.1) lib/abstract_controller/callbacks.rb:19:inprocess_action'
actionpack (5.1.1) lib/action_controller/metal/rescue.rb:20:in process_action' actionpack (5.1.1) lib/action_controller/metal/instrumentation.rb:32:inblock in process_action'
activesupport (5.1.1) lib/active_support/notifications.rb:166:in block in instrument' activesupport (5.1.1) lib/active_support/notifications/instrumenter.rb:21:ininstrument'
activesupport (5.1.1) lib/active_support/notifications.rb:166:in instrument' actionpack (5.1.1) lib/action_controller/metal/instrumentation.rb:30:inprocess_action'
actionpack (5.1.1) lib/action_controller/metal/params_wrapper.rb:252:in process_action' activerecord (5.1.1) lib/active_record/railties/controller_runtime.rb:22:inprocess_action'
actionpack (5.1.1) lib/abstract_controller/base.rb:124:in process' actionview (5.1.1) lib/action_view/rendering.rb:30:inprocess'
actionpack (5.1.1) lib/action_controller/metal.rb:189:in dispatch' actionpack (5.1.1) lib/action_controller/metal.rb:253:indispatch'
actionpack (5.1.1) lib/action_dispatch/routing/route_set.rb:49:in dispatch' actionpack (5.1.1) lib/action_dispatch/routing/route_set.rb:31:inserve'
actionpack (5.1.1) lib/action_dispatch/journey/router.rb:46:in block in serve' org/jruby/RubyArray.java:1734:ineach'
actionpack (5.1.1) lib/action_dispatch/journey/router.rb:33:in serve' actionpack (5.1.1) lib/action_dispatch/routing/route_set.rb:832:incall'
rack (2.0.3) lib/rack/etag.rb:25:in call' rack (2.0.3) lib/rack/conditional_get.rb:25:incall'
rack (2.0.3) lib/rack/head.rb:12:in call' torquebox-web-3.2.0 (java) lib/torquebox/session/servlet_store.rb:47:incall'
actionpack (5.1.1) lib/action_dispatch/middleware/cookies.rb:613:in call' activerecord (5.1.1) lib/active_record/migration.rb:556:incall'
actionpack (5.1.1) lib/action_dispatch/middleware/callbacks.rb:26:in block in call' activesupport (5.1.1) lib/active_support/callbacks.rb:97:inrun_callbacks'
actionpack (5.1.1) lib/action_dispatch/middleware/callbacks.rb:24:in call' actionpack (5.1.1) lib/action_dispatch/middleware/executor.rb:12:incall'
actionpack (5.1.1) lib/action_dispatch/middleware/debug_exceptions.rb:59:in call' actionpack (5.1.1) lib/action_dispatch/middleware/show_exceptions.rb:31:incall'
railties (5.1.1) lib/rails/rack/logger.rb:36:in call_app' railties (5.1.1) lib/rails/rack/logger.rb:24:inblock in call'
activesupport (5.1.1) lib/active_support/tagged_logging.rb:69:in block in tagged' activesupport (5.1.1) lib/active_support/tagged_logging.rb:26:intagged'
activesupport (5.1.1) lib/active_support/tagged_logging.rb:69:in tagged' railties (5.1.1) lib/rails/rack/logger.rb:24:incall'
sprockets-rails (3.2.0) lib/sprockets/rails/quiet_assets.rb:13:in call' actionpack (5.1.1) lib/action_dispatch/middleware/remote_ip.rb:79:incall'
actionpack (5.1.1) lib/action_dispatch/middleware/request_id.rb:25:in call' rack (2.0.3) lib/rack/method_override.rb:22:incall'
rack (2.0.3) lib/rack/runtime.rb:22:in call' activesupport (5.1.1) lib/active_support/cache/strategy/local_cache_middleware.rb:27:incall'
actionpack (5.1.1) lib/action_dispatch/middleware/executor.rb:12:in call' actionpack (5.1.1) lib/action_dispatch/middleware/static.rb:125:incall'
rack (2.0.3) lib/rack/sendfile.rb:111:in call' railties (5.1.1) lib/rails/engine.rb:522:incall'

Can anyone please help?

Body:
After a day of hustling somehow found a workaround, if anyone can better explain what was the issue it would be great. For those who wants the answer see below.

I changed the following line

= f.select :with_country_id,
             @filterrific.select_options[:with_country_id],
             { :include_blank => '- Any -' },
             { :class => 'form-control' }

into the below lines, basically I removed filterrific out of the select option and populated the select options in the form using ruby.

= f.select :with_country_id, Country.all.collect {|u| [u.name, u.id]},
                                        { :include_blank => '- Any -' },
                                        { :class => 'form-control' }


问:
How to fix - RuntimeException in Encrypter.php line 43
App.php - File

This is my App,php file

```<code>'key' => env('APP_KEY'),

'cipher' => 'AES-256-CBC',
</code>```

.env - File

This is my .env file

```<code>APP_ENV=local
APP_KEY=base64:CETuLOZZZi5QEEYXhyCO/O7l7fhM6LI5clvsT59cgTM=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=ads
DB_USERNAME=root
DB_PASSWORD=null

PUSHER_APP_ID=
PUSHER_KEY=
PUSHER_SECRET=
</code>```

Error was:

```<code>> RuntimeException in Encrypter.php line 43: The only supported ciphers
> are AES-128-CBC and AES-256-CBC with the correct key lengths.
</code>```

Developers please help me to solve this problems.
  Thanks

答: Check to ensure you .env file has value in APP_KEY, if not and you just created a new project or cloned a project, you will need to run php artisan key:generate in your console or terminal.

Body:
App.php - File

This is my App,php file

'key' => env('APP_KEY'),

'cipher' => 'AES-256-CBC',

.env - File

This is my .env file

APP_ENV=local
APP_KEY=base64:CETuLOZZZi5QEEYXhyCO/O7l7fhM6LI5clvsT59cgTM=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=ads
DB_USERNAME=root
DB_PASSWORD=null

PUSHER_APP_ID=
PUSHER_KEY=
PUSHER_SECRET=

Error was:

> RuntimeException in Encrypter.php line 43: The only supported ciphers
> are AES-128-CBC and AES-256-CBC with the correct key lengths.

Developers please help me to solve this problems.
  Thanks


问:
How to scroll down a page until all the views appeared?
In my page I have lots of data. The first time page opened i can see only number of data. When I scroll down the page other datas are starting to appear. It is going repeatedly. Problem is I wanna see all datas in my page and take their names but when I use List <WebElement> listItems=driver.findElement(AAA).findElements(BBB);this code, I can only get datas from first page. How can I see the others? (I don't want to use an id or class at the bottom. And scroll till to see it)

答:
Well, you surely can scroll to the bottom. The simplest way is to use JavaScript to see the scroll height and scroll to it:

```<code>JavascriptExecutor jse = (JavascriptExecutor) driver;
Long scrollHeight = (Long) jse.executeScript("return document.scrollHeight;");
jse.ExecuteScript("document.scrollTop="+scrollHeight);
</code>```

However, this only works if the page already has a scroll bar with the correct height. If it does not render fully at once, the scroll height might not be correct. There is a way around this, but I have never tried this with pages, only tables.

You press the PgDn button and check the scrollTop. You need to wait a second after each PgDn, because rendering the scrolling might take some time and you need the scrollTop to be correct already. As soon as the previous and current scrollTop are the same, you are done.

I have not personally tried the method I use here to press PgDn. I just send it to the body element here. The alternative is to use Actions.

```<code>JavascriptExecutor jse = (JavascriptExecutor) driver;
WebElement body = driver.findElement(By.tagName("body"));
String prevTop ="-1";
boolean continueScrolling = false;
do {
    body.sendKeys(Keys.PAGE_DOWN);
    Thread.sleep(1000); // you might need to add handling for InterruptedException
    String currentTop = String.valueOf(jse.executeScript("return document.scrollTop;"));
    continueScrolling = !currentTop.equals(prevTop);
    prevTop = currentTop;
} while (continueScrolling);
</code>```

Body:
Well, you surely can scroll to the bottom. The simplest way is to use JavaScript to see the scroll height and scroll to it:

JavascriptExecutor jse = (JavascriptExecutor) driver;
Long scrollHeight = (Long) jse.executeScript("return document.scrollHeight;");
jse.ExecuteScript("document.scrollTop="+scrollHeight);

However, this only works if the page already has a scroll bar with the correct height. If it does not render fully at once, the scroll height might not be correct. There is a way around this, but I have never tried this with pages, only tables.

You press the PgDn button and check the scrollTop. You need to wait a second after each PgDn, because rendering the scrolling might take some time and you need the scrollTop to be correct already. As soon as the previous and current scrollTop are the same, you are done.

I have not personally tried the method I use here to press PgDn. I just send it to the body element here. The alternative is to use Actions.

JavascriptExecutor jse = (JavascriptExecutor) driver;
WebElement body = driver.findElement(By.tagName("body"));
String prevTop ="-1";
boolean continueScrolling = false;
do {
    body.sendKeys(Keys.PAGE_DOWN);
    Thread.sleep(1000); // you might need to add handling for InterruptedException
    String currentTop = String.valueOf(jse.executeScript("return document.scrollTop;"));
    continueScrolling = !currentTop.equals(prevTop);
    prevTop = currentTop;
} while (continueScrolling);


问:
VS 2010 WCF service reference https connection error
I've got an error while updating WCF service reference in Visual Studio 2010:

There was an error downloading 'https://192.16.0.76/MyService.svc'.
The request was aborted: Could not create SSL/TLS secure channel.
Metadata contains a reference that cannot be resolved: 'https://192.16.0.76/MyService.svc'.
The HTTP request was forbidden with client authentication scheme 'Anonymous'.
The remote server returned an error: (403) Forbidden.

Two weeks ago reference update worked fine and nothing was changed in web.config file. Now I can't update service reference and add new features to the Silverlight application. I've looked for answer on the Internet and most people advice to check certificates on the developer's pc. I haven't canged any certificates fon my pc and I also add ny certificate to the local machine store as well. Maybe I should change the default certicate for Visual Studio but I can't find how to do this.

Here is my web.config file :

```<code>  <source name="System.ServiceModel"
      switchValue="Error,Warning"
      propagateActivity="true">
    <listeners>
      <add type="System.Diagnostics.DefaultTraceListener"
              name="Default">
        <filter type="" />
      </add>
      <add name="ServiceModelTraceListener">
        <filter type="" />
      </add>
    </listeners>
  </source>

  <source name="System.ServiceModel.MessageLogging"
  switchValue="Warning, Error">
    <listeners>
      <add type="System.Diagnostics.DefaultTraceListener" name="Default">
        <filter type="" />
      </add>
      <add name="ServiceModelMessageLoggingListener">
        <filter type="" />
      </add>
    </listeners>
  </source>
</sources>

<sharedListeners>

  <add initializeData="tracelog.svclog"
      type="System.Diagnostics.XmlWriterTraceListener, System,
                    Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
      name="ServiceModelTraceListener" traceOutputOptions="Timestamp">
    <filter type="" />
  </add>
  <add initializeData="messages.svclog"
      type="System.Diagnostics.XmlWriterTraceListener,
                    System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
      name="ServiceModelMessageLoggingListener" traceOutputOptions="Timestamp">
    <filter type="" />
  </add>
</sharedListeners>

<trace autoflush="true" />
</code>```

```<code><pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
<httpRuntime executionTimeout="600" />
</code>```

```<code>    </behavior>
  </serviceBehaviors>
</behaviors>
<bindings>
  <customBinding>
    <binding name="MyForm.Web.MyService.customBinding0"
         receiveTimeout="00:10:00" sendTimeout="00:10:00"

           openTimeout="00:10:00" closeTimeout="00:10:00">
      <binaryMessageEncoding/>
      <httpsTransport maxReceivedMessageSize="2147483647" />
    </binding>
  </customBinding>
  <wsHttpBinding>
    <binding name="CertificateWithTransport"
           receiveTimeout="00:10:00" sendTimeout="00:10:00"
           openTimeout="00:10:00" closeTimeout="00:10:00"
            maxReceivedMessageSize="2147483647">
      <security mode="Transport" >
        <transport clientCredentialType="Certificate"  />
      </security>
      <readerQuotas maxDepth="2640000"
               maxStringContentLength="2000000000"
               maxArrayLength="2000000000"
               maxBytesPerRead="2000000000"
               maxNameTableCharCount="2000000000" />
    </binding>
  </wsHttpBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
<services>
  <service behaviorConfiguration="ServiceBehavior" name="MyForm.Web.MyService">
    <endpoint address="" binding="wsHttpBinding" bindingConfiguration="CertificateWithTransport"
      contract="MyForm.Web.MyService" />
  </service>
</services>
<diagnostics >
  <messageLogging logMalformedMessages="true"
   logMessagesAtServiceLevel="true"
   logMessagesAtTransportLevel="true"
    />
</diagnostics>
</code>```

Any help will be appreciated.

[Upd] It seems that it can be caused by problems with certificate on my pc. How can I choose the certificate that will be used for https connection to the web service ? I've found similar topics on the internet but there were no solutions for it.

答: Going through WCF – 2 Way SSL Security using Certificates , might help you.</p>

Body:
I've got an error while updating WCF service reference in Visual Studio 2010:

There was an error downloading 'https://192.16.0.76/MyService.svc'.
The request was aborted: Could not create SSL/TLS secure channel.
Metadata contains a reference that cannot be resolved: 'https://192.16.0.76/MyService.svc'.
The HTTP request was forbidden with client authentication scheme 'Anonymous'.
The remote server returned an error: (403) Forbidden.

Two weeks ago reference update worked fine and nothing was changed in web.config file. Now I can't update service reference and add new features to the Silverlight application. I've looked for answer on the Internet and most people advice to check certificates on the developer's pc. I haven't canged any certificates fon my pc and I also add ny certificate to the local machine store as well. Maybe I should change the default certicate for Visual Studio but I can't find how to do this.

Here is my web.config file :

  <source name="System.ServiceModel"
      switchValue="Error,Warning"
      propagateActivity="true">
    <listeners>
      <add type="System.Diagnostics.DefaultTraceListener"
              name="Default">
        <filter type="" />
      </add>
      <add name="ServiceModelTraceListener">
        <filter type="" />
      </add>
    </listeners>
  </source>

  <source name="System.ServiceModel.MessageLogging"
  switchValue="Warning, Error">
    <listeners>
      <add type="System.Diagnostics.DefaultTraceListener" name="Default">
        <filter type="" />
      </add>
      <add name="ServiceModelMessageLoggingListener">
        <filter type="" />
      </add>
    </listeners>
  </source>
</sources>

<sharedListeners>

  <add initializeData="tracelog.svclog"
      type="System.Diagnostics.XmlWriterTraceListener, System,
                    Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
      name="ServiceModelTraceListener" traceOutputOptions="Timestamp">
    <filter type="" />
  </add>
  <add initializeData="messages.svclog"
      type="System.Diagnostics.XmlWriterTraceListener,
                    System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
      name="ServiceModelMessageLoggingListener" traceOutputOptions="Timestamp">
    <filter type="" />
  </add>
</sharedListeners>

<trace autoflush="true" />

<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
<httpRuntime executionTimeout="600" />

    </behavior>
  </serviceBehaviors>
</behaviors>
<bindings>
  <customBinding>
    <binding name="MyForm.Web.MyService.customBinding0"
         receiveTimeout="00:10:00" sendTimeout="00:10:00"

           openTimeout="00:10:00" closeTimeout="00:10:00">
      <binaryMessageEncoding/>
      <httpsTransport maxReceivedMessageSize="2147483647" />
    </binding>
  </customBinding>
  <wsHttpBinding>
    <binding name="CertificateWithTransport"
           receiveTimeout="00:10:00" sendTimeout="00:10:00"
           openTimeout="00:10:00" closeTimeout="00:10:00"
            maxReceivedMessageSize="2147483647">
      <security mode="Transport" >
        <transport clientCredentialType="Certificate"  />
      </security>
      <readerQuotas maxDepth="2640000"
               maxStringContentLength="2000000000"
               maxArrayLength="2000000000"
               maxBytesPerRead="2000000000"
               maxNameTableCharCount="2000000000" />
    </binding>
  </wsHttpBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
<services>
  <service behaviorConfiguration="ServiceBehavior" name="MyForm.Web.MyService">
    <endpoint address="" binding="wsHttpBinding" bindingConfiguration="CertificateWithTransport"
      contract="MyForm.Web.MyService" />
  </service>
</services>
<diagnostics >
  <messageLogging logMalformedMessages="true"
   logMessagesAtServiceLevel="true"
   logMessagesAtTransportLevel="true"
    />
</diagnostics>

Any help will be appreciated.

[Upd] It seems that it can be caused by problems with certificate on my pc. How can I choose the certificate that will be used for https connection to the web service ? I've found similar topics on the internet but there were no solutions for it.


答:
If you want to fill a 3-by-5 matrix with all of the values in test, making sure each row has no repeated values, you can do this very succinctly by using toeplitz to first generate an index matrix, then randomly permute the dimensions with randperm:

```<code>index = toeplitz(1:3, [3 5:-1:2]);
index = index(randperm(3), randperm(5));
</code>```

And a sample index:

```<code>index =

     1     5     4     2     3
     4     3     2     5     1
     5     4     3     1     2
</code>```

If your values in test are the numbers 1 through 5, this should be all you need to do. If test could be any vector with with 5 different numbers, three of each, then you can get the unique values of your test vector and index them with index. This solution will generalize to any test vector:

```<code>test = [3 3 3 7 7 7 5 5 5 9 9 9 4 4 4];    % Sample data
uniqueValues = unique(test);               % Get the unique values [3 4 5 7 9]
M = uniqueValues(index);                   % Use index as generated above
</code>```

And the result will be guaranteed to be a reordered version of what's in test:

```<code>M =

     3     9     7     4     5
     7     5     4     9     3
     9     7     5     3     4
</code>```

Title: Auto-fill matrix without row-repetitions

Body:
If you want to fill a 3-by-5 matrix with all of the values in test, making sure each row has no repeated values, you can do this very succinctly by using toeplitz to first generate an index matrix, then randomly permute the dimensions with randperm:

index = toeplitz(1:3, [3 5:-1:2]);
index = index(randperm(3), randperm(5));

And a sample index:

index =

     1     5     4     2     3
     4     3     2     5     1
     5     4     3     1     2

If your values in test are the numbers 1 through 5, this should be all you need to do. If test could be any vector with with 5 different numbers, three of each, then you can get the unique values of your test vector and index them with index. This solution will generalize to any test vector:

test = [3 3 3 7 7 7 5 5 5 9 9 9 4 4 4];    % Sample data
uniqueValues = unique(test);               % Get the unique values [3 4 5 7 9]
M = uniqueValues(index);                   % Use index as generated above

And the result will be guaranteed to be a reordered version of what's in test:

M =

     3     9     7     4     5
     7     5     4     9     3
     9     7     5     3     4


问:
Program to send UDP messages at a constant rate of a few Kbit/s sending them at 3Mbit/s?
The following program is supposed to send a message of size bytes in a
constant rate of args.rate bit/s on any channel (assuming the channel supports that rate) via UDP. There's probably a better way to do it but I believe this should work:

```<code>double interval = (double)(bytes * 8) / (double)args.rate;
struct timespec s, e;
if (clock_gettime(CLOCK_REALTIME, &s) == -1)
  REPORT_AND_EXIT;
while(true) {
  ssize_t rc = sendto(sockfd, args.msg, bytes, 0, (struct sockaddr *)(&peer),
      (socklen_t)sizeof(peer));
  if (rc == -1)
    REPORT_AND_EXIT;
  do {
    clock_gettime(CLOCK_REALTIME, &e);
  } while (ELAPSED(s, e) < interval);
  s = e;
}
</code>```

For completion sake here is the entire code (both receiver and transmitter).

With bytes = 6, args.rate = 638000, running it on lo, both iftop and nload (two network monitoring applications) show a constant rate of about 3Mbit/s, while I was expecting 638Kbit/s. I could not find what was wrong with my program so I used tcpdump to see what was going on, and unless I'm misinterpreting its results it informs me that after one second exactly 13286 6 byte UDP packets had been sent, amounting to 637728 bits or 637.728 Kbit/s, which is what I was expecting. So why is iftop showing me 3Mbit/s? I set both iftop and tcpdump to monitor lo only and I had nothing else running (tcpdump captured a single ICMP request that did not come from my application, but it should be negligible).

Here is the output of tcpdump -ttt -i lo and below is a R script that calculates from the log how many bits have been sent after one second (after cut -d' ' -f1 log | cut -d'.' -f2 | sed 's/^/0./ >log2)

```<code>library(dplyr)
df <- read.csv("log2", header=F)
names(df) <- c("time")
df %>%
  mutate(cum=cumsum(time), ct=as.numeric(row(df)), bytes=6*ct, bits=8*bytes, kbits=bits/1000) %>%
  filter(cum >= 1.0 - 1e-4) %>%
  head
</code>```

Results:

```<code>   time      cum    ct bytes   bits   kbits
7.5e-05 0.999931 13285 79710 637680 637.680
7.5e-05 1.000006 13286 79716 637728 637.728
7.6e-05 1.000082 13287 79722 637776 637.776
7.5e-05 1.000157 13288 79728 637824 637.824
7.5e-05 1.000232 13289 79734 637872 637.872
7.5e-05 1.000307 13290 79740 637920 637.920
</code>```

答:
Monitoring applications show you the real network traffic, which includes the UDP overhead.

The IP header is 20 bytes, and the UDP header is 8 bytes, totaling to a 28 bytes overhead. The 6 bytes packet you send are 34 bytes in real size.

With those 13,286 packets are 451,724 bytes, or 3,613,792 bits long. This is close to the 3Mbits you see.

The overhead below IP are not counted in IP monitoring because not relevant for an IP connection, and because it is not constant on a network path (for example, it can change when going through a modem).

Body:
The following program is supposed to send a message of size bytes in a
constant rate of args.rate bit/s on any channel (assuming the channel supports that rate) via UDP. There's probably a better way to do it but I believe this should work:

double interval = (double)(bytes * 8) / (double)args.rate;
struct timespec s, e;
if (clock_gettime(CLOCK_REALTIME, &s) == -1)
  REPORT_AND_EXIT;
while(true) {
  ssize_t rc = sendto(sockfd, args.msg, bytes, 0, (struct sockaddr *)(&peer),
      (socklen_t)sizeof(peer));
  if (rc == -1)
    REPORT_AND_EXIT;
  do {
    clock_gettime(CLOCK_REALTIME, &e);
  } while (ELAPSED(s, e) < interval);
  s = e;
}

For completion sake here is the entire code (both receiver and transmitter).

With bytes = 6, args.rate = 638000, running it on lo, both iftop and nload (two network monitoring applications) show a constant rate of about 3Mbit/s, while I was expecting 638Kbit/s. I could not find what was wrong with my program so I used tcpdump to see what was going on, and unless I'm misinterpreting its results it informs me that after one second exactly 13286 6 byte UDP packets had been sent, amounting to 637728 bits or 637.728 Kbit/s, which is what I was expecting. So why is iftop showing me 3Mbit/s? I set both iftop and tcpdump to monitor lo only and I had nothing else running (tcpdump captured a single ICMP request that did not come from my application, but it should be negligible).

Here is the output of tcpdump -ttt -i lo and below is a R script that calculates from the log how many bits have been sent after one second (after cut -d' ' -f1 log | cut -d'.' -f2 | sed 's/^/0./ >log2)

library(dplyr)
df <- read.csv("log2", header=F)
names(df) <- c("time")
df %>%
  mutate(cum=cumsum(time), ct=as.numeric(row(df)), bytes=6*ct, bits=8*bytes, kbits=bits/1000) %>%
  filter(cum >= 1.0 - 1e-4) %>%
  head

Results:

   time      cum    ct bytes   bits   kbits
7.5e-05 0.999931 13285 79710 637680 637.680
7.5e-05 1.000006 13286 79716 637728 637.728
7.6e-05 1.000082 13287 79722 637776 637.776
7.5e-05 1.000157 13288 79728 637824 637.824
7.5e-05 1.000232 13289 79734 637872 637.872
7.5e-05 1.000307 13290 79740 637920 637.920


问:
Python - Add tuple values to repeated keys in a dict
I've been trying to convert this test.csv file:

```<code>a,b,4
a,c,2
b,a,4
b,c,1
b,d,5
c,a,2
c,b,1
c,d,8
c,e,10
d,b,5
d,c,8
d,e,2
d,z,6
e,c,10
e,d,2
e,z,3
z,d,6
z,e,3
</code>```

Into this formatting. So far when I try to convert it, the repeated keys get override and not added as a second value. Could someone show me how to get this formatting?

```<code>G1 = {
    'a': [('b', 4), ('c', 2)],
    'b': [('a', 4), ('c', 1), ('d', 5)],
    'c': [('a', 2), ('b', 1), ('d', 8), ('e', 10)],
    'd': [('b', 5), ('c', 8), ('e', 2), ('z', 6)],
    'e': [('c', 10), ('d', 2), ('z', 3)],
    'z': [('d', 6), ('e', 3)],
}
</code>```

This is the code that converts the file into a dict, but replaces the new values for the repeated keys. I'd like to know how to add the values as tuples and for repeated keys, add the tuples as second values.

```<code>reader = csv.reader(open('test.csv'))
arcos = {}
for row in reader:
    key = row[0]
    arcos[key] = row[1:]
</code>```

And the result:

```<code>{
'a': ['c', 2.0],
 'b': ['d', 5.0],
 'c': ['e', 10.0],
 'd': ['z', 6.0],
 'e': ['z', 3.0],
 'z': ['e', 3.0]
}
</code>```

I hope what I've requested is possible.

Body:
I've been trying to convert this test.csv file:

a,b,4
a,c,2
b,a,4
b,c,1
b,d,5
c,a,2
c,b,1
c,d,8
c,e,10
d,b,5
d,c,8
d,e,2
d,z,6
e,c,10
e,d,2
e,z,3
z,d,6
z,e,3

Into this formatting. So far when I try to convert it, the repeated keys get override and not added as a second value. Could someone show me how to get this formatting?

G1 = {
    'a': [('b', 4), ('c', 2)],
    'b': [('a', 4), ('c', 1), ('d', 5)],
    'c': [('a', 2), ('b', 1), ('d', 8), ('e', 10)],
    'd': [('b', 5), ('c', 8), ('e', 2), ('z', 6)],
    'e': [('c', 10), ('d', 2), ('z', 3)],
    'z': [('d', 6), ('e', 3)],
}

This is the code that converts the file into a dict, but replaces the new values for the repeated keys. I'd like to know how to add the values as tuples and for repeated keys, add the tuples as second values.

reader = csv.reader(open('test.csv'))
arcos = {}
for row in reader:
    key = row[0]
    arcos[key] = row[1:]

And the result:

{
'a': ['c', 2.0],
 'b': ['d', 5.0],
 'c': ['e', 10.0],
 'd': ['z', 6.0],
 'e': ['z', 3.0],
 'z': ['e', 3.0]
}

I hope what I've requested is possible.

Body:
You can use groupby method and make this easy:

from itertools import groupby

with open('out.csv') as f:
    print({k:[(i.split(',')[1],i.split(',')[2]) for i in g] for k, g in groupby([i.strip() for i in f],lambda x: x.split(',')[0])})

Result:

 {'a': [('b', '4'), ('c', '2')], 'c': [('a', '2'), ('b', '1'), ('d', '8'), ('e', '10')], 'b': [('a', '4'), ('c', '1'), ('d', '5')], 'e': [('c', '10'), ('d', '2'), ('z', '3')], 'd': [('b', '5'), ('c', '8'), ('e', '2'), ('z', '6')], 'z': [('d', '6'), ('e', '3')]}


问:
When would getters and setters with mutex be thread safe?
Consider the following class:

```<code>class testThreads
{
private:
    int var; // variable to be modified
    std::mutex mtx; // mutex
public:
    void set_var(int arg) // setter
    {
        std::lock_guard<std::mutex> lk(mtx);
        var = arg;
    }

    int get_var() // getter
    {
        std::lock_guard<std::mutex> lk(mtx);
        return var;
    }

    void hundred_adder()
    {
        for(int i = 0; i < 100; i++)
        {
            int got = get_var();
            set_var(got + 1);
            sleep(0.1);
        }
     }
};
</code>```

When I create two threads in main(), each with a thread function of hundred_adder modifying the same variable var, the end result of the var is always different i.e. not 200 but some other number.

Conceptually speaking, why is this use of mutex with getter and setter functions not thread-safe? Do the lock-guards fail to prevent the race-condition to var? And what would be an alternative solution?

答: Why don't you just use std::atomic for the shared data (var in this case)? That will be more safe efficient.</p>

Body:
Consider the following class:

class testThreads
{
private:
    int var; // variable to be modified
    std::mutex mtx; // mutex
public:
    void set_var(int arg) // setter
    {
        std::lock_guard<std::mutex> lk(mtx);
        var = arg;
    }

    int get_var() // getter
    {
        std::lock_guard<std::mutex> lk(mtx);
        return var;
    }

    void hundred_adder()
    {
        for(int i = 0; i < 100; i++)
        {
            int got = get_var();
            set_var(got + 1);
            sleep(0.1);
        }
     }
};

When I create two threads in main(), each with a thread function of hundred_adder modifying the same variable var, the end result of the var is always different i.e. not 200 but some other number.

Conceptually speaking, why is this use of mutex with getter and setter functions not thread-safe? Do the lock-guards fail to prevent the race-condition to var? And what would be an alternative solution?


问:
How use my data for sklearn.naive_bayes.GaussianNB
I am trying to understand how Naive Bayes works and want to create some example using sklearn.naive_bayes.GaussianNB.
I have a data:

```<code>[
[1, 0],
[1, 1],
[0, 1],
// ...
];
</code>```

Where here [[1, 0]] the first number is the type of a pet: cat or dog, and the second one: light or dark color has a pet. After that I want to give a list like [0,0,1] that represent a color and predict the type of pet.

And I am trying to use example from http://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.GaussianNB.html. I rewrote this:

```<code>import numpy as np
X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
Y = np.array([1, 1, 1, 2, 2, 2])
</code>```

To:

```<code>import numpy as np
X = np.array([ [1, 0], [1, 1], [0, 1] ])
</code>```

But what should be instead of Y = np.array([1, 1, 1, 2, 2, 2]) in my case?

Or maybe I should keep my data in another one format?

答:
Your Y should be a one dimensional array of 'class labels'.

For each element in your data set X, you'd have one element in Y that gives the classification, e.g. 0 for a dog, 1 for a cat.

It looks like you have included the class label as the first element in your X, you might want to separate those into Y.

Due to the simplicity of the classification and the features of the data set GaussianNB seems to be a bit overkill, but I understand you're just exploring the concept.

Body:
I am trying to understand how Naive Bayes works and want to create some example using sklearn.naive_bayes.GaussianNB.
I have a data:

[
[1, 0],
[1, 1],
[0, 1],
// ...
];

Where here [[1, 0]] the first number is the type of a pet: cat or dog, and the second one: light or dark color has a pet. After that I want to give a list like [0,0,1] that represent a color and predict the type of pet.

And I am trying to use example from http://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.GaussianNB.html. I rewrote this:

import numpy as np
X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
Y = np.array([1, 1, 1, 2, 2, 2])

To:

import numpy as np
X = np.array([ [1, 0], [1, 1], [0, 1] ])

But what should be instead of Y = np.array([1, 1, 1, 2, 2, 2]) in my case?

Or maybe I should keep my data in another one format?


问:
what is the actual use of interface in java?

Possible Duplicates:

  Abstract class and Interface class?

  Java: interface / abstract classes / abstract method

In Java, whatever use of interface is fulfilled by abstract class. I know one advantage of interfaces is that if we implement an interface then we can also extend another class. Is there any other use or advantage of interface in Java?

答:
Interfaces allow the nominative typing in Java to work across disjoint class hierarchies.

This is due to the "single inheritance" limitation on a class hierarchy and "closed types". I will hold my tongue on subtype polymorphism and Java's implementation of it ;-)

There are other solutions to this problem such as dynamic typing, structural typing, multiple inheritance, and traits, etc. Each approach has advantages and dis-advantages. Interfaces were just the approach that Java took.


问:
How to use two google api keys simultaneously?
I wanna use google map and google place
So, I have got map api and place api.

But the tutorial teaches me one api usage.

for example
example-project of google map is

```<code><meta-data
   android:name="com.google.android.geo.API_KEY"
   android:value="@string/google_maps_key" />
</code>```

example-pro ject of google place is

```<code><meta-data
   android:name="com.google.android.geo.API_KEY"
   android:value="@string/google_places_key" />
</code>```

How can I use this two apis simultaneously??

答: you just need 1 key, make sure you enable map API and place API at google dev console for your project</p>

Body:
I wanna use google map and google place
So, I have got map api and place api.

But the tutorial teaches me one api usage.

for example
example-project of google map is

<meta-data
   android:name="com.google.android.geo.API_KEY"
   android:value="@string/google_maps_key" />

example-pro ject of google place is

<meta-data
   android:name="com.google.android.geo.API_KEY"
   android:value="@string/google_places_key" />

How can I use this two apis simultaneously??


问:
Angular 4 Can't bind to 'dragula' since it isn't a known property of 'div'
I'm struggling with binding ng2-dragula to AspNetCore SPA template. Tried everything, but still getting:

```<code>Exception: Call to Node module failed with error: Error: Template parse errors:
Can't bind to 'dragula' since it isn't a known property of 'div'. ("
<div>
<div class='wrapper'>
<div class='container' [ERROR ->][dragula]='"first-bag"'>
<div>Drag/drop item 1</div>
</div>
"): ng:///AppModule/DragulaComponent.html@7:31
at syntaxError (C:\Users\...\ClientApp\dist\vendor.js:36125:34)
at ...
</code>```

Has anyone used ng2-dragula in AspDotnetCoreSpa?

dragula.component.html

```<code><div>
 <div class='wrapper'>
  <div class='container' [dragula]='"first-bag"'>
   <div>Drag/drop item 1</div>
  </div>
 </div>
</div>
</code>```

dragula.component.ts

```<code>import { Component } from '@angular/core';
import { DragulaModule, DragulaService } from 'ng2-dragula'

@Component({
   selector: 'dragula',
   templateUrl: './dragula.component.html',
   styleUrls: ['../../../../node_modules/dragula/dist/dragula.min.css']
 })
 export class DragulaComponent {
}
</code>```

app.module.client.ts

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { DragulaModule } from 'ng2-dragula';
import { HttpModule } from '@angular/http';
import { sharedConfig } from './app.module.shared';

@NgModule({
    bootstrap: sharedConfig.bootstrap,
    declarations: sharedConfig.declarations,
    imports: [
        BrowserModule,
        FormsModule,
        DragulaModule,
        HttpModule,
        ...sharedConfig.imports
    ],
    providers: [
        { provide: 'ORIGIN_URL', useValue: location.origin }
    ]
})
export class AppModule {
}
</code>```

app.module.shared.ts

```<code>import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

import { AppComponent } from './components/app/app.component'
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';
import { DragulaComponent } from './components/dragula/dragula.component';

export const sharedConfig: NgModule = {
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        NavMenuComponent,
        CounterComponent,
        FetchDataComponent,
        DragulaComponent,
        HomeComponent
    ],
    imports: [
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: 'counter', component: CounterComponent },
            { path: 'fetch-data', component: FetchDataComponent },
            { path: 'dragula', component: DragulaComponent },
            { path: '**', redirectTo: 'home' }
        ])
    ]
};
</code>```

答: try to import DragulaModule in you app module(top level module)

Body:
I'm struggling with binding ng2-dragula to AspNetCore SPA template. Tried everything, but still getting:

Exception: Call to Node module failed with error: Error: Template parse errors:
Can't bind to 'dragula' since it isn't a known property of 'div'. ("

][dragula]='"first-bag"'>

Drag/drop item 1

"): ng:///AppModule/DragulaComponent.html@7:31
at syntaxError (C:\Users\...\ClientApp\dist\vendor.js:36125:34)
at ...

Has anyone used ng2-dragula in AspDotnetCoreSpa?

dragula.component.html

Drag/drop item 1

dragula.component.ts

import { Component } from '@angular/core';
import { DragulaModule, DragulaService } from 'ng2-dragula'

@Component({
   selector: 'dragula',
   templateUrl: './dragula.component.html',
   styleUrls: ['../../../../node_modules/dragula/dist/dragula.min.css']
 })
 export class DragulaComponent {
}

app.module.client.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { DragulaModule } from 'ng2-dragula';
import { HttpModule } from '@angular/http';
import { sharedConfig } from './app.module.shared';

@NgModule({
    bootstrap: sharedConfig.bootstrap,
    declarations: sharedConfig.declarations,
    imports: [
        BrowserModule,
        FormsModule,
        DragulaModule,
        HttpModule,
        ...sharedConfig.imports
    ],
    providers: [
        { provide: 'ORIGIN_URL', useValue: location.origin }
    ]
})
export class AppModule {
}

app.module.shared.ts

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

import { AppComponent } from './components/app/app.component'
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';
import { DragulaComponent } from './components/dragula/dragula.component';

export const sharedConfig: NgModule = {
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        NavMenuComponent,
        CounterComponent,
        FetchDataComponent,
        DragulaComponent,
        HomeComponent
    ],
    imports: [
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: 'counter', component: CounterComponent },
            { path: 'fetch-data', component: FetchDataComponent },
            { path: 'dragula', component: DragulaComponent },
            { path: '**', redirectTo: 'home' }
        ])
    ]
};


问:
TYPO3: Backend Module linking action of another Controller
I created a simple backend module for TYPO3 (7.6.15), with help of the ExtensionBuilder. The UserController and MediaController have a createAction, showAction and listAction. The PanelController just has the showAction which is the main view of the module.

Now I want to link actions from the other controllers in the template of the showAction.
The content of the view for the PanelController.showAction (MyExt/Resources/Private/Templates/Panel/Show.html) is the following:

```<code><f:layout name="Default" />
<f:section name="content">
  <f:flashMessages />
  <f:link.action action="create" controller="User">Create new User</f:link.action>
  <f:link.action action="create" controller="Media">Create new Media</f:link.action>
</f:section>
</code>```

If clicked on one of the links, I get: "Could not analyse class: "MyExt\MyExt\Controller\UserController" maybe not loaded or no autoloader?
Class MyExt\MyExt\Controller\UserController does not exist", as error.

I already tried to add plugin.tx_myext.callDefaultActionIfActionCantBeResolved = 1 to the setup.ts and load the other controllers in the initializeAction, but nothing worked so far.

I appreciate all help in advance and wish everyone a nice day!

答:
Did you tried to clear the cache manually?
Also you need to specify your controller in the composer.json at the section autoload.

After that you can you can dump the autoload classes in the install tool or with this cli command:

```<code>composer dump-autoload
</code>```

Here you can read more about it: typo3-composer

Body:
I created a simple backend module for TYPO3 (7.6.15), with help of the ExtensionBuilder. The UserController and MediaController have a createAction, showAction and listAction. The PanelController just has the showAction which is the main view of the module.

Now I want to link actions from the other controllers in the template of the showAction.
The content of the view for the PanelController.showAction (MyExt/Resources/Private/Templates/Panel/Show.html) is the following:

<f:layout name="Default" />
<f:section name="content">
  <f:flashMessages />
  <f:link.action action="create" controller="User">Create new User</f:link.action>
  <f:link.action action="create" controller="Media">Create new Media</f:link.action>
</f:section>

If clicked on one of the links, I get: "Could not analyse class: "MyExt\MyExt\Controller\UserController" maybe not loaded or no autoloader?
Class MyExt\MyExt\Controller\UserController does not exist", as error.

I already tried to add plugin.tx_myext.callDefaultActionIfActionCantBeResolved = 1 to the setup.ts and load the other controllers in the initializeAction, but nothing worked so far.

I appreciate all help in advance and wish everyone a nice day!

Body:
Did you tried to clear the cache manually?
Also you need to specify your controller in the composer.json at the section autoload.

After that you can you can dump the autoload classes in the install tool or with this cli command:

composer dump-autoload

Here you can read more about it: typo3-composer


问:
Execute code right after a fragment becomes visible for the first time
I have a fragment which shows a line chart created with MPAndroidChart. Loading the fragment takes about 200 milliseconds.

I want to improve the perceived app performance by loading the chart data data right after the fragment becomes visible.

Therefore I need to execute code right after the fragment becomes visible, but only the FIRST time it becomes visible.

I can not use onResume(), since it gets called just before the fragment is visible.

Note: I can not use an asynchrounous task, it needs to be done on the UI-thread.

答:
It can be implemented by using a static boolean variable. I used the code below to show the progress dialog only on the first time the app is launched.</p>

```<code>public class SettingsFragment extends Fragment {

    static boolean _areLecturesLoaded = true;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_settings, container, false);

        return rootView;
    }

    private class Getlimits extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = ProgressDialog.show(getActivity(), "", "Loading...", true);
            pd.setCancelable(false);
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            //your background code
            if(_areLecturesLoaded) {
                try {
                    Thread.sleep(3500);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pd.isShowing())
                pd.dismiss();
            _areLecturesLoaded = false;
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
It can be implemented by using a static boolean variable. I used the code below to show the progress dialog only on the first time the app is launched.

public class SettingsFragment extends Fragment {

    static boolean _areLecturesLoaded = true;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_settings, container, false);

        return rootView;
    }

    private class Getlimits extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = ProgressDialog.show(getActivity(), "", "Loading...", true);
            pd.setCancelable(false);
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            //your background code
            if(_areLecturesLoaded) {
                try {
                    Thread.sleep(3500);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pd.isShowing())
                pd.dismiss();
            _areLecturesLoaded = false;
        }
    }
}


问:
Ionic 3 CLI unable to start project behind proxy
I'm new to Ionic. I'm facing proxy issues while getting started with Ionic 3.

After installing Ionic & cordova via npm tried to create a new project with the below command as suggested by ionic help

```<code>npm install -g @ionic/cli-plugin-proxy
</code>```

followed by

```<code>ionic start helloWorld blank --type ionic-angular
</code>```

Error: getaddrinfo ENOTFOUND github.com github.com:443

npm config and git config are already set and working since i work with angular behind proxy able to install any libraries and push to github without any issues

npm config set proxy http://userid:password@proxy.server.com:port

npm config set https-proxy  http://userid:password@proxy.server.com:port

npm config set http-proxy  http://userid:password@proxy.server.com:port

git config --global http.proxy
http://proxyuser:proxypwd@proxy.server.com:8080

Having environment variables HTTP_PROX,PROXY and IONIC_HTTP_PROXY as well.

Tried uninstalling ionic and reinstall, set proxies again but nothing helps. Couldn't find any help.Do i need to set any other proxy to work with ionic 3 ?
Kindly guide me in resolving this.

versions

Node : 7.8.0

npm : 4.0.3

ionic : 3.1.2

cordova : 7.0.1

答:
Issue is fixed after updating to latest CLI 3.3.0

global packages:

```<code>@ionic/cli-plugin-proxy : 1.3.0
@ionic/cli-utils        : 1.3.0
Ionic CLI               : 3.3.0
</code>```

System:

```<code>Node       : v6.10.3
OS         : Windows 7
Xcode      : not installed
ios-deploy : not installed
ios-sim    : not installed
</code>```

Body:
I'm new to Ionic. I'm facing proxy issues while getting started with Ionic 3.

After installing Ionic & cordova via npm tried to create a new project with the below command as suggested by ionic help

npm install -g @ionic/cli-plugin-proxy

followed by

ionic start helloWorld blank --type ionic-angular

Error: getaddrinfo ENOTFOUND github.com github.com:443

npm config and git config are already set and working since i work with angular behind proxy able to install any libraries and push to github without any issues

npm config set proxy http://userid:password@proxy.server.com:port

npm config set https-proxy  http://userid:password@proxy.server.com:port

npm config set http-proxy  http://userid:password@proxy.server.com:port

git config --global http.proxy
http://proxyuser:proxypwd@proxy.server.com:8080

Having environment variables HTTP_PROX,PROXY and IONIC_HTTP_PROXY as well.

Tried uninstalling ionic and reinstall, set proxies again but nothing helps. Couldn't find any help.Do i need to set any other proxy to work with ionic 3 ?
Kindly guide me in resolving this.

versions

Node : 7.8.0

npm : 4.0.3

ionic : 3.1.2

cordova : 7.0.1

Body:
Issue is fixed after updating to latest CLI 3.3.0

global packages:

@ionic/cli-plugin-proxy : 1.3.0
@ionic/cli-utils        : 1.3.0
Ionic CLI               : 3.3.0

System:

Node       : v6.10.3
OS         : Windows 7
Xcode      : not installed
ios-deploy : not installed
ios-sim    : not installed