问:
Haml breaking. Illegal nesting: content can't be both given on the same line
I am still unclear about why this breaks:

```<code>.form-box
      %h3 Restrictions
      %legend Restricted Locations
        = form_for [:blueadmin, :wine, @wine], html: {class: 'form-horizontal col-lg-2'} do |f|
          %fieldset.inputs
            .control-group
              = f.label :us_states, "US States", class: 'control-label'
              .controls
                = f.collection_select :product, Restriction.all, :us_state, :us_state, {}, :multiple => 'true'
          %fieldset
            %ol
              %li.button
                = f.submit "Submit", class: 'btn btn-primary'
      %table.table.table-hover.table-condensed.story-list
        %th State
        %th Remove
</code>```

The error I get is:
Illegal nesting: content can't be both given on the same line as %legend and nested within it.

the = form_for seems to be the culprit

I understand Restricted Location is on the same line as %legend... but that's how I see the docs.

This works though, but it screws up my legend border:

```<code>  .form-box
      %h3 Restrictions
      %legend
        Restricted Locations
        = form_for [:blueadmin, :wine, @wine], html: {class: 'form-horizontal col-lg-2'} do |f|
          %fieldset.inputs
            .control-group
              = f.label :us_states, "US States", class: 'control-label'
              .controls
                = f.collection_select :product, Restriction.all, :us_state, :us_state, {}, :multiple => 'true'
          %fieldset
            %ol
              %li.button
                = f.submit "Submit", class: 'btn btn-primary'
    %table.table.table-hover.table-condensed.story-list
      %th State
      %th Remove
</code>```

It looks like this:

instead of this:

(notice how the thin line is in a different spot)

Lastly, how do I get the table on the bottom to appear to the right of the form and not underneath? How can I use columns to do this?

答:
You need to move the form out of %legend tag.

Change the code to this:

```<code>.form-box
  %h3 Restrictions
  %legend
    Restricted Locations
  = form_for [:blueadmin, :wine, @wine], html: {class: 'form-horizontal col-lg-2'} do |f|
    %fieldset.inputs
      .control-group
        = f.label :us_states, "US States", class: 'control-label'
        .controls
          = f.collection_select :product, Restriction.all, :us_state, :us_state, {}, :multiple => 'true'
    %fieldset
      %ol
        %li.button
          = f.submit "Submit", class: 'btn btn-primary'
  %table.table.table-hover.table-condensed.story-list
    %th State
    %th Remove
</code>```

Use inline content only if you have single element to nest. In your case you are trying to nest  Restricted Locations text as well as form

Note: HAML works on indentation so any changes in indentation results in different html code or syntax error

Body:
I am still unclear about why this breaks:

.form-box
      %h3 Restrictions
      %legend Restricted Locations
        = form_for [:blueadmin, :wine, @wine], html: {class: 'form-horizontal col-lg-2'} do |f|
          %fieldset.inputs
            .control-group
              = f.label :us_states, "US States", class: 'control-label'
              .controls
                = f.collection_select :product, Restriction.all, :us_state, :us_state, {}, :multiple => 'true'
          %fieldset
            %ol
              %li.button
                = f.submit "Submit", class: 'btn btn-primary'
      %table.table.table-hover.table-condensed.story-list
        %th State
        %th Remove

The error I get is:
Illegal nesting: content can't be both given on the same line as %legend and nested within it.

the = form_for seems to be the culprit

I understand Restricted Location is on the same line as %legend... but that's how I see the docs.

This works though, but it screws up my legend border:

  .form-box
      %h3 Restrictions
      %legend
        Restricted Locations
        = form_for [:blueadmin, :wine, @wine], html: {class: 'form-horizontal col-lg-2'} do |f|
          %fieldset.inputs
            .control-group
              = f.label :us_states, "US States", class: 'control-label'
              .controls
                = f.collection_select :product, Restriction.all, :us_state, :us_state, {}, :multiple => 'true'
          %fieldset
            %ol
              %li.button
                = f.submit "Submit", class: 'btn btn-primary'
    %table.table.table-hover.table-condensed.story-list
      %th State
      %th Remove

It looks like this:

instead of this:

(notice how the thin line is in a different spot)

Lastly, how do I get the table on the bottom to appear to the right of the form and not underneath? How can I use columns to do this?

Body:
You need to move the form out of %legend tag.

Change the code to this:

.form-box
  %h3 Restrictions
  %legend
    Restricted Locations
  = form_for [:blueadmin, :wine, @wine], html: {class: 'form-horizontal col-lg-2'} do |f|
    %fieldset.inputs
      .control-group
        = f.label :us_states, "US States", class: 'control-label'
        .controls
          = f.collection_select :product, Restriction.all, :us_state, :us_state, {}, :multiple => 'true'
    %fieldset
      %ol
        %li.button
          = f.submit "Submit", class: 'btn btn-primary'
  %table.table.table-hover.table-condensed.story-list
    %th State
    %th Remove

Use inline content only if you have single element to nest. In your case you are trying to nest  Restricted Locations text as well as form

Note: HAML works on indentation so any changes in indentation results in different html code or syntax error


来源: stackexchange

问:
SQL Server 2016 For JSON return name
I have a stored procedure with a simple select statement in which I return json:

```<code>SELECT A, B, C
FROM 123
FOR JSON AUTO
</code>```

This works fine. However, the name of the result, if I call the stored procedure, is something like: JSON_F52E2B61-18A1-11d1-B105-00805F49916B

How can I specify the name of the return value?

Thanks!

答:
You could call is as a subquery and alias it like so:

```<code>create table t (a int, b varchar(32), c varchar(32));
insert into t values (123, 'do re mi','fa so la' );
select (select a, b, c from t for json auto) as MyJson;
</code>```

dbfiddle.uk: http://dbfiddle.uk/?rdbms=sqlserver_2016&fiddle=2fc249147c9780fbd4d0ab307740b029

returns:

```<code>MyJson
[{"a":123,"b":"do re mi","c":"fa so la"}]
</code>```

ContentLicense: CC BY-SA 3.0

Title: SQL Server 2016 For JSON return name

Body:
I have a stored procedure with a simple select statement in which I return json:

SELECT A, B, C
FROM 123
FOR JSON AUTO

This works fine. However, the name of the result, if I call the stored procedure, is something like: JSON_F52E2B61-18A1-11d1-B105-00805F49916B

How can I specify the name of the return value?

Thanks!

Body:
You could call is as a subquery and alias it like so:

create table t (a int, b varchar(32), c varchar(32));
insert into t values (123, 'do re mi','fa so la' );
select (select a, b, c from t for json auto) as MyJson;

dbfiddle.uk: http://dbfiddle.uk/?rdbms=sqlserver_2016&fiddle=2fc249147c9780fbd4d0ab307740b029

returns:

MyJson
[{"a":123,"b":"do re mi","c":"fa so la"}]


问:
Sql Server Schema Compare Wrong
I did a schema compare using visual studio 2017.  The source was my production DB and the target was the repo.  The tool incorrectly told me I had to add a procedure that already existed (see image).  Has it lost sync somehow?  How can I fix it?

答:
If you right click the 'add' file you should get an 'ignore this local item' option.  Go with that.  Another way is to allow the add (like I did above) and just delete the duplicate proc.  After syncing with master repo everything was OK.

I still don't know the root cause, but this did happen after a long time without syncing, so, perhaps syncing the repo more often will prevent this from happening.

Title: Sql Server Schema Compare Wrong


问:
Regex to match strings with substring "/status" unless it contains "subscription/status"
I know how to match strings that end with "/status": ^.*status$.

However, I don't want this to apply to strings that end in "subscription/status".

Your help is much appreciated!

EDIT: I'm using a Javascript library to execute a mongoDB query. This is what I have so far:

```<code>const query = {
  "handler_url_str": {
    "$regex": "^.*status$"
  }
};
</code>```

Unfortunately, this matches all documents that end in "/status".

答:
Solution

```<code>"$regex": "^.*(?<!subscription)\/status$"
</code>```

Explanation

^.* - start with zero or more characters

Followed by

(?<!subscription)\/status - /status not preceded by subscription

$ - end of pattern

Body:
I know how to match strings that end with "/status": ^.*status$.

However, I don't want this to apply to strings that end in "subscription/status".

Your help is much appreciated!

EDIT: I'm using a Javascript library to execute a mongoDB query. This is what I have so far:

const query = {
  "handler_url_str": {
    "$regex": "^.*status$"
  }
};

Unfortunately, this matches all documents that end in "/status".

Body:
Solution

"$regex": "^.*(?<!subscription)\/status$"

Explanation

^.* - start with zero or more characters

Followed by

(?<!subscription)\/status - /status not preceded by subscription

$ - end of pattern


问:
Kendo Barcode - How to resize with script
I have a Barcode that is within a partial view.  If I do not include a width and height at the beginning I get an error when rendering.

@Html.Kendo().Barcode().Name("barcode-" + Guid.NewGuid().ToString()).Value(@Model.WidgetTagValue).Encoding(Model.barcode_symbology).Width(150).Height(150)```
</div>
</div>
</p>

<p>I have a resize event that tries to change it to fit the size of the parent div on page init and on window resize.</p>

<pre class="lang-js prettyprint-override"><code>function setBarcodeSize() {
        if ($('.k-barcode').length > 0) {
            $('.k-barcode').each(function () {
                var parentDivWidth = $(this).closest(".andon-widget-container").width() - 50;
                var parentDivHeight = $(this).closest(".andon-widget-container").height() - $(this).closest(".andon-widget-container").find(".andon-widget-title").height();
                $(this).css("width", $(this).width(parentDivWidth) + "px").css("height", $(this).height(parentDivHeight) + "px");
                $(this).data("kendoBarcode").redraw();
            });
        }
    }
</code>```

The width and height of the k-barcode  are set appropriately but the size of the child  with the data-role="surface" remains at 150x150

Advice?

答:
Looks like api documentation lied about it. You have to set dimentions by setOptions() method to make resize/redraw work. jQuery css() method doesn't work.

```<code>var barcode = $("#barcode").data("kendoBarcode");
barcode.setOptions({width: 600});
barcode.resize();
</code>```

Example: http://dojo.telerik.com/AgENi

Body:
I have a Barcode that is within a partial view.  If I do not include a width and height at the beginning I get an error when rendering.

@Html.Kendo().Barcode().Name("barcode-" + Guid.NewGuid().ToString()).Value(@Model.WidgetTagValue).Encoding(Model.barcode_symbology).Width(150).Height(150)

I have a resize event that tries to change it to fit the size of the parent div on page init and on window resize.

function setBarcodeSize() {
        if ($('.k-barcode').length > 0) {
            $('.k-barcode').each(function () {
                var parentDivWidth = $(this).closest(".andon-widget-container").width() - 50;
                var parentDivHeight = $(this).closest(".andon-widget-container").height() - $(this).closest(".andon-widget-container").find(".andon-widget-title").height();
                $(this).css("width", $(this).width(parentDivWidth) + "px").css("height", $(this).height(parentDivHeight) + "px");
                $(this).data("kendoBarcode").redraw();
            });
        }
    }

The width and height of the k-barcode  are set appropriately but the size of the child  with the data-role="surface" remains at 150x150

Advice?

Body:
Looks like api documentation lied about it. You have to set dimentions by setOptions() method to make resize/redraw work. jQuery css() method doesn't work.

var barcode = $("#barcode").data("kendoBarcode");
barcode.setOptions({width: 600});
barcode.resize();

Example: http://dojo.telerik.com/AgENi


问:
Improving a long if-else statement in bash
Is there a way to write a more elegant code which considers multiple possible combinations than writing a lengthy if-else statement?

I have randomly generated data sets like the ones below but some of the rows can be null sometimes.

{

semester1 grade1 final_grade1

semester1a grade1a final_grade1a

}

{

semester2 grade2 final_grade2

semester2a grade2a final_grade2a

}

I have already written code for all the possible logical combinations of my data:

```<code>if [[ -n $semester1 && -z $semester1a && -z $semester2 && -z $semester2a ]]; then
echo "Section 1:$semester1=$grade1, final grade for $semester1=$final_grade1 ."

elif [[ -n $semester1 && -n $semester1a && -z $semester2 && -z $semester2a ]]; then
echo "Section 1:$semester1=$grade1, $semester1a=$grade1a, final grade for $semester1=$final_grade1, final grade for $semester1a=$final_grade1a."

elif [[ -n $semester1 && -n $semester1a && -n $semester2 && -z $semester2a ]]; then
echo "Section 1:$semester1=$grade1, $semester1a=$grade1a, final grade for $semester1=$final_grade1, final grade for $semester1a=$final_grade1a."
echo "Section 2:$semester2=$grade2, final grade for $semester2=$final_grade2 ."

elif [[ -n $semester2 && -z $semester2a && -z $semester1 && -z $semester1a ]]; then
echo "Section 2:$semester2=$grade2, final grade for $semester2=$final_grade2 ."

elif [[ -n $semester2 && -n $semester2a && -z $semester1 && -z $semester1a ]]; then
echo "Section 2:$semester2=$grade2, $semester2a=$grade2a, final grade for $semester2=$final_grade2, final grade for $semester2a=$final_grade2a, ."

elif [[ -n $semester2 && -n $semester2a && -n $semester1 && -z $semester1a ]]; then
echo "Section 1:$semester1=$grade1, final grade for $semester1=$final_grade1 ."
echo "Section 2:$semester2=$grade2, $semester2a=$grade2a, final grade for $semester2=$final_grade2, final grade for $semester2a=$final_grade2a, ."

elif [[ -n $semester2 && -n $semester2a && -n $semester1 && -n $semester1a ]]; then
echo "Section 1:$semester1=$grade1, $semester1a=$grade1a, final grade for $semester1=$final_grade1, final grade for $semester1a=$final_grade1a, ."
echo "Section 2:$semester2=$grade2, $semester2a=$grade2a, final grade for $semester2=$final_grade2, final grade for $semester2a=$final_grade2a, ."

fi
</code>```

Is there a better way for checking this?

答:
If you aren't doing calculations; I would just assign a default value to undefined variables ("n/a" perhaps?)

```<code>: ${semester1:=n/a} ${semester1a:=n/a} ${semester2:=n/a} ${semester2a:=n/a}
: ${grade1:=n/a} ${grade1a:=n/a} ${grade2:=n/a} ${grade2a:=n/a}
: ${final_grade1:=n/a} ${final_grade1a:=n/a} ${final_grade2:=n/a} ${final_grade2a:=n/a}
echo "Section 1:$semester1=$grade1, $semester1a=$grade1a, final grade for $semester1=$final_grade1, final grade for $semester1a=$final_grade1a, ."
echo "Section 2:$semester2=$grade2, $semester2a=$grade2a, final grade for $semester2=$final_grade2, final grade for $semester2a=$final_grade2a, ."
</code>```

This task cries out, though, for data structures like lists and dicts/hashes/maps that bash is sorely lacking in.

Body:
Is there a way to write a more elegant code which considers multiple possible combinations than writing a lengthy if-else statement?

I have randomly generated data sets like the ones below but some of the rows can be null sometimes.

{

semester1 grade1 final_grade1

semester1a grade1a final_grade1a

}

{

semester2 grade2 final_grade2

semester2a grade2a final_grade2a

}

I have already written code for all the possible logical combinations of my data:

if [[ -n $semester1 && -z $semester1a && -z $semester2 && -z $semester2a ]]; then
echo "Section 1:$semester1=$grade1, final grade for $semester1=$final_grade1 ."

elif [[ -n $semester1 && -n $semester1a && -z $semester2 && -z $semester2a ]]; then
echo "Section 1:$semester1=$grade1, $semester1a=$grade1a, final grade for $semester1=$final_grade1, final grade for $semester1a=$final_grade1a."

elif [[ -n $semester1 && -n $semester1a && -n $semester2 && -z $semester2a ]]; then
echo "Section 1:$semester1=$grade1, $semester1a=$grade1a, final grade for $semester1=$final_grade1, final grade for $semester1a=$final_grade1a."
echo "Section 2:$semester2=$grade2, final grade for $semester2=$final_grade2 ."

elif [[ -n $semester2 && -z $semester2a && -z $semester1 && -z $semester1a ]]; then
echo "Section 2:$semester2=$grade2, final grade for $semester2=$final_grade2 ."

elif [[ -n $semester2 && -n $semester2a && -z $semester1 && -z $semester1a ]]; then
echo "Section 2:$semester2=$grade2, $semester2a=$grade2a, final grade for $semester2=$final_grade2, final grade for $semester2a=$final_grade2a, ."

elif [[ -n $semester2 && -n $semester2a && -n $semester1 && -z $semester1a ]]; then
echo "Section 1:$semester1=$grade1, final grade for $semester1=$final_grade1 ."
echo "Section 2:$semester2=$grade2, $semester2a=$grade2a, final grade for $semester2=$final_grade2, final grade for $semester2a=$final_grade2a, ."

elif [[ -n $semester2 && -n $semester2a && -n $semester1 && -n $semester1a ]]; then
echo "Section 1:$semester1=$grade1, $semester1a=$grade1a, final grade for $semester1=$final_grade1, final grade for $semester1a=$final_grade1a, ."
echo "Section 2:$semester2=$grade2, $semester2a=$grade2a, final grade for $semester2=$final_grade2, final grade for $semester2a=$final_grade2a, ."

fi

Is there a better way for checking this?

Body:
If you aren't doing calculations; I would just assign a default value to undefined variables ("n/a" perhaps?)

: ${semester1:=n/a} ${semester1a:=n/a} ${semester2:=n/a} ${semester2a:=n/a}
: ${grade1:=n/a} ${grade1a:=n/a} ${grade2:=n/a} ${grade2a:=n/a}
: ${final_grade1:=n/a} ${final_grade1a:=n/a} ${final_grade2:=n/a} ${final_grade2a:=n/a}
echo "Section 1:$semester1=$grade1, $semester1a=$grade1a, final grade for $semester1=$final_grade1, final grade for $semester1a=$final_grade1a, ."
echo "Section 2:$semester2=$grade2, $semester2a=$grade2a, final grade for $semester2=$final_grade2, final grade for $semester2a=$final_grade2a, ."

This task cries out, though, for data structures like lists and dicts/hashes/maps that bash is sorely lacking in.


问:
MS Access Having Clause
Alright so I understand the point of the HAVING clause. I am having an issue and I am wondering if I can solve this the way I want to.

I want to execute one query using ADODB.Recordset and then use the Filter function to sift through the data set.

The problem is the query at the moment which looks like this:

```<code>SELECT tblMT.Folder, tblMT.MTDATE, tblMT.Cust, Sum(tblMT.Hours)
FROM tblMT
GROUP BY tblMT.Folder, tblMT.MTDATE, tblMT.Cust
HAVING tblMT.Cust LIKE "TEST*" AND Min(tblMT.MTDATE)>=Date()-30 AND MAX(tblMT.MTDATE)<=Date()
ORDER BY tblMT.TheDATE DESC;
</code>```

So the above works as expected.... however I want to be able to use the tblMT.Cust as the filter without having to keep re querying the database. If I remove it I get a:

Data type mismatch in criteria expression.

Is what I am trying to do possible? If someone can point me in the right direction here would be great.

答:
Ok... the type mismatch is caused because either tblmt.mtdate isn't a date field or tblmt.hours isn't a number field AND you have data that either isn't a date or isn't a number when the customer isn't like 'TEST*'.  Or, for some customers, you have a NULL in mt.date and null can't be compared with >=. you'd still get the error if you said where tblMt.cust not like "TEST*" too.

Problem is likely with the data or your expectation and you need to handle it.

What data types are tblMT.hours and tblMt.MtDate?

Title: MS Access Having Clause

Body:
Alright so I understand the point of the HAVING clause. I am having an issue and I am wondering if I can solve this the way I want to.

I want to execute one query using ADODB.Recordset and then use the Filter function to sift through the data set.

The problem is the query at the moment which looks like this:

SELECT tblMT.Folder, tblMT.MTDATE, tblMT.Cust, Sum(tblMT.Hours)
FROM tblMT
GROUP BY tblMT.Folder, tblMT.MTDATE, tblMT.Cust
HAVING tblMT.Cust LIKE "TEST*" AND Min(tblMT.MTDATE)>=Date()-30 AND MAX(tblMT.MTDATE)<=Date()
ORDER BY tblMT.TheDATE DESC;

So the above works as expected.... however I want to be able to use the tblMT.Cust as the filter without having to keep re querying the database. If I remove it I get a:

Data type mismatch in criteria expression.

Is what I am trying to do possible? If someone can point me in the right direction here would be great.


问:
Javascript variable not changing inside setInterval() function?
The variable counter does not change for some reason, it stays its initial value, of 50. It's a global variable, that is tried to be changed inside a function called by setInterval().

```<code>var mode = false;
var counter = 50;
var interval = null;
var increment = false;
var MAX = 50;
var MIN = 0;
var INTERVAL_MS = 3000;

setInterval(doInterval, INTERVAL_MS);

function doInterval() {
    if(increment)
    {
        counter += 1;
    }
    else
    {
        console.log("Decrement, " + counter);
        counter -= 1;
    }

    // Set direction
    if(counter = MIN)
    {
        increment = true;
    }
    else if(counter = MAX)
    {
        increment = false;
    }

    console.log("set to " + counter + " (D) Increment next time? " + increment);

    // dosomething with the values
}
</code>```

The output from this code

decrement, 50

set to 50 (D) Increment next time? false

decrement, 50

set to 50 (D) Increment next time? false

decrement, 50

set to 50 (D) Increment next time? false

And so on

Since it's 50 and increment is false, it should become 49, 48, however it seems that I can't change the variable's value. What could be a reason? The code is run inside a NodeJS app.

答:
= is for assignment and == is equality check (=== for strict check). Please use equality check to fix your code.</p>

```<code>// Set direction
    if(counter == MIN)
    {
        increment = true;
    }
    else if(counter == MAX)
    {
        increment = false;
    }
</code>```

Body:
The variable counter does not change for some reason, it stays its initial value, of 50. It's a global variable, that is tried to be changed inside a function called by setInterval().

var mode = false;
var counter = 50;
var interval = null;
var increment = false;
var MAX = 50;
var MIN = 0;
var INTERVAL_MS = 3000;

setInterval(doInterval, INTERVAL_MS);

function doInterval() {
    if(increment)
    {
        counter += 1;
    }
    else
    {
        console.log("Decrement, " + counter);
        counter -= 1;
    }

    // Set direction
    if(counter = MIN)
    {
        increment = true;
    }
    else if(counter = MAX)
    {
        increment = false;
    }

    console.log("set to " + counter + " (D) Increment next time? " + increment);

    // dosomething with the values
}

The output from this code

decrement, 50

set to 50 (D) Increment next time? false

decrement, 50

set to 50 (D) Increment next time? false

decrement, 50

set to 50 (D) Increment next time? false

And so on

Since it's 50 and increment is false, it should become 49, 48, however it seems that I can't change the variable's value. What could be a reason? The code is run inside a NodeJS app.

Body:
= is for assignment and == is equality check (=== for strict check). Please use equality check to fix your code.

// Set direction
    if(counter == MIN)
    {
        increment = true;
    }
    else if(counter == MAX)
    {
        increment = false;
    }


问:
Shopify Liquid finding out date of a specific day of the week
Wondering if someone could help with a question on Liquid / Shopify. I am working with a store that delivers product every Thursday, provided you order by Tuesday 12pm of the same week.

In the notification to the customer, I needed to indicate which Thursday it will ship i.e. 'This' or 'Next' based on order date. I have accomplished that with the following logic in liquid:

```<code>{% if  date | date: "%A" == 'Tuesday' and date | date: "%k" > 12 %}
   Your order will be delivered on Thursday of next week.
{% elsif date | date: "%A" == 'Wednesday' or date | date: "%A" == 'Thursday' %}
    Your order will be delivered on Thursday of next week.
{% else %}
    Your order will be delivered this Thursday
{% endif %}
</code>```

Above does the job for the moment. However, I've been tasked to actually publish the 'date' of the Thursday of delivery. I've racked my brains and tried to figure out a way where I can write a function in liquid to tell me what 'This' Thursdays date is and what 'Next' Thursdays date will be. But I'm coming up trumps. I know how to do this in PHP and Ruby using the inbuilt functions but I'm new to Liquid and don't think it has inbuilt functions because it's a markup language (. So I would think you'd have to do some unix time math, but that makes it really complex.

Is there another way, or do I have to resort to using some convoluted unix timestamp math?

Thanks.

答:
You will be required to make some unix calculations, but they will be simple ones.

See the code below:

```<code>{% assign today = 'now' | date: '%s' %}
{% assign single_day = 86400 %}
{% assign today_number = 'now' | date: '%u' | plus: 0 %}

{% if  today_number < 2 %}

    Delivery by {{ today | plus: single_day | date: '%Y/%m/%d' }}

{% else %}

    {% assign days_until_next = 9 | minus: today_number  %}
    {% assign days_unix = days_until_next | times: single_day  %}
    Delivery by {{ today | plus: days_unix  | date: '%Y/%m/%d' }}

{% endif %}
</code>```

I will try to break it down.

Assigning reusable data

{% assign today = 'now' | date: '%s' %} - with this we are getting the current unix timestamp for the server date

{% assign single_day = 86400 %} - this is the number that defines a single day in unix timestamp

{% assign today_number = 'now' | date: '%u' | plus: 0 %} - this returns the current day as a number (1...7). The plus: 0 is to convert it to a number instead of a string.

Condition

{% if  today_number < 2 %} - we are checking if today_number is smaller than 2 ( where 2 is Tuesday ), it can be written in this case like so as well {% if  today_number == 1 %}, but you get the logic

Output

If the above condition is true we do this:

{{ today | plus: single_day | date: '%Y/%m/%d' }} - this sums the timestamp today and the single_day timestamp, giving us the date tomorrow

If the if statement return false we go in the {% else %} statement where we set a few variables.

{% assign days_until_next = 9 | minus: today_number  %} - since we are counting from the 2nd day I'm using the number 9 as a base and substract the current today_number so for example if today is Tuesday, we have 2 and 9-2=7, so this means the next Tuesday is 7 days from now.

{% assign days_unix = days_until_next | times: single_day  %} - this just calculates the single day unix number times the days until the next Tuesday. So if we continue the above Tuesday example you get 86400*7=604800

{{ today | plus: days_unix  | date: '%Y/%m/%d' }} - finally we sum the today unix number with the unix number for the days until the next Tuesday and we convert it to a readable date.

Hope that this is simple enough to follow.

Have a great day!

Body:
Wondering if someone could help with a question on Liquid / Shopify. I am working with a store that delivers product every Thursday, provided you order by Tuesday 12pm of the same week.

In the notification to the customer, I needed to indicate which Thursday it will ship i.e. 'This' or 'Next' based on order date. I have accomplished that with the following logic in liquid:

{% if  date | date: "%A" == 'Tuesday' and date | date: "%k" > 12 %}
   Your order will be delivered on Thursday of next week.
{% elsif date | date: "%A" == 'Wednesday' or date | date: "%A" == 'Thursday' %}
    Your order will be delivered on Thursday of next week.
{% else %}
    Your order will be delivered this Thursday
{% endif %}

Above does the job for the moment. However, I've been tasked to actually publish the 'date' of the Thursday of delivery. I've racked my brains and tried to figure out a way where I can write a function in liquid to tell me what 'This' Thursdays date is and what 'Next' Thursdays date will be. But I'm coming up trumps. I know how to do this in PHP and Ruby using the inbuilt functions but I'm new to Liquid and don't think it has inbuilt functions because it's a markup language (. So I would think you'd have to do some unix time math, but that makes it really complex.

Is there another way, or do I have to resort to using some convoluted unix timestamp math?

Thanks.

Body:
You will be required to make some unix calculations, but they will be simple ones.

See the code below:

{% assign today = 'now' | date: '%s' %}
{% assign single_day = 86400 %}
{% assign today_number = 'now' | date: '%u' | plus: 0 %}

{% if  today_number < 2 %}

    Delivery by {{ today | plus: single_day | date: '%Y/%m/%d' }}

{% else %}

    {% assign days_until_next = 9 | minus: today_number  %}
    {% assign days_unix = days_until_next | times: single_day  %}
    Delivery by {{ today | plus: days_unix  | date: '%Y/%m/%d' }}

{% endif %}

I will try to break it down.

Assigning reusable data

{% assign today = 'now' | date: '%s' %} - with this we are getting the current unix timestamp for the server date

{% assign single_day = 86400 %} - this is the number that defines a single day in unix timestamp

{% assign today_number = 'now' | date: '%u' | plus: 0 %} - this returns the current day as a number (1...7). The plus: 0 is to convert it to a number instead of a string.

Condition

{% if  today_number < 2 %} - we are checking if today_number is smaller than 2 ( where 2 is Tuesday ), it can be written in this case like so as well {% if  today_number == 1 %}, but you get the logic

Output

If the above condition is true we do this:

{{ today | plus: single_day | date: '%Y/%m/%d' }} - this sums the timestamp today and the single_day timestamp, giving us the date tomorrow

If the if statement return false we go in the {% else %} statement where we set a few variables.

{% assign days_until_next = 9 | minus: today_number  %} - since we are counting from the 2nd day I'm using the number 9 as a base and substract the current today_number so for example if today is Tuesday, we have 2 and 9-2=7, so this means the next Tuesday is 7 days from now.

{% assign days_unix = days_until_next | times: single_day  %} - this just calculates the single day unix number times the days until the next Tuesday. So if we continue the above Tuesday example you get 86400*7=604800

{{ today | plus: days_unix  | date: '%Y/%m/%d' }} - finally we sum the today unix number with the unix number for the days until the next Tuesday and we convert it to a readable date.

Hope that this is simple enough to follow.

Have a great day!


问:
How do I find a word in a string using RegEx and C#?
I cannot seem to find solution to find a certain word from a string.

Example:
Searching: Hi

From: Laughing

using String.Contains or Regex.IsMatch returning true value. I need something to find inside string but not part of word.

Testing using String.Contains() or Regex.ISMatch()

```<code>("Hi", "Laughing") return true  //It should return false
</code>```

What I would like returned is this:

```<code>("Hi","Hi!") or ("Say Hi!") //this is what i want exactly
</code>```

Second test

答:
```<code>    var pattern = @"\bHi\b";
    var phrase = "Hi, John!";
    var phrase2 = "Hello Philip!";
    Console.WriteLine(Regex.IsMatch(phrase, pattern));
    Console.WriteLine(Regex.IsMatch(phrase2, pattern));
</code>```

Body:
I cannot seem to find solution to find a certain word from a string.

Example:
Searching: Hi

From: Laughing

using String.Contains or Regex.IsMatch returning true value. I need something to find inside string but not part of word.

Testing using String.Contains() or Regex.ISMatch()

("Hi", "Laughing") return true  //It should return false

What I would like returned is this:

("Hi","Hi!") or ("Say Hi!") //this is what i want exactly

Second test


问:
Passing specified parameters in route file to the controller in laravel
In laravel routes file I have written this :

```<code>Route::get('/{lang}/{page}', 'PagesController@get' )->where('lang' , $langPattern );
</code>```

and in pages controller I wrote this :

```<code>public function get($lang,$page)
{
     // do something
}
</code>```

But I want only to use page parameter

I created a middleware to select language and there is no need for $lang in controllers

How can I remove it ?

Can I write like this :

```<code>public function get($page)
{
     // do something
}
</code>```

My language middleware :

```<code>public function handle($request, Closure $next )
{
    // URL language
    $urllang = $request->segment(1);

    if ($request->session()->has("lang")){
        $sessionLang = $request->session()->get('lang');

        // if requested url hasn't language
        if ($urllang == NULL) {
            $urllang = $sessionLang;
            return redirect('/' . $sessionLang);
        }

        // if user change the language
        elseif ($urllang != NULL && $urllang != $sessionLang) {
            $request->session()->put('lang' , $urllang);
        }
    }
    else{
        // if there is no session lang and no url lang
        // get app main lang from config file
        // Put session and redirect
        if ($urllang == NULL) {
            $request->session()->put('lang' , config('app.locale'));
            return redirect('/' . config('app.locale'));
        }
        // if there is no session
        // Only put session
        else{
            $request->session()->put('lang' , $urllang);
        }
    }

    // get requested language id from database
    $lang = Lang::select("id" , "short" , "name" , "title" , "keywords" , "description" , "copyrights" , "site_name")->where( ['short' => $urllang , 'active' => 1 ])->first();
    // if requested language is not exist
    if (!$lang) {
        $request->session()->put('lang' , config('app.locale'));
        abort(404);
    }else{
        Lang::set($lang);
        return $next($request);
    }

}
</code>```

Thanks .

答:
Finally i found the best solution
Just i added to my language middleware this line

```<code>$request->route()->forgetParameter('lang');
</code>```

I asked it to remove lang parameter from request variable .

Hope to help you .

Body:
In laravel routes file I have written this :

Route::get('/{lang}/{page}', 'PagesController@get' )->where('lang' , $langPattern );

and in pages controller I wrote this :

public function get($lang,$page)
{
     // do something
}

But I want only to use page parameter

I created a middleware to select language and there is no need for $lang in controllers

How can I remove it ?

Can I write like this :

public function get($page)
{
     // do something
}

My language middleware :

public function handle($request, Closure $next )
{
    // URL language
    $urllang = $request->segment(1);

    if ($request->session()->has("lang")){
        $sessionLang = $request->session()->get('lang');

        // if requested url hasn't language
        if ($urllang == NULL) {
            $urllang = $sessionLang;
            return redirect('/' . $sessionLang);
        }

        // if user change the language
        elseif ($urllang != NULL && $urllang != $sessionLang) {
            $request->session()->put('lang' , $urllang);
        }
    }
    else{
        // if there is no session lang and no url lang
        // get app main lang from config file
        // Put session and redirect
        if ($urllang == NULL) {
            $request->session()->put('lang' , config('app.locale'));
            return redirect('/' . config('app.locale'));
        }
        // if there is no session
        // Only put session
        else{
            $request->session()->put('lang' , $urllang);
        }
    }

    // get requested language id from database
    $lang = Lang::select("id" , "short" , "name" , "title" , "keywords" , "description" , "copyrights" , "site_name")->where( ['short' => $urllang , 'active' => 1 ])->first();
    // if requested language is not exist
    if (!$lang) {
        $request->session()->put('lang' , config('app.locale'));
        abort(404);
    }else{
        Lang::set($lang);
        return $next($request);
    }

}

Thanks .

Body:
Finally i found the best solution
Just i added to my language middleware this line

$request->route()->forgetParameter('lang');

I asked it to remove lang parameter from request variable .

Hope to help you .


问:
Javascript Find User
I have the below javascript to get the UserID from a online form. This script will go through IE DOM Explorer to find the valued. But when I run the script, it is totally ignoring my "If" statement. It is just providing a value for "NewAuthUserID", without considering the "if". </p>

```<code>(function () {
  var NewAuthUserID = "";
  var UserId = $('tr.background-highlight:contains("REQUESTER PROFILE") + tr').children('td:contains("User ID:")+td').text();
  if ('tr.background-highlight:contains("NEW AUTHORIZED INDIVIDUAL PROFILE:"') {
    var NewAuthUserID = $('td:contains("User ID:")+td:eq(2)').text();
  };
  alert(UserId);
  alert(NewAuthUserID)
})();
</code>```

答:
Off topic response:

The way you manage/select your nodes may require a lot of maintanance in the future and is prone to errors.

For example: tr.background-highlight:contains("REQUESTER PROFILE") + tr

In words: Get me the table-row after a table-row with hilighted background, that contains "REQUESTER PROFILE".

What if you'll have to add a row in between them? what if you'll need to select the row, wether it is hilighted or not? what if further rows will be hilighted in the future, so that this selector ain't uniqu anymore? what if the label changes? maybe even the language? ...

In each of these cases you'll have to revisit (potentially all) your jquery selectors, just because some minor layout changed.

That's not very reliable.

Will you remember that when you'll get asked to do these changes? Maybe someone else will have to do these changes, will he/she know what to look for?

Tell me, do you remember the details/implications/quirks of the work you've done a week ago? not to speak about your work from a few months ago.

Better:

Use "unique" identifier to, well, identify your nodes by their role; and I'm not talking about IDs. Unique within their specific context.

The easiest way would be to use css-classes. Annotating the rows/cells so you can select the very same field as $('.ref-requester-provile .ref-user-id')

This is way more reliable and future-proof than your bulky $('tr.background-highlight:contains("REQUESTER PROFILE") + tr').children('td:contains("User ID:")+td') where your JS needs to know every little detail of your template/markup, and needs to be adapted with every little change.

Why did I prepend these classes with ref-? to distinct them from classes that are meant for styling

If you don't need to style these nodes and need these identifyer solely to reference them in your JS, I'd rather use a data-attribute. Why? Let's sum it up with:

performance: when you need to add/remove these marker; avoid unnecessary render-cycles

A cleaner seperation between style and code: classes are primarily for styling, but we don't style here.

Title: Javascript Find User

Body:
I have the below javascript to get the UserID from a online form. This script will go through IE DOM Explorer to find the valued. But when I run the script, it is totally ignoring my "If" statement. It is just providing a value for "NewAuthUserID", without considering the "if".

(function () {
  var NewAuthUserID = "";
  var UserId = $('tr.background-highlight:contains("REQUESTER PROFILE") + tr').children('td:contains("User ID:")+td').text();
  if ('tr.background-highlight:contains("NEW AUTHORIZED INDIVIDUAL PROFILE:"') {
    var NewAuthUserID = $('td:contains("User ID:")+td:eq(2)').text();
  };
  alert(UserId);
  alert(NewAuthUserID)
})();


问:
simple way to identify the user is having the account in Gmail?
Do any one say which is the simple way to identify the user is having the account in Gmail ?</p>

答:
You cannot automatically determine whether an arbitrary user has a Gmail account.

Instead, you can ask the user:

```<code><input type="checkbox" name="HasGmail" />
<label for="HasGmail">Do you have a Gmail account?</label>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You cannot automatically determine whether an arbitrary user has a Gmail account.

Instead, you can ask the user:

<input type="checkbox" name="HasGmail" />
<label for="HasGmail">Do you have a Gmail account?</label>


问:
see if the div is present or not in geb
We are using Geb for automation. I have spinner loaded before every page gets loaded. we are using waitFor() , but it takes a long time and the scripts are getting run more than the specified time.The DOM element is

```<code>   <div classname="loader"></div>
</code>```

i tried to see if the element is present.

```<code>   if(!$(".loader").displayed== true)
   {}
</code>```

But i am getting error as ,

```<code>   geb.waiting.WaitTimeoutException: condition did not pass in 40.0 seconds (failed with exception)

at geb.waiting.Wait.waitFor(Wait.groovy:138)
at geb.waiting.DefaultWaitingSupport.doWaitFor(DefaultWaitingSupport.groovy:51)
at geb.waiting.DefaultWaitingSupport.waitFor(DefaultWaitingSupport.groovy:46)
at geb.Page.waitFor(Page.groovy:516)
at geb.Browser.methodMissing(Browser.groovy:206)
at geb.spock.GebSpec.methodMissing(GebSpec.groovy:56)
at loaderSpec(loaderSpec.groovy:415)
 Caused by: Assertion failed:

 $(".loader").displayed== false
|            |        |
  |            true     false
   [[[ChromeDriver: chrome on XP (1b3943691dd96ebaf9098b1720c87ee9)] -> css
 selector: .loader]]

at loaderSpec(loaderSpec.groovy:415)
at loaderSpec(loaderSpec.groovy:415)
at geb.waiting.Wait.waitFor(Wait.groovy:127)
... 6 more
</code>```

I am not sure how to check if the div is present or not present. If I extend the time to wait for, I am getting element not found error.

Kindly let me know your input.

答:
Are you checking that the div is visible while you are waiting for the spinner to go away?
I've had an issue exactly like this that plagued me. Here is the solution my coworkers and I came up with:</p>

```<code>try{
    waitFor(10) { element.isDisplayed() } //wait for spinner to kick in
    waitFor() { !element.isDisplayed() }  //wait for spinner to go away
} catch(WaitTimeoutException e) {
// if spinner loads & deloads faster than this code is reached
// then WTE will be caught and we dont need to handle the spinner any more

    //println(e.printStackTrace())
}
</code>```

Title: see if the div is present or not in geb

Body:
We are using Geb for automation. I have spinner loaded before every page gets loaded. we are using waitFor() , but it takes a long time and the scripts are getting run more than the specified time.The DOM element is

i tried to see if the element is present.

   if(!$(".loader").displayed== true)
   {}

But i am getting error as ,

   geb.waiting.WaitTimeoutException: condition did not pass in 40.0 seconds (failed with exception)

at geb.waiting.Wait.waitFor(Wait.groovy:138)
at geb.waiting.DefaultWaitingSupport.doWaitFor(DefaultWaitingSupport.groovy:51)
at geb.waiting.DefaultWaitingSupport.waitFor(DefaultWaitingSupport.groovy:46)
at geb.Page.waitFor(Page.groovy:516)
at geb.Browser.methodMissing(Browser.groovy:206)
at geb.spock.GebSpec.methodMissing(GebSpec.groovy:56)
at loaderSpec(loaderSpec.groovy:415)
 Caused by: Assertion failed:

 $(".loader").displayed== false
|            |        |
  |            true     false
   [[[ChromeDriver: chrome on XP (1b3943691dd96ebaf9098b1720c87ee9)] -> css
 selector: .loader]]

at loaderSpec(loaderSpec.groovy:415)
at loaderSpec(loaderSpec.groovy:415)
at geb.waiting.Wait.waitFor(Wait.groovy:127)
... 6 more

I am not sure how to check if the div is present or not present. If I extend the time to wait for, I am getting element not found error.

Kindly let me know your input.

Body:
Are you checking that the div is visible while you are waiting for the spinner to go away?
I've had an issue exactly like this that plagued me. Here is the solution my coworkers and I came up with:

try{
    waitFor(10) { element.isDisplayed() } //wait for spinner to kick in
    waitFor() { !element.isDisplayed() }  //wait for spinner to go away
} catch(WaitTimeoutException e) {
// if spinner loads & deloads faster than this code is reached
// then WTE will be caught and we dont need to handle the spinner any more

    //println(e.printStackTrace())
}


问:
Trigger events that are loaded via AJAX
The issue: when retrieving data from an Ajax request that contains components to be used in jQuery calls. The jQuery isn't working.

Solution: as answered by  Bikash Waiba the reason this happens is because the jQuery functionality needs to know the page has loaded.

答:
You could make it into a function, and have use the onclick="" attribute to call the function.

```<code><script>
function request(id) {
    $.ajax({
      url: '../resources/handlers/like.php',
      type: 'POST',
      data: {id: id},
      cache:false,
      success: function(data) {
        $('#likeNumber').html(data);
      }
    });
}
</script>
<div class='community-post-like-button' id='likeClick' data-value='test' onclick="request(this.id);">Like Me</div>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Trigger events that are loaded via AJAX

Body:
You could make it into a function, and have use the onclick="" attribute to call the function.

<script>
function request(id) {
    $.ajax({
      url: '../resources/handlers/like.php',
      type: 'POST',
      data: {id: id},
      cache:false,
      success: function(data) {
        $('#likeNumber').html(data);
      }
    });
}
</script>
<div class='community-post-like-button' id='likeClick' data-value='test' onclick="request(this.id);">Like Me</div>


问:
React Component interface to methods
Q: Is there any way to provide an interface to access public methods from a given reusable component?

Scenario: Imagine that I am buiding a Tabs component. It's located inside a parent component, called App:

```<code><App>
    <Tabs />
    <button id="previous">Previous</button>
    <button id="next">Next</button>
</App>
</code>```

As you can see there is two buttons that should interact with Tabs component, moving it to previous or next tab pane.

My implementation consists in keeping next() and previous() methods inside Tabs component:

```<code>export default class Tabs extends React.Component {
    next() {}
    previous() {}
}
</code>```

Q: How can I bind next() and previous() methods to those buttons inside App component? Can I write some kind of interface exposed by Tabs component? What is the best and clean way to do that?

Edit 1: ...

Edit 2: Tabs is a "reusable" component. Many applications can render it inside.

答:
If your buttons act on elements of the Tab component, then they should be inside this component. You can then easily change the state of your component with the onPress prop of the Button.

If you still want to keep your buttons outside of your component (even if I don't see a clear reason for that), then you should consider using a store like Redux to maintain a "global" state across your components.

Title: React Component interface to methods

Body:
Q: Is there any way to provide an interface to access public methods from a given reusable component?

Scenario: Imagine that I am buiding a Tabs component. It's located inside a parent component, called App:

<App>
    <Tabs />
    <button id="previous">Previous</button>
    <button id="next">Next</button>
</App>

As you can see there is two buttons that should interact with Tabs component, moving it to previous or next tab pane.

My implementation consists in keeping next() and previous() methods inside Tabs component:

export default class Tabs extends React.Component {
    next() {}
    previous() {}
}

Q: How can I bind next() and previous() methods to those buttons inside App component? Can I write some kind of interface exposed by Tabs component? What is the best and clean way to do that?

Edit 1: ...

Edit 2: Tabs is a "reusable" component. Many applications can render it inside.


问:
How to version/update AssemblyInfo.cs of assemblies shared by others that are deployed independent?
I've got a legacy solution with multiple project references.

Two of those projects are deployed independently, and both reference the other projects.

Currently the versioning is purely manual, but I'd like to automate the process (of updating the version number of AssemblyInfo.cs).

We're using Visual Studio 2010, SVN, and TeamCity, and already have a proven way of updating the version numbers for other solutions. However, those solutions only have one version number to consider, whilst this solution have to.

One way could be to update the two important, i.e. the reason for deployment, numbers automatically, and update the others manually.

答:
Try : Versioning Controlled Build

Command line-utility supports VC++ 6.0 DSW files as well as VS2002/2003/2005/2008 SLN files. It shares configuration settings with the add-in version, but user can override these settings with appropriate startup switches. Please check CommandLine.txt file included in the setup for a brief description and list of startup switches.
During command-line utility setup, corresponding menu with two items are added to Programs menu. "AutoVer" entry starts the command-line utility with /g switch, opening the same GUI as the add-in does.


问:
What are the standard containers that do not require CopyAssignable/CopyConstructible?
Until C++11, I think std::vector<T> required T to be CopyAssignable and CopyConstructible for basic operations (extending the capacity would require copying object to another memory location). But if you do v1 = v0, I assume that it would to actually copy the values.

Are there any standard containers that do not require for any of their functions their value_type to be assignable and copyable ?

To say it otherwise, I have a type that has is not copyable/assignable, which containers are safe to use portably and to what extent ?

答:
From cppreference.com

The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type is a complete type and meets the requirements of Erasable, but many member functions impose stricter requirements.

Notably std::vector<std::unique_ptr<T>> (for some complete T) is a non-CopyAssignable / non-CopyConstructible container.


问:
Android Studio - Images Expand Buttons (and break weight rules?)
I have been working around an issue for far too long. Any time I drop an image into an ImageButton, the button expands to be very large. To try to fix this, I created a TableLayout with TableRows, where the TableLayout has a weightSum and the rows each have their own layout_weight. However, regardless of how much weight that I assign a row, the image blows up and compresses all of my other rows. In other words, the TableRows do not respect the layout_weight assigned to them.

Below, I have four rows with weights 4, 5, 3, 1, respectively. The ImageButton is in the 3rd row with layout_weight="3". However, as you can see, the row expands to fit the button image.

At any rate, this is a major issue when I have multiple buttons on the screen. I have created many buttons of the same exact size thinking that I would make them large, so they will scale well with larger devices. Once again, the problem is that they don't scale down to fit inside of a button, but they expand the button, destroying all of the layout_weights in the process.

```<code><?xml version="1.0" encoding="utf-8"?>
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:weightSum="13"
        android:background="@drawable/edit_users_view">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="4"/>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="5">
            <ScrollView>
                <!-- Figure out button first -->
            </ScrollView>
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="3">
            <ImageButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/selector_cancel_button"/>

        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1">
        </TableRow>
</TableLayout>
</code>```

In addition - This issue may be in part with how I am storing my images. I have saved everything into my drawable folder, but nothing inside my mipmap folders. Though, I did try saving this cancel button into the mipmap-mdpi folder and loading it into the ImageButton, but the effect was exactly the same. Mipmap folders probably just set resolution, not size? I didn't expand my drawable folder because there are maybe 50 images/selectors inside.

答: The best that I can recommend you is to get your images sliced on the highest resolution you are targeting, let's say your higher resolution you are targeting is 1080x1920. Get you screen designed on this resolution and get the images on the actual size from this screen design. Put that images in respective "drawable" not "mipmap" like for 1080x1920 the respective folder is "drawable-xxhdpi". Access your images though drawable folder and then you don't even need to use weights or even fixed sizes. It will work like a charm.</p>

Body:
I have been working around an issue for far too long. Any time I drop an image into an ImageButton, the button expands to be very large. To try to fix this, I created a TableLayout with TableRows, where the TableLayout has a weightSum and the rows each have their own layout_weight. However, regardless of how much weight that I assign a row, the image blows up and compresses all of my other rows. In other words, the TableRows do not respect the layout_weight assigned to them.

Below, I have four rows with weights 4, 5, 3, 1, respectively. The ImageButton is in the 3rd row with layout_weight="3". However, as you can see, the row expands to fit the button image.

At any rate, this is a major issue when I have multiple buttons on the screen. I have created many buttons of the same exact size thinking that I would make them large, so they will scale well with larger devices. Once again, the problem is that they don't scale down to fit inside of a button, but they expand the button, destroying all of the layout_weights in the process.

<?xml version="1.0" encoding="utf-8"?>
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:weightSum="13"
        android:background="@drawable/edit_users_view">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="4"/>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="5">
            <ScrollView>

            </ScrollView>
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="3">
            <ImageButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/selector_cancel_button"/>

        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1">
        </TableRow>
</TableLayout>

In addition - This issue may be in part with how I am storing my images. I have saved everything into my drawable folder, but nothing inside my mipmap folders. Though, I did try saving this cancel button into the mipmap-mdpi folder and loading it into the ImageButton, but the effect was exactly the same. Mipmap folders probably just set resolution, not size? I didn't expand my drawable folder because there are maybe 50 images/selectors inside.


问:
Alternative to swiftmailer in laravel
I have an issue with using swiftmailer with the client's SMTP microsoft exchange server.

To troubleshoot, I am thinking of changing out the swiftmailer with something else.

My entire setup is on an internal network. So no mailgun or sendgrid at all.

How do I use an alternative library for swiftmailer in Laravel in order to troubleshoot?

Also this is the log I get when I tried to use swiftmailer on Laravel

```<code><< 250-xxx.internal.abc.com Hello [xxx.xx.xxx.xx]
250-SIZE 36700160
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-AUTH
250-8BITMIME
250-BINARYMIME
250-CHUNKING
250-XEXCH50
250 XSHADOW

>> STARTTLS

<< 500 5.3.3 Unrecognized command

!! Expected response code 220 but got code "500", with message "500 5.3.3 Unrecognized command
</code>```

What I tried part (I)

Somebody asked me to try MAIL_ENCRYPTION to null and dd(config('mail.encryption')), so the below is the answer:

Code:

```<code>    try {
        Mail::send('emails.test', [], function ($m) {
        $m->from('xxx@client.com', 'Your Application')->to('me@me.com');
        dd(config('mail.encryption'));
        var_dump('executed');
    });
     } catch (Exception $e) {
        var_dump($e->getMessage());
        var_dump($e->getTraceAsString());
    }
</code>```

Result:
   null  was printed out The string executed was not.

What I tried part (II):

explicitly use swiftmailer transport with encryption set to null

```<code>  try {
    // Create the Transport
    $transport = \Swift_SmtpTransport::newInstance();

    $transport->setUsername('xxx@client.com')
    ->setPort(25)
    ->setHost('smtp.internal.client.com')
    ->setEncryption(null);

    // Create the Mailer using your created Transport
    $mailer = \Swift_Mailer::newInstance($transport);

    $logger = new \Swift_Plugins_Loggers_ArrayLogger();
    $mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($logger));

    $message = new \Swift_Message('Wonderful Subject');
    $message->setFrom(['xxx@client.com' => 'John Doe']);
    $message->setTo(['me@me.com'])->setBody('Here is the message itself');

    // // Send the message
    $numSent = $mailer->send($message);
    } catch(\Swift_TransportException $e) {
        var_dump('test');
        var_dump($e->getMessage());
        var_dump($e->getTraceAsString());
    }
</code>```

Result:

```<code>www-data@server:~/html/laravel-app$ php artisan email:send
string(4) "test"
string(127) "Failed to authenticate on SMTP server with username "xxx@client.com" using 0 possible authenticators"
string(2503) "#0 /var/www/html/a3qp/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php(332): Swift_Transport_Esmtp_AuthHandler->afterEhlo(Object(Swift_SmtpTransport))
</code>```

What I tried Part (III):

Same as part II but set encryption to 'tls' explicitly. I get the same error message as the original one at the very top.

What I tried Part (IV):

Someone asked me to take out the dd line in Part I This is what I got

```<code>string(8) "executed"
[Swift_TransportException]
Failed to authenticate on SMTP server with username "xxx@client.com" using 0 possible authenticators
</code>```

Update

I am using SMTP to a MS Exchange server that is in my client's infrastructure. I have no access to that server's SMTP log, so it's hard to troubleshoot. The code is totally intranet. There is no access to outside internet service and I am not supposed to use mailgun or any other smtp cloud services to send client's transactional emails meant for internal consumption.

I have another code using a legacy cakephp 2 system that can work with the same SMTP mail server with no issues.

I have tested my laravel SMTP settings on a google mail. And it works fine.

My next step for troubleshooting is to see if it's swiftmailer or the rest of laravel where the issue lies. Hence this post.

Yes, I am trying to get hold of the IT team responsible for the Exchange server, but they are in another country. I am still trying though.

I know I am repeating point 2, but the comments suggest that this point is not clear enough. I am using the exact same SMTP settings on a legacy cakephp 2 system to send emails and there is no issue. Because I cannot get hold of the IT team responsible for the exchange server and plus the SMTP settings do work for another cakephp 2 system, I feel I should try to troubleshoot it on the laravel system to find out for sure.

I have tried PHP mail and sendmail by changing the .env file. I did not trigger any error messages but i also appear not to receive any emails.

Please see What I tried Part I, Part II, Part III, Part IV for details on code used to test the SMTP

答:
The SMTP server you're attempting to connect to does not understand the STARTTLS command. To prevent the STARTTLS command from being attempted, you must disable encryption by setting your MAIL_ENCRYPTION environment variable to null in your .env file.

The next issue is that, according to the EHLO response, the SMTP server does not accept any authentication methods. If it did, the line 250-AUTH would also include the methods it accepted (e.g. 250-AUTH PLAIN DIGEST-MD5).

To prevent an authentication attempt, you must set your MAIL_USERNAME environment variable to null in your .env file.

To sum up, your .env file should have the following lines:

```<code>MAIL_ENCRYPTION=null
MAIL_USERNAME=null
</code>```

That will disable tls encryption and disable authentication.

Title: Alternative to swiftmailer in laravel

Body:
I have an issue with using swiftmailer with the client's SMTP microsoft exchange server.

To troubleshoot, I am thinking of changing out the swiftmailer with something else.

My entire setup is on an internal network. So no mailgun or sendgrid at all.

How do I use an alternative library for swiftmailer in Laravel in order to troubleshoot?

Also this is the log I get when I tried to use swiftmailer on Laravel

<< 250-xxx.internal.abc.com Hello [xxx.xx.xxx.xx]
250-SIZE 36700160
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-AUTH
250-8BITMIME
250-BINARYMIME
250-CHUNKING
250-XEXCH50
250 XSHADOW

>> STARTTLS

<< 500 5.3.3 Unrecognized command

!! Expected response code 220 but got code "500", with message "500 5.3.3 Unrecognized command

What I tried part (I)

Somebody asked me to try MAIL_ENCRYPTION to null and dd(config('mail.encryption')), so the below is the answer:

Code:

    try {
        Mail::send('emails.test', [], function ($m) {
        $m->from('xxx@client.com', 'Your Application')->to('me@me.com');
        dd(config('mail.encryption'));
        var_dump('executed');
    });
     } catch (Exception $e) {
        var_dump($e->getMessage());
        var_dump($e->getTraceAsString());
    }

Result:
   null  was printed out The string executed was not.

What I tried part (II):

explicitly use swiftmailer transport with encryption set to null

  try {
    // Create the Transport
    $transport = \Swift_SmtpTransport::newInstance();

    $transport->setUsername('xxx@client.com')
    ->setPort(25)
    ->setHost('smtp.internal.client.com')
    ->setEncryption(null);

    // Create the Mailer using your created Transport
    $mailer = \Swift_Mailer::newInstance($transport);

    $logger = new \Swift_Plugins_Loggers_ArrayLogger();
    $mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($logger));

    $message = new \Swift_Message('Wonderful Subject');
    $message->setFrom(['xxx@client.com' => 'John Doe']);
    $message->setTo(['me@me.com'])->setBody('Here is the message itself');

    // // Send the message
    $numSent = $mailer->send($message);
    } catch(\Swift_TransportException $e) {
        var_dump('test');
        var_dump($e->getMessage());
        var_dump($e->getTraceAsString());
    }

Result:

www-data@server:~/html/laravel-app$ php artisan email:send
string(4) "test"
string(127) "Failed to authenticate on SMTP server with username "xxx@client.com" using 0 possible authenticators"
string(2503) "#0 /var/www/html/a3qp/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php(332): Swift_Transport_Esmtp_AuthHandler->afterEhlo(Object(Swift_SmtpTransport))

What I tried Part (III):

Same as part II but set encryption to 'tls' explicitly. I get the same error message as the original one at the very top.

What I tried Part (IV):

Someone asked me to take out the dd line in Part I This is what I got

string(8) "executed"
[Swift_TransportException]
Failed to authenticate on SMTP server with username "xxx@client.com" using 0 possible authenticators

Update

I am using SMTP to a MS Exchange server that is in my client's infrastructure. I have no access to that server's SMTP log, so it's hard to troubleshoot. The code is totally intranet. There is no access to outside internet service and I am not supposed to use mailgun or any other smtp cloud services to send client's transactional emails meant for internal consumption.

I have another code using a legacy cakephp 2 system that can work with the same SMTP mail server with no issues.

I have tested my laravel SMTP settings on a google mail. And it works fine.

My next step for troubleshooting is to see if it's swiftmailer or the rest of laravel where the issue lies. Hence this post.

Yes, I am trying to get hold of the IT team responsible for the Exchange server, but they are in another country. I am still trying though.

I know I am repeating point 2, but the comments suggest that this point is not clear enough. I am using the exact same SMTP settings on a legacy cakephp 2 system to send emails and there is no issue. Because I cannot get hold of the IT team responsible for the exchange server and plus the SMTP settings do work for another cakephp 2 system, I feel I should try to troubleshoot it on the laravel system to find out for sure.

I have tried PHP mail and sendmail by changing the .env file. I did not trigger any error messages but i also appear not to receive any emails.

Please see What I tried Part I, Part II, Part III, Part IV for details on code used to test the SMTP

Body:
The SMTP server you're attempting to connect to does not understand the STARTTLS command. To prevent the STARTTLS command from being attempted, you must disable encryption by setting your MAIL_ENCRYPTION environment variable to null in your .env file.

The next issue is that, according to the EHLO response, the SMTP server does not accept any authentication methods. If it did, the line 250-AUTH would also include the methods it accepted (e.g. 250-AUTH PLAIN DIGEST-MD5).

To prevent an authentication attempt, you must set your MAIL_USERNAME environment variable to null in your .env file.

To sum up, your .env file should have the following lines:

MAIL_ENCRYPTION=null
MAIL_USERNAME=null

That will disable tls encryption and disable authentication.


问:
How can a slow internet on client side be a reason for server time out exception in asp.net?
I have a .Net application up and running.

We have had a fluctuating connection yesterday. While testing in such scenarios we had received multiple server time out exception emails like below.

Server Time Out

```<code>Type : System.Web.HttpException, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
Message : Request timed out.
Source :
Help link :
WebEventCode : 3001
ErrorCode : -2147467259
Data : System.Collections.ListDictionaryInternal
TargetSite :
HResult : -2147467259
Stack Trace : The stack trace is unavailable.
Additional Info:
</code>```

IMPORTANT: Above exception occurred while doing a ajax post by a button placed with in update panel.

My question here is why would a slow internet on client side raise such server time out exception?

Isn't server timeout exception is related to such cases where server cannot execute the request in underlying time mention in HttpRuntime setting? May be due to some lengthy operation or some long database execution which takes longer than the time mentioned in setting under HttpRuntime.

If server is not able to connect to the client due to clients fluctuating internet, then Client Disconnected exception would be raised which we did yesterday. But I am not able to conclude the reason for this server timeout exception.

I already know that increasing the execution timeout will fix the issue, but I have to provide technical explanation for the reason as to why such exception of Server Timeout raised.

My best guess here is that the ajax request would be doing some continuous communication with server for executing of single request server and would raise timeout exception if it does not receives some required further communication messages due to client's bad internet. I have search over internet for the same to support my guess but in vain.

Also to provide environmental details, there is a load balancer serving the request.

Any help would be highly appreciated.

答:
It is because (as you write) the connection of client to server is slow, so if the server (or client) sending data to this server, connection can´t handle it, so you get timeout error, because the data can´t been transfered in defined time.

You also write, that this is caused by sending Ajax request, so maybe try to increase execusion timeout in web configuration file (web.config):

```<code><httpRuntime executionTimeout = "number(in seconds)"/>
</code>```

More about executionTimeout here and here about Ajax requests.

Body:
I have a .Net application up and running.

We have had a fluctuating connection yesterday. While testing in such scenarios we had received multiple server time out exception emails like below.

Server Time Out

Type : System.Web.HttpException, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
Message : Request timed out.
Source :
Help link :
WebEventCode : 3001
ErrorCode : -2147467259
Data : System.Collections.ListDictionaryInternal
TargetSite :
HResult : -2147467259
Stack Trace : The stack trace is unavailable.
Additional Info:

IMPORTANT: Above exception occurred while doing a ajax post by a button placed with in update panel.

My question here is why would a slow internet on client side raise such server time out exception?

Isn't server timeout exception is related to such cases where server cannot execute the request in underlying time mention in HttpRuntime setting? May be due to some lengthy operation or some long database execution which takes longer than the time mentioned in setting under HttpRuntime.

If server is not able to connect to the client due to clients fluctuating internet, then Client Disconnected exception would be raised which we did yesterday. But I am not able to conclude the reason for this server timeout exception.

I already know that increasing the execution timeout will fix the issue, but I have to provide technical explanation for the reason as to why such exception of Server Timeout raised.

My best guess here is that the ajax request would be doing some continuous communication with server for executing of single request server and would raise timeout exception if it does not receives some required further communication messages due to client's bad internet. I have search over internet for the same to support my guess but in vain.

Also to provide environmental details, there is a load balancer serving the request.

Any help would be highly appreciated.

Body:
It is because (as you write) the connection of client to server is slow, so if the server (or client) sending data to this server, connection can´t handle it, so you get timeout error, because the data can´t been transfered in defined time.

You also write, that this is caused by sending Ajax request, so maybe try to increase execusion timeout in web configuration file (web.config):

<httpRuntime executionTimeout = "number(in seconds)"/>

More about executionTimeout here and here about Ajax requests.


问:
string interpolation with jQuery
I'm trying to pass in the value of a variable to a jQuery selector but I can't seem to get it right. Here is what I'm working with:

jQuery

```<code>var state = $("<%= @state %>").selector;
</code>```

that captures this value -> "pending"

I'm trying to pass that value into this selector:

jQuery

```<code>$(".snitches-index-header + .tags-column .#{state}_count")
</code>```

As you can see I'm trying to pass the string into the jQuery selector. But this is not working as I expect. What am I doing wrong so that the selector would read:

```<code>$(".snitches-index-header + .tags-column .pending_count")
</code>```

but obviously use the variable state instead of pending?

答:
You can concatenate the variable with the string:

```<code>$(".snitches-index-header + .tags-column ." + state + "_count")
</code>```

If you are trying to use a Template literal then you need to use backticks and the dollar sign not #:

```<code>$(`.snitches-index-header + .tags-column .${state}_count`)
</code>```

Title: string interpolation with jQuery

Body:
I'm trying to pass in the value of a variable to a jQuery selector but I can't seem to get it right. Here is what I'm working with:

jQuery

var state = $("<%= @state %>").selector;

that captures this value -> "pending"

I'm trying to pass that value into this selector:

jQuery

$(".snitches-index-header + .tags-column .#{state}_count")

As you can see I'm trying to pass the string into the jQuery selector. But this is not working as I expect. What am I doing wrong so that the selector would read:

$(".snitches-index-header + .tags-column .pending_count")

but obviously use the variable state instead of pending?

Body:
You can concatenate the variable with the string:

$(".snitches-index-header + .tags-column ." + state + "_count")

If you are trying to use a Template literal then you need to use backticks and the dollar sign not #:

$(`.snitches-index-header + .tags-column .${state}_count`)


问:
Rails strong params for creating multiple objects from one form
I am trying to create multiple objects of the same model from one form. Params which I get in my create method look like this:

```<code><ActionController::Parameters {"objects"=> <ActionController::Parameters {
  "0"=>{priority"=>"24", "style"=>"three_pictures"},
  "1"=>{"priority"=>"24", "style"=>"three_pictures"},
  "2"=>{"priority"=>"24", "style"=>"three_pictures"}
} permitted: false>}permitted: false>
</code>```

I am confused about using strong params in this case. My create method looks like this:

```<code>def create
  params[:objects].each do |index, object|
    Object.create(object.permit(:priority, :style))
  end
  ...
end
</code>```

This works, but doesn't look like the right way to do this. How should this be done?

答:
I think that I need a bit more info here. When I create more than 1 record at a time its usually a chield of another object and mine looks like this

```<code># Never trust parameters from the scary internet, only allow the white list through.
def family_params
  params.require(:family).permit(:name, users_attributes: [ :name, :email ])
end
</code>```

I hope that this helps.

Happy Hacking :)

Body:
I am trying to create multiple objects of the same model from one form. Params which I get in my create method look like this:

<ActionController::Parameters {"objects"=> <ActionController::Parameters {
  "0"=>{priority"=>"24", "style"=>"three_pictures"},
  "1"=>{"priority"=>"24", "style"=>"three_pictures"},
  "2"=>{"priority"=>"24", "style"=>"three_pictures"}
} permitted: false>}permitted: false>

I am confused about using strong params in this case. My create method looks like this:

def create
  params[:objects].each do |index, object|
    Object.create(object.permit(:priority, :style))
  end
  ...
end

This works, but doesn't look like the right way to do this. How should this be done?

Body:
I think that I need a bit more info here. When I create more than 1 record at a time its usually a chield of another object and mine looks like this

# Never trust parameters from the scary internet, only allow the white list through.
def family_params
  params.require(:family).permit(:name, users_attributes: [ :name, :email ])
end

I hope that this helps.

Happy Hacking :)


问:
What's the right way to do counts in Rails?
I have a rails app with many following pieces of code:

```<code>Our active community of <%= Account.find_all_by_admin(false).count %>
</code>```

My question is is this the right way to do counts on views? It seems so "dirty" is there a more railish, way to do counts? I'm thinking named scopes perhaps, but I just want to be sure that these type of things won't have  a greater impact in performance.

Thank You,

答:
A named scope shouldn't have an impact on performance

```<code>scope :not_admin, where(:admin => false)
</code>```

Then you can have Account.not_admin.count

Edited per DGM's comment: To check the generated SQL in a console, compare Account.not_admin.to_sql with Account.find_all_by_admin(false).to_sql

Body:
I have a rails app with many following pieces of code:

Our active community of <%= Account.find_all_by_admin(false).count %>

My question is is this the right way to do counts on views? It seems so "dirty" is there a more railish, way to do counts? I'm thinking named scopes perhaps, but I just want to be sure that these type of things won't have  a greater impact in performance.

Thank You,

Body:
A named scope shouldn't have an impact on performance

scope :not_admin, where(:admin => false)

Then you can have Account.not_admin.count

Edited per DGM's comment: To check the generated SQL in a console, compare Account.not_admin.to_sql with Account.find_all_by_admin(false).to_sql


问:
POST 404 Error (Component not found) in Joomla
I am running some custom php file that contains some javascript code within a Joomla website through an extension called sourcerer. Everything works as expected from the php side of things however I am experiencing an issue with a call to another php file made from within a javascript.  Here is the javascript code in question and on the second line is the "suburb.php" file that is called from within this code that is causing the issue.

```<code>$.ajax({
 url : 'suburb.php',
 dataType: "json",
 method: 'post',
 data: {
     name_startsWith: request.term,
     type: 'suburb_table',
     row_num : 1
 },
 success: function( data ) {
     response( $.map( data, function( item ) {
         var code = item.split("|");
         return {
             label: code[0],
             value: code[0],
             data : item
         }
     }));
 }
});
</code>```

The problem I am having is that even though the originating php file that contains this javascript is in the same directory as the suburb.php file, Joomla seems to change the URL call to "localhost/index.php/menu_alias/suburb.php" and this causes a POST error 404 (Component non found).

I have tried using many variation of the url path in that second line of the code, but all have failed. Can somebody tell me what my url path should look like for this to work?

Thank you,
Adri

答:
Use an absolute URL instead of of just "suburb.php" so it should be something like: http://www.[joomlasite].com/suburb.php

As for the localhost, then I would say you likely have the $live_site set to "localhost" in your configuration.php - make sure you set the $live_site to empty. If that's not the case, then search your database for any occurrence of localhost.

Body:
I am running some custom php file that contains some javascript code within a Joomla website through an extension called sourcerer. Everything works as expected from the php side of things however I am experiencing an issue with a call to another php file made from within a javascript.  Here is the javascript code in question and on the second line is the "suburb.php" file that is called from within this code that is causing the issue.

$.ajax({
 url : 'suburb.php',
 dataType: "json",
 method: 'post',
 data: {
     name_startsWith: request.term,
     type: 'suburb_table',
     row_num : 1
 },
 success: function( data ) {
     response( $.map( data, function( item ) {
         var code = item.split("|");
         return {
             label: code[0],
             value: code[0],
             data : item
         }
     }));
 }
});

The problem I am having is that even though the originating php file that contains this javascript is in the same directory as the suburb.php file, Joomla seems to change the URL call to "localhost/index.php/menu_alias/suburb.php" and this causes a POST error 404 (Component non found).

I have tried using many variation of the url path in that second line of the code, but all have failed. Can somebody tell me what my url path should look like for this to work?

Thank you,
Adri


问:
Maven Jacoco Configuration - Exclude classes/packages from report not working
I have a maven multi-module project and I'm using jacoco-maven for code coverage reports. Some classes should not be reported, as they're Spring configuration and I'm not interested in them.

I have declared the maven-jacoco plugin as follow:

```<code><plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.2.201409121644</version>
<configuration>
    <outputDirectory>${project.reporting.outputDirectory}/jacoco-ut</outputDirectory>
    <exclude>some.package.*</exclude>
    <exclude>**/*Config.*</exclude>
    <exclude>**/*Dev.*</exclude>
    <exclude>some/package/SomeClass.java</exclude>
</configuration>
<executions>
    <execution>
        <goals>
            <goal>prepare-agent</goal>
        </goals>
    </execution>
    <execution>
        <id>report</id>
        <phase>prepare-package</phase>
        <goals>
            <goal>report</goal>
        </goals>
    </execution>
    <execution>
        <id>post-unit-test</id>
        <phase>test</phase>
        <goals>
            <goal>report</goal>
        </goals>
    </execution>
</executions>
</plugin>
</code>```

The problem is that when I execute mvn clean verify jacoco still reports classes that should have been excluded as my xml configuration points out. How can I configure it properly?

答:
Though Andrew already answered question with details , i am giving code how to exclude it in pom

```<code>           <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.7.9</version>
                <configuration>
                    <excludes>
                        <exclude>**/*com/test/vaquar/khan/HealthChecker.class</exclude>
                    </excludes>
                </configuration>
                <executions>
                    <!-- prepare agent for measuring integration tests -->
                    <execution>
                        <id>jacoco-initialize</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>jacoco-site</id>
                        <phase>package</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
</code>```

For Springboot application

```<code><build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>sonar-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.sonarsource.scanner.maven</groupId>
                <artifactId>sonar-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                       <!-- Exclude class from test coverage -->
                        <exclude>**/*com/khan/vaquar/Application.class</exclude>
                        <!-- Exclude full package from test coverage -->
                        <exclude>**/*com/khan/vaquar/config/**</exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</code>```

Body:
I have a maven multi-module project and I'm using jacoco-maven for code coverage reports. Some classes should not be reported, as they're Spring configuration and I'm not interested in them.

I have declared the maven-jacoco plugin as follow:

<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.2.201409121644</version>
<configuration>
    <outputDirectory>${project.reporting.outputDirectory}/jacoco-ut</outputDirectory>
    <exclude>some.package.*</exclude>
    <exclude>**/*Config.*</exclude>
    <exclude>**/*Dev.*</exclude>
    <exclude>some/package/SomeClass.java</exclude>
</configuration>
<executions>
    <execution>
        <goals>
            <goal>prepare-agent</goal>
        </goals>
    </execution>
    <execution>
        <id>report</id>
        <phase>prepare-package</phase>
        <goals>
            <goal>report</goal>
        </goals>
    </execution>
    <execution>
        <id>post-unit-test</id>
        <phase>test</phase>
        <goals>
            <goal>report</goal>
        </goals>
    </execution>
</executions>
</plugin>

The problem is that when I execute mvn clean verify jacoco still reports classes that should have been excluded as my xml configuration points out. How can I configure it properly?

Body:
Though Andrew already answered question with details , i am giving code how to exclude it in pom

           <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.7.9</version>
                <configuration>
                    <excludes>
                        <exclude>**/*com/test/vaquar/khan/HealthChecker.class</exclude>
                    </excludes>
                </configuration>
                <executions>
                    <!-- prepare agent for measuring integration tests -->
                    <execution>
                        <id>jacoco-initialize</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>jacoco-site</id>
                        <phase>package</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

For Springboot application

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>sonar-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.sonarsource.scanner.maven</groupId>
                <artifactId>sonar-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                       <!-- Exclude class from test coverage -->
                        <exclude>**/*com/khan/vaquar/Application.class</exclude>
                        <!-- Exclude full package from test coverage -->
                        <exclude>**/*com/khan/vaquar/config/**</exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>


问:
Angularjs Filter comparison with two numbers
I have a collection of fields and a collection of pages.  Each field has a pageNumber property and each page has a pageNumber property.  In my filter, I want to only list the fields that match the page that I'm currently on in the parent ng-repeat.  This works great unless I have 10 pages in the pages collection because then it lists all the fields in any pages 10 through 19 on page one also.  I assume that somehow the filter I'm using returns a positive match when 1=1, 1=10, 1=11, 1=12, etc. for some reason.  How can I make sure the comparison it matches the pages correctly?

```<code><div ng-repeat="p in model.pages">
    <div ng-repeat="f in model.fields | filter: { pageNumber: p.pageNumber }">
        <div class="pdf-field">{{f.pageNumber}} = {{p.pageNumber}}</div>
    </div>
</div>
</code>```

答:
Try adding :true at the end. It matches for strict equality only:

```<code><div ng-repeat="f in model.fields | filter: { pageNumber: p.pageNumber }:true">
</code>```

Body:
I have a collection of fields and a collection of pages.  Each field has a pageNumber property and each page has a pageNumber property.  In my filter, I want to only list the fields that match the page that I'm currently on in the parent ng-repeat.  This works great unless I have 10 pages in the pages collection because then it lists all the fields in any pages 10 through 19 on page one also.  I assume that somehow the filter I'm using returns a positive match when 1=1, 1=10, 1=11, 1=12, etc. for some reason.  How can I make sure the comparison it matches the pages correctly?

{{f.pageNumber}} = {{p.pageNumber}}

Body:
Try adding :true at the end. It matches for strict equality only:

<div ng-repeat="f in model.fields | filter: { pageNumber: p.pageNumber }:true">


答:
its just basic js syntax issue.</p>

```<code>  $(".snitches-index-header + .tags-column ."+state+"_count");
</code>```

Title: string interpolation with jQuery

Body:
its just basic js syntax issue.

  $(".snitches-index-header + .tags-column ."+state+"_count");


问:
Extracting Data from TTN (TheThings Network) using REST API
I have successfully Integrated TTN theThingsNetwork with my LoRaWAN Gateway. Also I am able to forward data between from Nodes to theThingsNetwork. Now I am looking for information to fetch data from TTN Thethingsnetwork to my own server. Any information will be appreciated.
Thanks in advance.

Regards,
Zaheen

答:
First, let me welcome your on The Things Network !

To get your data to your own server, you have several possibilities:

The first one is to create a MQTT client running on your server to receive all your data in real-time. For this, you can use several SDKs provided by The Things Network at https://www.thethingsnetwork.org/docs/applications/sdks.html

The next way to do it is using integrations. In the upper-right corder of your application management console, you should see an "Integration" tab.

Using this tab, you can create two different types of integrations:

The first type is the "HTTP integration". Using this one, all received messages for your application will be forwarded to the url provided in the integration configuration. A complete documentation is available at https://www.thethingsnetwork.org/docs/applications/http/

The second type is the "Storage integration". Using this one, all your received messages are stored in a database for 7 days ans are query-able via REST. A complete documentation is available at https://www.thethingsnetwork.org/docs/applications/http/ https://www.thethingsnetwork.org/docs/applications/storage/


问:
How to embed Youtube live chat with url permanent?
The embed URL for a channel's live stream is:

```<code>https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID
</code>```

and it works but if I want to embed near at it a YouTube live chat for current streaming the URL that I use for the embed is:

```<code>https://www.youtube.com/live_chat?v=VIDEOID&embed_domain=DOMAINURL
</code>```

The problem is this: for every new live stream the Video ID changes. So that the embedded code isn't valid anymore and chat isn't displayed for next streaming.I want a permanent URL live chat valid for all my YouTube streaming
without change video id manually every time.
How to resolve? Perhaps with a script in PHP or javascript that read current YouTube URL and replace video id in chat embed URL?
thanks

答:
You could get the video ID using PHP like this:

<?php

try {
    $videoId = getLiveVideoID('CHANNEL_ID');

    // Output the Chat URL
    echo "The Chat URL is https://www.youtube.com/live_chat?v=".$videoId;
} catch(Exception $e) {
    // Echo the generated error
    echo "ERROR: ".$e->getMessage();
}

// The method which finds the video ID
function getLiveVideoID($channelId)
{
    $videoId = null;

    // Fetch the livestream page
    if($data = file_get_contents('https://www.youtube.com/embed/live_stream?channel='.$channelId))
    {
        // Find the video ID in there
        if(preg_match('/\'VIDEO_ID\': \"(.*?)\"/', $data, $matches))
            $videoId = $matches[1];
        else
            throw new Exception('Couldn\'t find video ID');
    }
    else
        throw new Exception('Couldn\'t fetch data');

    return $videoId;
}
```

Body:
The embed URL for a channel's live stream is:

https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID

and it works but if I want to embed near at it a YouTube live chat for current streaming the URL that I use for the embed is:

https://www.youtube.com/live_chat?v=VIDEOID&embed_domain=DOMAINURL

The problem is this: for every new live stream the Video ID changes. So that the embedded code isn't valid anymore and chat isn't displayed for next streaming.I want a permanent URL live chat valid for all my YouTube streaming
without change video id manually every time.
How to resolve? Perhaps with a script in PHP or javascript that read current YouTube URL and replace video id in chat embed URL?
thanks


问:
How to mock a dictionary?
First, I'd better ask if I should mock dictionaries? And if I should how can I achieve that?

I am using Rhino Mocks. I looked through its documentation and saw that it can mock ArrayList. So I tried it on Dictionary but no luck. I got the error that I'm not calling a virtual method bla bla... Will it be a problem if I don't mock it?

答:
I can assure you that the Dictionary works fine in .Net :)

I think you need to be pragmatic when writing your tests and not try to mock everything. Because how far can you go? How would you mock an int? Obviously it is discussable where is the border line, but I usually don't mock:

.Net framework as long as it doesn't connect to some external resources

my own trivial classes (i.e. ones that only store data)

static helper methods (these should be really simple though), including extension methods

Title: How to mock a dictionary?


问:
where() takes from 1 to 2 positional arguments but 3 were given
I have three arrays, X, Y and Z. I want to put in res and element of X in case the corresponding element from Z is true; otherwise, I will put an element from Y.

I implemented it like this:

```<code>X = tf.constant([[1, 2], [3, 4]])
Y = tf.constant([[5, 6], [7, 8]])
Z = tf.constant([[True, False], [False, True]], tf.bool)
res = tf.where(Z, X, Y)
print(res.eval())
</code>```

However, I am getting this error:

```<code>TypeError: where() takes from 1 to 2 positional arguments but 3 were given
</code>```

I looked at the definiton of tf.where from here and my usage seems fine.

Any idea what could be the issue?

答:
I suspect you are using an old version of TensorFlow:

e.g. in r0.10 tf.where used to take only 2 arguments.

tf.where(input, name=None)

https://www.tensorflow.org/versions/r0.10/api_docs/python/math_ops/sequence_comparison_and_indexing#where

Body:
I have three arrays, X, Y and Z. I want to put in res and element of X in case the corresponding element from Z is true; otherwise, I will put an element from Y.

I implemented it like this:

X = tf.constant([[1, 2], [3, 4]])
Y = tf.constant([[5, 6], [7, 8]])
Z = tf.constant([[True, False], [False, True]], tf.bool)
res = tf.where(Z, X, Y)
print(res.eval())

However, I am getting this error:

TypeError: where() takes from 1 to 2 positional arguments but 3 were given

I looked at the definiton of tf.where from here and my usage seems fine.

Any idea what could be the issue?