问:
whereraw Vs DB::raw in Laravel
I am confused and really don't know how and where should I choose to use one from both ?

I read docs for both

https://laravel.com/docs/5.4/queries#where-clauses

And

https://laravel.com/docs/5.4/queries#raw-expressions

If I use query something like this its not working

```<code>DB::table('table_name')
->where('parent_id', $parent_id)
->whereRaw("date",">",$date)
->get();
</code>```

But it works

```<code>DB::table('table_name')
->where('parent_id', $parent_id)
->where(DB::raw("date",">",$date))
->get();
</code>```

答:
DB::raw() lets you write raw statements as a part of the query. Eg:

```<code>->where(DB::raw('DATE(date_column)'), '>', '2017-01-01')
</code>```

But if you need to write a complete "raw where", you should use whereRaw (for your convenience). Eg:

```<code>->whereRaw('DATE(date_column) > DATE(another_date_column)')
</code>```

Also, whereRaw() accepts a complete where clause.

So, in your first example it's not working, because you should do it:

```<code>->whereRaw("date > ".$date)
</code>```

And your second example could be simplified by using just whereRaw() like the above statement in my answer.

Also DB::raw() can be used in ->select(),groupBy() and others.

Title: whereraw Vs DB::raw in Laravel

Body:
I am confused and really don't know how and where should I choose to use one from both ?

I read docs for both

https://laravel.com/docs/5.4/queries#where-clauses

And

https://laravel.com/docs/5.4/queries#raw-expressions

If I use query something like this its not working

DB::table('table_name')
->where('parent_id', $parent_id)
->whereRaw("date",">",$date)
->get();

But it works

DB::table('table_name')
->where('parent_id', $parent_id)
->where(DB::raw("date",">",$date))
->get();

Body:
DB::raw() lets you write raw statements as a part of the query. Eg:

->where(DB::raw('DATE(date_column)'), '>', '2017-01-01')

But if you need to write a complete "raw where", you should use whereRaw (for your convenience). Eg:

->whereRaw('DATE(date_column) > DATE(another_date_column)')

Also, whereRaw() accepts a complete where clause.

So, in your first example it's not working, because you should do it:

->whereRaw("date > ".$date)

And your second example could be simplified by using just whereRaw() like the above statement in my answer.

Also DB::raw() can be used in ->select(),groupBy() and others.


来源: stackexchange

问:
Asp.Net page reload problem after login
I am devolping a web application.the problem is that i am using a login control (not a .NET control) which is a part of master page and is acessible from all pages. if user log In from a page the login control updates itself and displlay some statistics of logged In user but the specific page does not reload. (some options on page are visible only to authenticated users, so that after login, page should be reloaded to display such options)

after logIn methoed I wrote

```<code>Reponse.Redirect(Request.Url.AbsoluteUri)
</code>```

after this the browser response the "Page cannot be displayed"

It would be of great help to me.

Many Thanks, Regards. AZHAR

答:
Another thing that you should look at is the roles that you allow in the folder (in the web.config file in the folder).

I accidentally misspelt a role name and it kept redirecting my users to the login page.

ContentLicense: CC BY-SA 2.5

Title: Asp.Net page reload problem after login

Body:
I am devolping a web application.the problem is that i am using a login control (not a .NET control) which is a part of master page and is acessible from all pages. if user log In from a page the login control updates itself and displlay some statistics of logged In user but the specific page does not reload. (some options on page are visible only to authenticated users, so that after login, page should be reloaded to display such options)

after logIn methoed I wrote

Reponse.Redirect(Request.Url.AbsoluteUri)

after this the browser response the "Page cannot be displayed"

It would be of great help to me.

Many Thanks, Regards. AZHAR


问:
elasticsearch ajax call error
I try to use elasticsearch with an ajax call in my jquery webpage but I fail to make it work...

here is my ajax query :

```<code>var data = {
                query:{match:{_all:10}},
                fields: 'DEPET'
                };
            $.ajax({
                type : 'POST', // envoi des données en GET ou POST
                url : 'http://localhost:9200/_search' , // url du fichier de traitement
                crossDomain: true,
              async: false,
              data: JSON.stringify(data),
              dataType : 'json',
                beforeSend : function() { // traitements JS à faire AVANT l'envoi
                    $('#ajax-loader2').append('<img src="/dev/wp-content/themes/codium-dn/images/ripple.gif" alt="loader" id="ajax-loader" />');
                },
                success : function(data){ // traitements JS à faire APRES le retour d'ajax-search.php
                    $('#ajax-loader').remove(); // on enleve le loader
                    $('#results').html(data); // affichage des résultats dans le bloc
                    console.log(data);
                },
                error: function (data, error) {
                    console.log(arguments);
                    //alert(" Can't do because: " + error);
                }
            })
</code>```

I also put this in my elasticsearch.yml

```<code>http.cors.enabled: true
http.cors.allow-origin: "*"
http.cors.allow-credentials: true
http.cors.allow-headers: "X-Requested-With, Content-Type, Content-Length, Authorization"
http.cors.allow-methods: OPTIONS, HEAD, GET, POST, PUT, DELETE
</code>```

And this is what the console chrome dev give me :

```<code>(index):451 (3) [Object, "error", DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://localhost:9200/_s…, callee: function, Symbol(Symbol.iterator): function]

Request URL:http://localhost:9200/_search
Referrer Policy:no-referrer-when-downgrade
Request Headers
Provisional headers are shown
Accept:application/json, text/javascript, */*; q=0.01
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Origin:https://domain.ovh
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.33 Safari/537.36
Form Data
view source
view URL encoded
{"query":{"match":{"_all":10}},"fields":"DEPET"}:
</code>```

Thanks for your inputs

答:
Try out this

```<code>var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:9200/_search",
  "method": "POST",
  "headers": {
    "cache-control": "no-cache",
    "postman-token": "c24112d5-9dc4-0230-7954-01064b61be5c"
  },
  "data": "{\r\n  \"query\": {\r\n    \"match_all\": {}\r\n  }\r\n}\r\n"
}

$.ajax(settings).done(function (response) {
  console.log(response);
});
</code>```

I have used postman tool to generate this code.

ContentLicense: CC BY-SA 3.0

Title: elasticsearch ajax call error

Body:
I try to use elasticsearch with an ajax call in my jquery webpage but I fail to make it work...

here is my ajax query :

var data = {
                query:{match:{_all:10}},
                fields: 'DEPET'
                };
            $.ajax({
                type : 'POST', // envoi des données en GET ou POST
                url : 'http://localhost:9200/_search' , // url du fichier de traitement
                crossDomain: true,
              async: false,
              data: JSON.stringify(data),
              dataType : 'json',
                beforeSend : function() { // traitements JS à faire AVANT l'envoi
                    $('#ajax-loader2').append('');
                },
                success : function(data){ // traitements JS à faire APRES le retour d'ajax-search.php
                    $('#ajax-loader').remove(); // on enleve le loader
                    $('#results').html(data); // affichage des résultats dans le bloc
                    console.log(data);
                },
                error: function (data, error) {
                    console.log(arguments);
                    //alert(" Can't do because: " + error);
                }
            })

I also put this in my elasticsearch.yml

http.cors.enabled: true
http.cors.allow-origin: "*"
http.cors.allow-credentials: true
http.cors.allow-headers: "X-Requested-With, Content-Type, Content-Length, Authorization"
http.cors.allow-methods: OPTIONS, HEAD, GET, POST, PUT, DELETE

And this is what the console chrome dev give me :

(index):451 (3) [Object, "error", DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://localhost:9200/_s…, callee: function, Symbol(Symbol.iterator): function]

Request URL:http://localhost:9200/_search
Referrer Policy:no-referrer-when-downgrade
Request Headers
Provisional headers are shown
Accept:application/json, text/javascript, */*; q=0.01
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Origin:https://domain.ovh
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.33 Safari/537.36
Form Data
view source
view URL encoded
{"query":{"match":{"_all":10}},"fields":"DEPET"}:

Thanks for your inputs

Body:
Try out this

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:9200/_search",
  "method": "POST",
  "headers": {
    "cache-control": "no-cache",
    "postman-token": "c24112d5-9dc4-0230-7954-01064b61be5c"
  },
  "data": "{\r\n  \"query\": {\r\n    \"match_all\": {}\r\n  }\r\n}\r\n"
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

I have used postman tool to generate this code.


问:
Same max-width for different items in complete html with css
is it possible to write a css-class in which the width is dynamicly the width of the most lengst item?

I would know how to do it in jquery (iterate through) but I need it in css / css3

答:
CSS Code to set the width dynamically

The width of all the rows will be set to the width of the longest row.

ul{
    margin: 0;
    padding: 5px;
    list-style: none;
    width:50%;
    background-color: #eee;
}

ul::after {
    clear: both;
    content: "";
    display: block;
}

li {
    background: grey none repeat scroll 0 0;
    display: block;
    float: left;
    margin: 5px;
    width: calc(50% - 10px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
    <li>row 1</li>
    <li>row 2</li>
    <li>This is the widest row 3</li>
    <li>row 4</li>
</ul></code>```

Body:
CSS Code to set the width dynamically

The width of all the rows will be set to the width of the longest row.

ul{
    margin: 0;
    padding: 5px;
    list-style: none;
    width:50%;
    background-color: #eee;
}

ul::after {
    clear: both;
    content: "";
    display: block;
}

li {
    background: grey none repeat scroll 0 0;
    display: block;
    float: left;
    margin: 5px;
    width: calc(50% - 10px);
}

<ul>
    <li>row 1</li>
    <li>row 2</li>
    <li>This is the widest row 3</li>
    <li>row 4</li>
</ul>


问:
"Add JUnit library" in Eclipes does not have "Junit 5" option
Can anyone help me to add Junit 5 in eclipse? When I create java project and add junit library it only shows Junit3 and junit4. I did not find junit5 and do not know how to set up things so that I can use Junit5 in project. I also gone through this guide, but did not understand where to setup these codes in eclipse.

Can anyone help me step by step how to implement Junit5 Test in eclipse-neon?

答: According to Eclipse bug 488566 support for JUnit 5 will not be released until Eclipse Oxygen.1 (4.7.1) planned for September 2017.</p>

ContentLicense: CC BY-SA 4.0


问:
how to access static variables using ui.xml
I have a class with some static variables like
    public static String MENU = "menu1";
How do i access the value of those variables in ui.xml ? </p>

<p>To access methods i saw something like </p>

答:
I found this question and solved it somehow later.

My class holding the global shared limits

```<code>/**
 * Class to hold shared limits for input fields
 */
public final class InputLimits {
    /**
     * private constructor that prevent instantiation.
     */
    private InputLimits() {

    }

    public static final int MAX_LENGTH = 10;

    /**

     * @return max length for GWT (is resolved at compile time no instance of class needed only method declaration)

     */

public static final int getMaxLength() {

    return MAX_LENGTH;

    }

}
</code>```

I'm using this in GWT in the following way:

```<code><ui:with field="InputLimits" type="....InputLimits"/>
<g:TextBox ui:field="text" maxLength="{InputLimits.getMaxLength}" />
</code>```

Official GWT documentation should be here:
http://www.gwtproject.org/doc/latest/DevGuideUiBinder.html#Hello_Text_Resources

Body:
I have a class with some static variables like
    public static String MENU = "menu1";
How do i access the value of those variables in ui.xml ?

To access methods i saw something like

Body:
I found this question and solved it somehow later.

My class holding the global shared limits

/**
 * Class to hold shared limits for input fields
 */
public final class InputLimits {
    /**
     * private constructor that prevent instantiation.
     */
    private InputLimits() {

    }

    public static final int MAX_LENGTH = 10;

    /**

     * @return max length for GWT (is resolved at compile time no instance of class needed only method declaration)

     */

public static final int getMaxLength() {

    return MAX_LENGTH;

    }

}

I'm using this in GWT in the following way:

<ui:with field="InputLimits" type="....InputLimits"/>
<g:TextBox ui:field="text" maxLength="{InputLimits.getMaxLength}" />

Official GWT documentation should be here:
http://www.gwtproject.org/doc/latest/DevGuideUiBinder.html#Hello_Text_Resources


问:
Getting Highest of Element Within Foreach Loop
I'm trying to find when a foreach loop gets to the end so that I can close the HTML tags and am revising this question to be a little more succinct. I am now passing the data set as an array into the function in the hopes that it might make it easier. I need to determine when one of the fields hits the maximum value which I've not been able to work out since each pass through the foreach, it "thinks" it is at the maximum until the next pass and so on.

The data set array looks something like this:

```<code>Array
(
    [0] => 3391
    [ID] => 3391
    [1] => 2
    [SubID] => 2
    [2] => 2
    [ListType] => 2
    [3] => 0
    [IndentText] => 0
    [4] => 3
    [BaseGroup] => 3
    [4] => 1
    [Quantity] => 1
)
</code>```

How can I fetch the highest SubID value as it loops through? I'm thinking along the lines of a function like this but can't work out how to get the highest value when it is run with each row.

```<code>function getMax($index, $array) {
    $array = array($array[$index]);
    return max($array);
}
</code>```

I expected to run this as $maxID = getMax("SubID", $array) but haven't figured out how to actually make it give any meaningful result but once it works, then:

```<code>if ($maxID == $row['SubID']) :
   // CLOSING HTML HERE
endif;
</code>```

... will tell the code that it is at the last row and the tags can be closed. Any ideas?

Here is the entire function but really the question is not directly related to it so I'm not sure if it will help.

```<code>function Notes($rowEntry) {
    // Create variables
    $ListType = (isset($rowEntry['ListType'])) ? $rowEntry['ListType'] : "";
    /* $ID = (isset($rowEntry['ID'])) ? $rowEntry['ID'] : ""; */
    $SubID = (isset($rowEntry['SubID'])) ? $rowEntry['SubID'] : "";
    $GroupNo = (isset($rowEntry['GroupNo'])) ? $rowEntry['GroupNo'] : "";
    $Title = (isset($rowEntry['Title'])) ? $rowEntry['Title'] : "";
    $SubPartNo = (isset($rowEntry['SubPartNo'])) ? $rowEntry['SubPartNo'] : "";
    $SubDescription = (isset($rowEntry['SubDescription'])) ? LinkAbbvr($rowEntry['SubDescription']) : " ";
    $SubPage = (isset($rowEntry['SubPage'])) ? $rowEntry['SubPage'] : "";
    // SubQuantity field is integer so, to match original hardcopy, 0 used in place of X
    // Condition below changes it back to X for display
    $SubQuantity = (isset($rowEntry['SubQuantity'])) ? $rowEntry['SubQuantity'] : "";
    $SubQuantity = ($SubQuantity == 0) ? "X" : $SubQuantity;
    // Create Edit link to SubQuantity value
    $EditSubQuantity = (isset($_SESSION['AccessLevel']) && $_SESSION['AccessLevel'] == 3)
                            ? "<a href=\"/administration/adminforms.php?FormID=33&ID=$SubID\">$SubQuantity</a>"
                            : $SubQuantity;

    // For note of a specific group by itself, ie Group 3.5890 page 98
    // Uses style .groupcaption
    if ($ListType == 1) :
        if ($GroupNo && $Title) :
            $last_groupnote = "";
            if ($Title && $GroupNo != $last_groupnote) :
                $last_groupnote = $GroupNo;

                $NotesText = "<div class=\"groupcaption\">\n";
                    $NotesText .= "<div class=\"SubTitle\">$Title</div>\n";
                $NotesText .= "</div>\n\n";

            echo $NotesText;
            endif;
        endif;

    // For indented sub-listings, ie Group 3.639 page 108
    // This lists Quantity, PartNo and Description
    // Uses style #css-subtable
    elseif ($ListType == 2) :
        global $TitleCaption;
        $NotesText = "";
        // Show Title column only once
        if ($Title != $TitleCaption) :
            $TitleCaption = $Title;
            // Close part listing row table
            $NotesText .= "</div>\n\n";
            // Open subtable and title
            $NotesText .= "<div id=\"css-subtable\">\n";
            $NotesText .= "<div class=\"RowCaption\">$Title</div>\n\n";
        endif;

        if ($SubDescription && !is_null($SubDescription)) :
            $NotesText .= "<div class=\"row\">\n";
                $NotesText .= "<div class=\"col\">$EditSubQuantity</div>\n";
                $NotesText .= "<div class=\"col\">$SubPartNo</div>\n";
                $NotesText .= "<div class=\"col\">$SubDescription</div>\n";
            $NotesText .= "</div>\n\n";
        endif;

        $subMax = getMax("SubID", $rowEntry);

        // Check to see if last row
        if ($SubID == $subMax) :
        //if ($SubID == 15) :
            // Close the subtable
            $NotesText .= "</div>\n\n";
            // Restart row table
            if ($ListType < 5) :
                $NotesText .= "<div id=\"css-table\">\n";
            elseif ($ListType > 4) :
                $NotesText .= "<div id=\"css-sublist$ListType\">\n";
            endif;
        endif;

        echo $NotesText;

    // For indented sub-listings description-only list, ie Group 1.322 page 16
    // This lists Description only
    // Uses style #css-subsingletable
    elseif ($ListType == 3) :
        global $rowCount;
        $NotesText = "";

        $rowCount++;
        // Clost main style, open new one
        if ($rowCount == 1) :
            // Close part listing row table
            $NotesText .= "</div>\n\n";
            // Open subtable and title
            $NotesText .= "<div id=\"css-subsingletable\">\n";
        endif;

        if ($SubDescription && !is_null($SubDescription)) :
            $rowCount++;
            $NotesText .= "<div class=\"row\">\n";
                $NotesText .= "<div class=\"col\">$SubDescription</div>\n";
            $NotesText .= "</div>\n\n";
        endif;

        if ($rowCount == 3) :
            $NotesText .= "</div>\n\n";
            // Restart row table
            if ($ListType < 5) :
                $NotesText .= "<div id=\"css-table\">\n";
            elseif ($ListType > 4) :
                $NotesText .= "<div id=\"css-sublist$ListType\">\n";
            endif;
        endif;
        echo $NotesText;

    // For single notes, ie Group 1.607 page 29
    // Uses style #css-partnotes
    elseif ($ListType == 4) :
        $TitleCaption = "";

        if ($Title) :
            if ($Title != $TitleCaption) :
                $TitleCaption = $Title;
                // Close part listing row table
                $NotesText = "</div>\n\n";
                    $NotesText .= "<div id=\"css-partnotes\">\n";
                        $NotesText .= "<div class=\"row\">\n";
                            $NotesText .= "<div class=\"col\">\n";
                                $NotesText .= "<div class=\"RowCaption\">$Title</div>\n";
                            $NotesText .= "</div>\n";
                        $NotesText .= "</div>\n";
                    $NotesText .= "</div>\n\n";
                // Restart row table
                if ($ListType < 5) :
                    $NotesText .= "<div id=\"css-table\">\n";
                elseif ($ListType > 4) :
                    $NotesText .= "<div id=\"css-sublist$ListType\">\n";
                endif;
                echo $NotesText;
            endif;
        endif;
    endif;
}
</code>```

The function above is being called from:

```<code>// This function used to simplify partsbook.php and partsbookdetails.php
// IN CONJUNCTION WITH ABOVE, FUNCTION PARTIALLY REPLACES OBSOLETE PartID()
function PartsList($sqlView) {
    $rowView = DBConnect($sqlView, "Multiple", "pchome_packardsimperials");
    if ($rowView) :
        $last_groupno = "";
        $last_id = "";
        $rowNumber = 0;
        foreach ($rowView as $row) :
            $rowNumber++;
            $ID = (isset($row['ID'])) ? $row['ID'] : "";
            $ListType = (isset($row['ListType'])) ? $row['ListType'] : "";
            $BaseGroup = (isset($row['BaseGroup'])) ? $row['BaseGroup'] : 0;
            $GroupNo = (isset($row['GroupNo'])) ? $row['GroupNo'] : "";
            $GroupName = (isset($row['GroupName'])) ? LinkAbbvr($row['GroupName']) : "";
            $Name = (isset($row['Name'])) ? LinkAbbvr($row['Name']) : "";
            $Title = (isset($row['Title'])) ? $row['Title'] : "";
            $PartNo = (isset($row['PartNo'])) ? $row['PartNo'] : "";

            $Models = (isset($row['Models'])) ? $row['Models'] : "";
            $Description = (isset($row['Description'])) ? LinkAbbvr($row['Description']) : " ";
            $PageNo = (isset($row['PageNo'])) ? $row['PageNo'] : "";
            $SubPage = (isset($row['SubPage'])) ? $row['SubPage'] : "";
            $RevDate = (isset($row['RevDate'])) ? $row['RevDate'] : "";
            $Edition = (isset($row['Edition'])) ? $row['Edition'] : "";

            // Choose variable for use in title of GroupNo() function
            if ($ListType < 5) :
                $ListName = $Name;
            elseif ($ListType > 4) :
                $ListName = $Title;
            endif;

            // Check to see if GroupNo is different than previous one
            if ($GroupNo != $last_groupno || $rowNumber == 1) :
                $last_groupno = $GroupNo;
                $NewGroup = TRUE;
            else :
                $NewGroup = FALSE;
            endif;

            // Show GroupNo() captions only once per group
            if ($NewGroup === TRUE) :
                GroupNo($GroupNo, $NewGroup, $ListName, $rowNumber, $ListType);
            endif;

            if ($ListType < 5) :
                // To prevent duplicates, check to see if ID is different than previous one before displaying
                if ($ID != $last_id) :
                    $last_id = $ID;
                    PartRow($row);
                endif;
                Notes($row);
            elseif ($ListType > 4) :
                SpecialRow($row);
            endif;

        endforeach;
    endif;
}
</code>```

答:
Thank you everyone for trying to help! Impossible is not a word I use often but in this case I think it applies to what I was tying to do. Once I came to terms with that, I found a workaround that seems to do the trick but through the query by way of a subquery which never occurred to me before. Here is a portion of the query which simply gives the highest value that the parts_notes table might have, then a conditional in the function compares with the row's SubID it is receiving and closes the tags when there is a match. It seems to work well so far.

```<code>SELECT DISTINCT
pl.ID,
pn.ID AS SubID,

IF(ListType,(SELECT MAX(ID)
FROM parts_notes
WHERE PageNo=108
AND ListType IS NOT NULL
AND SubPage IS NULL ),NULL) AS SubMax,

ListType,
IndentText, . . .
</code>```

Body:
I'm trying to find when a foreach loop gets to the end so that I can close the HTML tags and am revising this question to be a little more succinct. I am now passing the data set as an array into the function in the hopes that it might make it easier. I need to determine when one of the fields hits the maximum value which I've not been able to work out since each pass through the foreach, it "thinks" it is at the maximum until the next pass and so on.

The data set array looks something like this:

Array
(
    [0] => 3391
    [ID] => 3391
    [1] => 2
    [SubID] => 2
    [2] => 2
    [ListType] => 2
    [3] => 0
    [IndentText] => 0
    [4] => 3
    [BaseGroup] => 3
    [4] => 1
    [Quantity] => 1
)

How can I fetch the highest SubID value as it loops through? I'm thinking along the lines of a function like this but can't work out how to get the highest value when it is run with each row.

function getMax($index, $array) {
    $array = array($array[$index]);
    return max($array);
}

I expected to run this as $maxID = getMax("SubID", $array) but haven't figured out how to actually make it give any meaningful result but once it works, then:

if ($maxID == $row['SubID']) :
   // CLOSING HTML HERE
endif;

... will tell the code that it is at the last row and the tags can be closed. Any ideas?

Here is the entire function but really the question is not directly related to it so I'm not sure if it will help.

function Notes($rowEntry) {
    // Create variables
    $ListType = (isset($rowEntry['ListType'])) ? $rowEntry['ListType'] : "";
    /* $ID = (isset($rowEntry['ID'])) ? $rowEntry['ID'] : ""; */
    $SubID = (isset($rowEntry['SubID'])) ? $rowEntry['SubID'] : "";
    $GroupNo = (isset($rowEntry['GroupNo'])) ? $rowEntry['GroupNo'] : "";
    $Title = (isset($rowEntry['Title'])) ? $rowEntry['Title'] : "";
    $SubPartNo = (isset($rowEntry['SubPartNo'])) ? $rowEntry['SubPartNo'] : "";
    $SubDescription = (isset($rowEntry['SubDescription'])) ? LinkAbbvr($rowEntry['SubDescription']) : " ";
    $SubPage = (isset($rowEntry['SubPage'])) ? $rowEntry['SubPage'] : "";
    // SubQuantity field is integer so, to match original hardcopy, 0 used in place of X
    // Condition below changes it back to X for display
    $SubQuantity = (isset($rowEntry['SubQuantity'])) ? $rowEntry['SubQuantity'] : "";
    $SubQuantity = ($SubQuantity == 0) ? "X" : $SubQuantity;
    // Create Edit link to SubQuantity value
    $EditSubQuantity = (isset($_SESSION['AccessLevel']) && $_SESSION['AccessLevel'] == 3)
                            ? "$SubQuantity"
                            : $SubQuantity;

    // For note of a specific group by itself, ie Group 3.5890 page 98
    // Uses style .groupcaption
    if ($ListType == 1) :
        if ($GroupNo && $Title) :
            $last_groupnote = "";
            if ($Title && $GroupNo != $last_groupnote) :
                $last_groupnote = $GroupNo;

                $NotesText = "
\n";
                    $NotesText .= "
$Title
\n";
                $NotesText .= "
\n\n";

            echo $NotesText;
            endif;
        endif;

    // For indented sub-listings, ie Group 3.639 page 108
    // This lists Quantity, PartNo and Description
    // Uses style #css-subtable
    elseif ($ListType == 2) :
        global $TitleCaption;
        $NotesText = "";
        // Show Title column only once
        if ($Title != $TitleCaption) :
            $TitleCaption = $Title;
            // Close part listing row table
            $NotesText .= "
\n\n";
            // Open subtable and title
            $NotesText .= "
\n";
            $NotesText .= "
$Title
\n\n";
        endif;

        if ($SubDescription && !is_null($SubDescription)) :
            $NotesText .= "
\n";
                $NotesText .= "
$EditSubQuantity
\n";
                $NotesText .= "
$SubPartNo
\n";
                $NotesText .= "
$SubDescription
\n";
            $NotesText .= "
\n\n";
        endif;

        $subMax = getMax("SubID", $rowEntry);

        // Check to see if last row
        if ($SubID == $subMax) :
        //if ($SubID == 15) :
            // Close the subtable
            $NotesText .= "
\n\n";
            // Restart row table
            if ($ListType < 5) :
                $NotesText .= "
\n";
            elseif ($ListType > 4) :
                $NotesText .= "
\n";
            endif;
        endif;

        echo $NotesText;

    // For indented sub-listings description-only list, ie Group 1.322 page 16
    // This lists Description only
    // Uses style #css-subsingletable
    elseif ($ListType == 3) :
        global $rowCount;
        $NotesText = "";

        $rowCount++;
        // Clost main style, open new one
        if ($rowCount == 1) :
            // Close part listing row table
            $NotesText .= "
\n\n";
            // Open subtable and title
            $NotesText .= "
\n";
        endif;

        if ($SubDescription && !is_null($SubDescription)) :
            $rowCount++;
            $NotesText .= "
\n";
                $NotesText .= "
$SubDescription
\n";
            $NotesText .= "
\n\n";
        endif;

        if ($rowCount == 3) :
            $NotesText .= "
\n\n";
            // Restart row table
            if ($ListType < 5) :
                $NotesText .= "
\n";
            elseif ($ListType > 4) :
                $NotesText .= "
\n";
            endif;
        endif;
        echo $NotesText;

    // For single notes, ie Group 1.607 page 29
    // Uses style #css-partnotes
    elseif ($ListType == 4) :
        $TitleCaption = "";

        if ($Title) :
            if ($Title != $TitleCaption) :
                $TitleCaption = $Title;
                // Close part listing row table
                $NotesText = "
\n\n";
                    $NotesText .= "
\n";
                        $NotesText .= "
\n";
                            $NotesText .= "
\n";
                                $NotesText .= "
$Title
\n";
                            $NotesText .= "
\n";
                        $NotesText .= "
\n";
                    $NotesText .= "
\n\n";
                // Restart row table
                if ($ListType < 5) :
                    $NotesText .= "
\n";
                elseif ($ListType > 4) :
                    $NotesText .= "
\n";
                endif;
                echo $NotesText;
            endif;
        endif;
    endif;
}

The function above is being called from:

// This function used to simplify partsbook.php and partsbookdetails.php
// IN CONJUNCTION WITH ABOVE, FUNCTION PARTIALLY REPLACES OBSOLETE PartID()
function PartsList($sqlView) {
    $rowView = DBConnect($sqlView, "Multiple", "pchome_packardsimperials");
    if ($rowView) :
        $last_groupno = "";
        $last_id = "";
        $rowNumber = 0;
        foreach ($rowView as $row) :
            $rowNumber++;
            $ID = (isset($row['ID'])) ? $row['ID'] : "";
            $ListType = (isset($row['ListType'])) ? $row['ListType'] : "";
            $BaseGroup = (isset($row['BaseGroup'])) ? $row['BaseGroup'] : 0;
            $GroupNo = (isset($row['GroupNo'])) ? $row['GroupNo'] : "";
            $GroupName = (isset($row['GroupName'])) ? LinkAbbvr($row['GroupName']) : "";
            $Name = (isset($row['Name'])) ? LinkAbbvr($row['Name']) : "";
            $Title = (isset($row['Title'])) ? $row['Title'] : "";
            $PartNo = (isset($row['PartNo'])) ? $row['PartNo'] : "";

            $Models = (isset($row['Models'])) ? $row['Models'] : "";
            $Description = (isset($row['Description'])) ? LinkAbbvr($row['Description']) : " ";
            $PageNo = (isset($row['PageNo'])) ? $row['PageNo'] : "";
            $SubPage = (isset($row['SubPage'])) ? $row['SubPage'] : "";
            $RevDate = (isset($row['RevDate'])) ? $row['RevDate'] : "";
            $Edition = (isset($row['Edition'])) ? $row['Edition'] : "";

            // Choose variable for use in title of GroupNo() function
            if ($ListType < 5) :
                $ListName = $Name;
            elseif ($ListType > 4) :
                $ListName = $Title;
            endif;

            // Check to see if GroupNo is different than previous one
            if ($GroupNo != $last_groupno || $rowNumber == 1) :
                $last_groupno = $GroupNo;
                $NewGroup = TRUE;
            else :
                $NewGroup = FALSE;
            endif;

            // Show GroupNo() captions only once per group
            if ($NewGroup === TRUE) :
                GroupNo($GroupNo, $NewGroup, $ListName, $rowNumber, $ListType);
            endif;

            if ($ListType < 5) :
                // To prevent duplicates, check to see if ID is different than previous one before displaying
                if ($ID != $last_id) :
                    $last_id = $ID;
                    PartRow($row);
                endif;
                Notes($row);
            elseif ($ListType > 4) :
                SpecialRow($row);
            endif;

        endforeach;
    endif;
}

Body:
Thank you everyone for trying to help! Impossible is not a word I use often but in this case I think it applies to what I was tying to do. Once I came to terms with that, I found a workaround that seems to do the trick but through the query by way of a subquery which never occurred to me before. Here is a portion of the query which simply gives the highest value that the parts_notes table might have, then a conditional in the function compares with the row's SubID it is receiving and closes the tags when there is a match. It seems to work well so far.

SELECT DISTINCT
pl.ID,
pn.ID AS SubID,

IF(ListType,(SELECT MAX(ID)
FROM parts_notes
WHERE PageNo=108
AND ListType IS NOT NULL
AND SubPage IS NULL ),NULL) AS SubMax,

ListType,
IndentText, . . .


问:
How to use dot as in punctuation and not append in PHP
I'm putting a SQL query together in PHP. How do I declare a dot in punctuation?

Example code as requested:

```<code>$sql="SELECT COUNT(*) FROM Table1 WHERE LOWER(location2) REGEXP '.* .$location .*'";
</code>```

See .* is a regexp and should not be interpreted by PHP as a concatenation.

答:
This is nothing to do with PHP syntax.  Your example contains a . inside a quoted string, which PHP interprets as a . inside a quoted string.  Therefore nothing is wrong there.

What you're probably experiencing is MySQL treating the . as a wild-card operator in a regular expression.  In regular expression syntax (whether in MySQL, PHP, Perl, wherever) . is a wild-card that matches any single character.  If you want to include a literal . in your regex, you need to escape it, i.e. \..

Because you are using it inside a string inside a string, you also need to escape the \ character so that it makes it through to the regex correctly.  Without testing I would say it needs escaping twice (once for PHP and once for MySQL), e.g. "'\\\\.'" in PHP becomes '\\.' in MySQL, becomes \. in the regular expression.

(Obviously, only escape the . characters that are meant to be treated literally - I would assume the .* is meant to match any character - these should not be changed.)

OwnerDisplayName: Kevster

Body:
I'm putting a SQL query together in PHP. How do I declare a dot in punctuation?

Example code as requested:

$sql="SELECT COUNT(*) FROM Table1 WHERE LOWER(location2) REGEXP '.* .$location .*'";

See .* is a regexp and should not be interpreted by PHP as a concatenation.


问:
Equivalent of File.ReadLines(filepath) C# in Javascript
In my current C# code, I used the .NET package File.ReadLines(). Are there any ways to re-write that code in Javascript?

```<code>var csvArray = File.ReadLines(filePath).Select(x => x.Split(',')).ToArray();
</code>```

I know that LINQ Select could be used in Javascript. My current progress is on reading a CSV file. Kindly check my JS code below.

```<code>    var fs = require('fs');
    var csv = require('fast-csv');
    var filepath = $('#appFilePathInput').value();

    fs.createReadStream(filepath)
    .pipe(csv())
    .on('data', function(data){
        //Should I put the LINQ Select and Split toArray code here?
    });
    .on('data', function(data){
        console.log('Read Finished');
    });
</code>```

GOAL is to read the local CSV file to an Array in JavaScript.

Kindly help me improve my existing code since it is my first time writing code in pure Javascript.

Thank you very much!

答:
You need to replace the new line \n with a comma, then do a split by comma

```<code>var data = "Server1, Server2, Server3 \n 1.5, 2.9, 3.1"
var result = data.replace("\n", ",").split(",");
</code>```

you can check the result in the console in this fiddle https://jsfiddle.net/9oa25k2t/

Body:
In my current C# code, I used the .NET package File.ReadLines(). Are there any ways to re-write that code in Javascript?

var csvArray = File.ReadLines(filePath).Select(x => x.Split(',')).ToArray();

I know that LINQ Select could be used in Javascript. My current progress is on reading a CSV file. Kindly check my JS code below.

    var fs = require('fs');
    var csv = require('fast-csv');
    var filepath = $('#appFilePathInput').value();

    fs.createReadStream(filepath)
    .pipe(csv())
    .on('data', function(data){
        //Should I put the LINQ Select and Split toArray code here?
    });
    .on('data', function(data){
        console.log('Read Finished');
    });

GOAL is to read the local CSV file to an Array in JavaScript.

Kindly help me improve my existing code since it is my first time writing code in pure Javascript.

Thank you very much!

Body:
You need to replace the new line \n with a comma, then do a split by comma

var data = "Server1, Server2, Server3 \n 1.5, 2.9, 3.1"
var result = data.replace("\n", ",").split(",");

you can check the result in the console in this fiddle https://jsfiddle.net/9oa25k2t/


问:
What data structure should I use in objC for key-value pair when the key is numeric?
I have sample data as follows

```<code>1 -> Apple
2 -> Banana
3 -> Cherries
4 -> Guava
5 -> Apple
..........
..........
</code>```

Now, I need to store this in a data structure in objective C. Like you can see, the keys are numeric and the values are NSString type. Typically would've used dictionary but in this case, I can't because the key is not a string.

I instead started to use NSMapTable. Only problem with NSMapTable is, there is no easy way to manipulate things such as, [NSDictionary allKeys] etc.

I did see something called as [Maptable keyEnumerator] but keyEnumerator doesn't look like it can be sorted. So I am running out of ideas on what is the best data structure to use in this situation. Any suggestion is welcome.

答:
You can use NSNumber for your keys:

```<code>NSDictionary *myDic = @{
                            @(1): @"Apple",
                            @(2): @"Banana",
                            @(3): @"Cherries",
                            @(4): @"Guava"

                            };
</code>```

Body:
I have sample data as follows

1 -> Apple
2 -> Banana
3 -> Cherries
4 -> Guava
5 -> Apple
..........
..........

Now, I need to store this in a data structure in objective C. Like you can see, the keys are numeric and the values are NSString type. Typically would've used dictionary but in this case, I can't because the key is not a string.

I instead started to use NSMapTable. Only problem with NSMapTable is, there is no easy way to manipulate things such as, [NSDictionary allKeys] etc.

I did see something called as [Maptable keyEnumerator] but keyEnumerator doesn't look like it can be sorted. So I am running out of ideas on what is the best data structure to use in this situation. Any suggestion is welcome.

Body:
You can use NSNumber for your keys:

NSDictionary *myDic = @{
                            @(1): @"Apple",
                            @(2): @"Banana",
                            @(3): @"Cherries",
                            @(4): @"Guava"

                            };


问:
dplyr - filter by group size
What is the best way to filter a data.frame to only get groups of say size 5?

So my data looks as follows:

```<code>require(dplyr)
n <- 1e5
x <- rnorm(n)
# Category size ranging each from 1 to 5
cat <- rep(seq_len(n/3), sample(1:5, n/3, replace = TRUE))[1:n]

dat <- data.frame(x = x, cat = cat)
</code>```

The dplyr way i could come up with was

```<code>dat <- group_by(dat, cat)

system.time({
  out1 <- dat %>% filter(n() == 5L)
})
#    user  system elapsed
#   1.157   0.218   1.497
</code>```

But this is very slow... Is there a better way in dplyr?

So far my workaround solutions looks as follows:

```<code>system.time({
  all_ind <- rep(seq_len(n_groups(dat)), group_size(dat))
  take_only <- which(group_size(dat) == 5L)
  out2 <- dat[all_ind %in% take_only, ]
})
#    user  system elapsed
#   0.026   0.008   0.036
all.equal(out1, out2) # TRUE
</code>```

But this doesn't feel very dplyr like...

答:
Here's another dplyr approach you can try

```<code>semi_join(dat, count(dat, cat) %>% filter(n == 5), by = "cat")
</code>```

--

Here's another approach based on OP's original approach with a little modification:

```<code>n <- 1e5
x <- rnorm(n)
# Category size ranging each from 1 to 5
cat <- rep(seq_len(n/3), sample(1:5, n/3, replace = TRUE))[1:n]

dat <- data.frame(x = x, cat = cat)

# second data set for the dt approch
dat2 <- data.frame(x = x, cat = cat)

sol_floo0 <- function(dat){
  dat <- group_by(dat, cat)
  all_ind <- rep(seq_len(n_groups(dat)), group_size(dat))
  take_only <- which(group_size(dat) == 5L)
  dat[all_ind %in% take_only, ]
}

sol_floo0_v2 <- function(dat){
  g <- group_by(dat, cat) %>% group_size()
  ind <- rep(g == 5, g)
  dat[ind, ]
}

microbenchmark::microbenchmark(times = 10,
                               sol_floo0(dat),
                               sol_floo0_v2(dat2))
#Unit: milliseconds
#               expr      min       lq     mean   median       uq      max neval cld
#     sol_floo0(dat) 43.72903 44.89957 45.71121 45.10773 46.59019 48.64595    10   b
# sol_floo0_v2(dat2) 29.83724 30.56719 32.92777 31.97169 34.10451 38.31037    10  a
all.equal(sol_floo0(dat), sol_floo0_v2(dat2))
#[1] TRUE
</code>```

Title: dplyr - filter by group size

Body:
What is the best way to filter a data.frame to only get groups of say size 5?

So my data looks as follows:

require(dplyr)
n <- 1e5
x <- rnorm(n)
# Category size ranging each from 1 to 5
cat <- rep(seq_len(n/3), sample(1:5, n/3, replace = TRUE))[1:n]

dat <- data.frame(x = x, cat = cat)

The dplyr way i could come up with was

dat <- group_by(dat, cat)

system.time({
  out1 <- dat %>% filter(n() == 5L)
})
#    user  system elapsed
#   1.157   0.218   1.497

But this is very slow... Is there a better way in dplyr?

So far my workaround solutions looks as follows:

system.time({
  all_ind <- rep(seq_len(n_groups(dat)), group_size(dat))
  take_only <- which(group_size(dat) == 5L)
  out2 <- dat[all_ind %in% take_only, ]
})
#    user  system elapsed
#   0.026   0.008   0.036
all.equal(out1, out2) # TRUE

But this doesn't feel very dplyr like...

Body:
Here's another dplyr approach you can try

semi_join(dat, count(dat, cat) %>% filter(n == 5), by = "cat")

--

Here's another approach based on OP's original approach with a little modification:

n <- 1e5
x <- rnorm(n)
# Category size ranging each from 1 to 5
cat <- rep(seq_len(n/3), sample(1:5, n/3, replace = TRUE))[1:n]

dat <- data.frame(x = x, cat = cat)

# second data set for the dt approch
dat2 <- data.frame(x = x, cat = cat)

sol_floo0 <- function(dat){
  dat <- group_by(dat, cat)
  all_ind <- rep(seq_len(n_groups(dat)), group_size(dat))
  take_only <- which(group_size(dat) == 5L)
  dat[all_ind %in% take_only, ]
}

sol_floo0_v2 <- function(dat){
  g <- group_by(dat, cat) %>% group_size()
  ind <- rep(g == 5, g)
  dat[ind, ]
}

microbenchmark::microbenchmark(times = 10,
                               sol_floo0(dat),
                               sol_floo0_v2(dat2))
#Unit: milliseconds
#               expr      min       lq     mean   median       uq      max neval cld
#     sol_floo0(dat) 43.72903 44.89957 45.71121 45.10773 46.59019 48.64595    10   b
# sol_floo0_v2(dat2) 29.83724 30.56719 32.92777 31.97169 34.10451 38.31037    10  a
all.equal(sol_floo0(dat), sol_floo0_v2(dat2))
#[1] TRUE


问:
How do I handle claim check with cqrs
TL;DR:
 1. Am I creating an anti-pattern?
 2. What is the best way to handle a claim check with CQRS?

I have several entry points in my system (webapi passing in json and xml), as well as through the file system with fixed-length files.

I am using Rebus with MSMQ and Sql server to manage my messaging.  The data can be larger than 4mb (MSMQ's max message size if I believe).  When the system receives a file I convert it into a stream and create a command that implements IAttachmentCommand as below:

```<code>public interface IAttachmentCommand : ICommand
{
    Stream Attachment { get; }

    IClaimCheckCommand ToClaimCheck(string attachmentId);
}

public interface IClaimCheckCommand : ICommand
{
    string AttachmentId { get; }
}
</code>```

I then send it using a command bus (using Rebus).  If the command is of type IAttachmentCommand I create an attachment in the rebus databus table and return a new IAttachmentCommand using ToClaimCheck on the original command.  The AttachmentCommand is effectively a carbon copy of the original command, except it now has the attachmentId instead of the data.

I will then call send in my Rebus bus with my new AttachmentId as below:

```<code>public void Send<TCommand>(TCommand command) where TCommand : ICommand
{
  if (command is IAttachmentCommand)
  {
    var cmd = command as IAttachmentCommand;
    var task = CreateAttachment(cmd);  // method excluded, but persists to Rebus DataBus and returns AttachmentId
    var claimCheck = task.Result;
    _activator.Bus.Send(claimCheck);
  }
  else
  {
    _activator.Bus.Send(command);
  }
}
</code>```

This seems to be working, although I am happy to have my code pulled to shreds.  I can send commands, apply the events that are generated by my aggregate roots, persist to the event store etc etc.

I simply pick up a file from a webapi call or the file system, create a command and send it off with my command bus.

In a separate windows service I have a command dispatcher monitoring MSMQ for these messages.  When a message comes in it will then iterate through however many CommandValidationHandlers there are to validate the command.  CommandValidationHandlers implement the following:

```<code>public interface ICommandValidationHandler<in TCommand> where TCommand : ICommand
{
   ValidationResult Validate(TCommand command);
}
</code>```

ValidationResult effectively returns a collection of errors.  These errors are logged, published as an InvalidCommand event that contains the Command info and the errors - this then allows me to have any subscribers that are listening pick up the event - send a mail or call a web service etc to say that the message failed, with the reasons.  If the command is invalid an exception is then thrown and the process stops.

My concern is that on validation I have the attachmentId, and have to retrieve the file, which is then validated, for example against an xsd.

From there I need to deserialize it to an object (generally a collection of financial transactions with a header which contains meta data such as no of transactions etc) and perform extra validation on data in the object.

Once this validation is complete I need to iterate through the collection of transactions in the object and send these to their relevant bounded contexts using the command bus, and further processing takes place.

It seems in this instance that I will be hitting the claim store a number of times - once for each validation handler (although I guess this could be resolved with a composite collection of validators), but then again in the Command Handler once validation has taken place.

In the various Event Handlers I have that need access to all the data I need to retrieve the data from the claim store each time and deserialize a number of times.

This seems like code-smell to me.  Should I consider caching the file the first time I retrieve it and clear it from cache once all event handlers have finished their work?

Does anybody have better suggestions?

答:
From what I understand about your problem the question is really: "should I use a caching mechanism for reading the claim store on the validation handlers?"

In your case, because the data in the claim store is immutable, you could cache it as long as you need it. That is the beauty of the immutable data: is forever cacheable.

To implement the caching mechanism you could use the decorator pattern over the claim store and switch to the cached version in your composition root in the dependency container. In this way you can anytime switch back to the uncached one.

You could cache it even more, you could cache even the result of the validation if the validated data does not ever change and it is repeated over time.

Title: How do I handle claim check with cqrs

Body:
TL;DR:
 1. Am I creating an anti-pattern?
 2. What is the best way to handle a claim check with CQRS?

I have several entry points in my system (webapi passing in json and xml), as well as through the file system with fixed-length files.

I am using Rebus with MSMQ and Sql server to manage my messaging.  The data can be larger than 4mb (MSMQ's max message size if I believe).  When the system receives a file I convert it into a stream and create a command that implements IAttachmentCommand as below:

public interface IAttachmentCommand : ICommand
{
    Stream Attachment { get; }

    IClaimCheckCommand ToClaimCheck(string attachmentId);
}

public interface IClaimCheckCommand : ICommand
{
    string AttachmentId { get; }
}

I then send it using a command bus (using Rebus).  If the command is of type IAttachmentCommand I create an attachment in the rebus databus table and return a new IAttachmentCommand using ToClaimCheck on the original command.  The AttachmentCommand is effectively a carbon copy of the original command, except it now has the attachmentId instead of the data.

I will then call send in my Rebus bus with my new AttachmentId as below:

public void Send<TCommand>(TCommand command) where TCommand : ICommand
{
  if (command is IAttachmentCommand)
  {
    var cmd = command as IAttachmentCommand;
    var task = CreateAttachment(cmd);  // method excluded, but persists to Rebus DataBus and returns AttachmentId
    var claimCheck = task.Result;
    _activator.Bus.Send(claimCheck);
  }
  else
  {
    _activator.Bus.Send(command);
  }
}

This seems to be working, although I am happy to have my code pulled to shreds.  I can send commands, apply the events that are generated by my aggregate roots, persist to the event store etc etc.

I simply pick up a file from a webapi call or the file system, create a command and send it off with my command bus.

In a separate windows service I have a command dispatcher monitoring MSMQ for these messages.  When a message comes in it will then iterate through however many CommandValidationHandlers there are to validate the command.  CommandValidationHandlers implement the following:

public interface ICommandValidationHandler<in TCommand> where TCommand : ICommand
{
   ValidationResult Validate(TCommand command);
}

ValidationResult effectively returns a collection of errors.  These errors are logged, published as an InvalidCommand event that contains the Command info and the errors - this then allows me to have any subscribers that are listening pick up the event - send a mail or call a web service etc to say that the message failed, with the reasons.  If the command is invalid an exception is then thrown and the process stops.

My concern is that on validation I have the attachmentId, and have to retrieve the file, which is then validated, for example against an xsd.

From there I need to deserialize it to an object (generally a collection of financial transactions with a header which contains meta data such as no of transactions etc) and perform extra validation on data in the object.

Once this validation is complete I need to iterate through the collection of transactions in the object and send these to their relevant bounded contexts using the command bus, and further processing takes place.

It seems in this instance that I will be hitting the claim store a number of times - once for each validation handler (although I guess this could be resolved with a composite collection of validators), but then again in the Command Handler once validation has taken place.

In the various Event Handlers I have that need access to all the data I need to retrieve the data from the claim store each time and deserialize a number of times.

This seems like code-smell to me.  Should I consider caching the file the first time I retrieve it and clear it from cache once all event handlers have finished their work?

Does anybody have better suggestions?


问:
I am trying to get a jquery plug in to work on my wordpress site
I am trying to get this plug in to work: https://gopalraju.github.io/gridtab/#features . Here is the test site I am using: http://testing.bdanzer.com/ . I enqueued the files via the functions.php file and added the script tag in the footer.php. They show up enqueued on the site but the jquery plug in isn't working? Here is the code:

Functions.php file:

```<code>function bdanzer_scripts() {
    wp_enqueue_script( 'gridtabready.js', get_stylesheet_directory_uri() . '/bdanzer/gridtab/gridtabready.js', array( 'jquery' ), '1.0.0', false );
    wp_enqueue_script( 'gridtab.js', get_stylesheet_directory_uri() . '/bdanzer/gridtab/gridtab.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_style( 'gridtab.css', get_template_directory_uri() . '/bdanzer/gridtab/gridtab.min.css' );
}
add_action( 'wp_enqueue_scripts', 'bdanzer_scripts', 11);
</code>```

Footer.php file:

```<code><script>
      $(document).ready(function() {
          $('.gridtab-1').gridtab({
              grid: 6,
              tabPadding: 0,
              borderWidth: 10,
              contentPadding: 40,
              responsive: [{
                  breakpoint: 991,
                  settings: {
                      grid: 4,
                      contentPadding: 30
                  }
              }, {
                  breakpoint: 767,
                  settings: {
                      grid: 3,
                      contentPadding: 20
                  }
              }, {
                  breakpoint: 520,
                  settings: {
                      grid: 2
                  }
              }]
          });

          $('.gridtab-2').gridtab({
              grid: 4,
              config:{
                layout: 'tab'
              },
              callbacks: {
                  open: function() {
                      console.log('open');
                  },
                  close: function() {
                      console.log('close');
                  }
              },
              responsive: [{
                  breakpoint: 991,
                  settings: {

                      grid: 3,
                  }
              }, {
                  breakpoint: 767,
                  settings: {
                      grid: 2,
                  }
              }, {
                  breakpoint: 520,
                  settings: {
                      grid: 1,
                  }
              }]
          });
          $('.gridtab-3').gridtab({
              grid: 3,
              config:{
                layout:'tab',
                activeTab:1,
                showClose:true,
                showArrows:true,
              }
          });

          $('.gridtab-4').gridtab({
              grid: 6,
              tabPadding: 0,
              borderWidth: 10,
              contentPadding: 40,
              config:{
                scrollToTab:true,
                showClose:true,
                showArrows:true
              },
              responsive: [{
                  breakpoint: 991,
                  settings: {
                      grid: 4,
                      contentPadding: 30
                  }
              }, {
                  breakpoint: 767,
                  settings: {
                      grid: 3,
                  }
              }, {
                  breakpoint: 520,
                  settings: {
                      grid: 2
                  }
              }]
          });
          $('.gridtab-5').gridtab({
              grid: 3,
              config:{
                layout:'tab',
                activeTab:1,
                keepOpen:true,
                showClose:true,
                showArrows:true,
                scrollToTab:true,
              }
          });
          $('.gridtab-6').gridtab({
              grid: 3,
              config:{
                layout:'tab',
                activeTab:1,
                showClose:true,
                showArrows:true,
                scrollToTab:true,
              }
          });
      });
    </script>
</code>```

答:
Check your functions.php file, seems like you have enqueued the scripts wrongly. If you take a look at the source code (ctrl+u in Chrome) of your testing page you will see the following script enqueued thus:

```<code><script type="text/rocketscript" data-rocketsrc='http://testing.bdanzer.com/wp-includes/js/jquery/jquery.js?ver=1.12.4'></script>
<script type="text/rocketscript" data-rocketsrc='http://testing.bdanzer.com/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.4.1'></script>
<script type="text/rocketscript" data-rocketsrc='http://testing.bdanzer.com/wp-content/themes/popperscores-master/bdanzer/gridtab/gridtabready.js?ver=1.0.0'></script>
</code>```

First, your script type reads type="text/rocketscript" rather than "text/javascript".  I'm not sure what you intend to achieve by that.

Secondly, you have a syntax error in calling script files from your server. You are referencing your scripts via data-rocketsrc='...' rather than src='...'
You should take a look at that an all scripts you are referencing this way. perhaps this will help solve the problems.

Body:
I am trying to get this plug in to work: https://gopalraju.github.io/gridtab/#features . Here is the test site I am using: http://testing.bdanzer.com/ . I enqueued the files via the functions.php file and added the script tag in the footer.php. They show up enqueued on the site but the jquery plug in isn't working? Here is the code:

Functions.php file:

function bdanzer_scripts() {
    wp_enqueue_script( 'gridtabready.js', get_stylesheet_directory_uri() . '/bdanzer/gridtab/gridtabready.js', array( 'jquery' ), '1.0.0', false );
    wp_enqueue_script( 'gridtab.js', get_stylesheet_directory_uri() . '/bdanzer/gridtab/gridtab.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_style( 'gridtab.css', get_template_directory_uri() . '/bdanzer/gridtab/gridtab.min.css' );
}
add_action( 'wp_enqueue_scripts', 'bdanzer_scripts', 11);

Footer.php file:

Body:
Check your functions.php file, seems like you have enqueued the scripts wrongly. If you take a look at the source code (ctrl+u in Chrome) of your testing page you will see the following script enqueued thus:

<script type="text/rocketscript" data-rocketsrc='http://testing.bdanzer.com/wp-includes/js/jquery/jquery.js?ver=1.12.4'></script>
<script type="text/rocketscript" data-rocketsrc='http://testing.bdanzer.com/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.4.1'></script>
<script type="text/rocketscript" data-rocketsrc='http://testing.bdanzer.com/wp-content/themes/popperscores-master/bdanzer/gridtab/gridtabready.js?ver=1.0.0'></script>

First, your script type reads type="text/rocketscript" rather than "text/javascript".  I'm not sure what you intend to achieve by that.

Secondly, you have a syntax error in calling script files from your server. You are referencing your scripts via data-rocketsrc='...' rather than src='...'
You should take a look at that an all scripts you are referencing this way. perhaps this will help solve the problems.


问:
Add Line Number to existing HTML
I'm trying to add line numbers to existing html with unequal line height - many types of font size and also images.
each line look like -

```<code><div id="1"><right><span>line 1</span></right></div>
<div id="2"><right><span>line 2</span></right></div>
<div id="3"><right><span>line 3</span></right></div>
</code>```

is there simple way to add line numbers that will be vertically align?
thanks

答:
Maybe a little automated paragraph counter.

$(document).ready(function() {
  var maxNum = 0;//how many lines should be prepared (Takin in considersation, there would be more wrappers)
  $(".NumeredTextBlock").each(function() {//create counter for each .NumeredTextBlock wrapper
    var line = 1;//start with number 1
    $("p", this).each(function() {//look for paragraph elements inside wrapper
      $(this).addClass("line" + line);//add class with line number
      line++;
      if (maxNum < line) maxNum = line;//set the maximum number of lines used in HTML DOM for wrapper
    });
  });
  var prepStyle = "";//prepare css style with line numbering
  while (maxNum--) {//prepare as many styles as the max number in document
    prepStyle += ".line" + maxNum + ":before{content:'" + maxNum + "'}";
  }
  $("#numbers").html(prepStyle);//add prepared styles to the HTML DOM
  console.log("resulting generated ")
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.NumeredTextBlock p {
  padding-left: 50px;
  position: relative;
}

.NumeredTextBlock p:before {
  display: block;
  position: absolute;
  left: 5px;
}</code>```

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna

Lorem ipsum dol

Lorem

```

Title: Add Line Number to existing HTML

Body:
I'm trying to add line numbers to existing html with unequal line height - many types of font size and also images.
each line look like -

<right>line 1</right>

<right>line 2</right>

<right>line 3</right>

is there simple way to add line numbers that will be vertically align?
thanks

Body:
Maybe a little automated paragraph counter.

$(document).ready(function() {
  var maxNum = 0;//how many lines should be prepared (Takin in considersation, there would be more wrappers)
  $(".NumeredTextBlock").each(function() {//create counter for each .NumeredTextBlock wrapper
    var line = 1;//start with number 1
    $("p", this).each(function() {//look for paragraph elements inside wrapper
      $(this).addClass("line" + line);//add class with line number
      line++;
      if (maxNum < line) maxNum = line;//set the maximum number of lines used in HTML DOM for wrapper
    });
  });
  var prepStyle = "";//prepare css style with line numbering
  while (maxNum--) {//prepare as many styles as the max number in document
    prepStyle += ".line" + maxNum + ":before{content:'" + maxNum + "'}";
  }
  $("#numbers").html(prepStyle);//add prepared styles to the HTML DOM
  console.log("resulting generated <style id='numbers'>"+prepStyle+"</style>")
});

.NumeredTextBlock p {
  padding-left: 50px;
  position: relative;
}

.NumeredTextBlock p:before {
  display: block;
  position: absolute;
  left: 5px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="NumeredTextBlock">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo</p>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna</p>
  <p>Lorem ipsum dol</p>
  <p>Lorem</p>
</div>
<style id="numbers"></style>


问:
Forcing unaligned bitfield packing in MSVC
I've a struct of bitfields that add up to 48 bits. On GCC this correctly results in a 6 byte structure, but in MSVC the structure comes out 8 bytes. I need to find some way to force MSVC to pack the struct properly, both for interoperability and because it's being used in a memory-critical environment.

The struct seen below consists of three 15-bit numbers, one 2-bit number, and a 1-bit sign. 15+15+15+2+1 = 48, so in theory it should fit into six bytes, right?

```<code>struct S
{
  unsigned short a:15;
  unsigned short b:15;
  unsigned short c:15;
  unsigned short d:2;
  unsigned short e:1;
};
</code>```

However, compiling this on both GCC and MSVC results in sizeof(S) == 8. Thinking that this might have to do with alignment, I tried using #pragma pack(1) before the struct declaration, telling the compiler to back to byte, not int, boundaries. On GCC, this worked, resulting in sizeof(S) == 6.

However, on MSVC05, the sizeof still came out to 8, even with pack(1) set! After reading this other SO answer, I tried replacing unsigned short d with unsigned char and unsigned short e with bool. The result is sizeof(S) == 7!

I found that if I split d into two one-bit fields and wedged them in between the other members, the struct finally packed properly.

```<code>struct S
{
  unsigned short a:15;
  unsigned short dHi : 1;
  unsigned short b:15;
  unsigned short dLo : 1;
  unsigned short c:15;
  unsigned short e:1;
};

printf( "%d\n", sizeof(S) ); // "6"
</code>```

But having d split like that is cumbersome and causes trouble for me later on when I have to work on the struct.  Is there some way I can force MSVC to pack this struct into 6 bytes, exactly as GCC does?

答:
If you use the type "unsigned __int64" to declare all elements of the structure, you'll get an object with sizeof(S)=8, but the last two bytes will be unused and the first six will contain the data in the format you want.

Alternatively, if you can accept some structure reordering, this will work

```<code>#pragma pack(1)
struct S3
{
  unsigned int a:15;
  unsigned int b:15;
  unsigned int d:2;
  unsigned short c:15;
  unsigned short e:1;
};
</code>```

Body:
I've a struct of bitfields that add up to 48 bits. On GCC this correctly results in a 6 byte structure, but in MSVC the structure comes out 8 bytes. I need to find some way to force MSVC to pack the struct properly, both for interoperability and because it's being used in a memory-critical environment.

The struct seen below consists of three 15-bit numbers, one 2-bit number, and a 1-bit sign. 15+15+15+2+1 = 48, so in theory it should fit into six bytes, right?

struct S
{
  unsigned short a:15;
  unsigned short b:15;
  unsigned short c:15;
  unsigned short d:2;
  unsigned short e:1;
};

However, compiling this on both GCC and MSVC results in sizeof(S) == 8. Thinking that this might have to do with alignment, I tried using #pragma pack(1) before the struct declaration, telling the compiler to back to byte, not int, boundaries. On GCC, this worked, resulting in sizeof(S) == 6.

However, on MSVC05, the sizeof still came out to 8, even with pack(1) set! After reading this other SO answer, I tried replacing unsigned short d with unsigned char and unsigned short e with bool. The result is sizeof(S) == 7!

I found that if I split d into two one-bit fields and wedged them in between the other members, the struct finally packed properly.

struct S
{
  unsigned short a:15;
  unsigned short dHi : 1;
  unsigned short b:15;
  unsigned short dLo : 1;
  unsigned short c:15;
  unsigned short e:1;
};

printf( "%d\n", sizeof(S) ); // "6"

But having d split like that is cumbersome and causes trouble for me later on when I have to work on the struct.  Is there some way I can force MSVC to pack this struct into 6 bytes, exactly as GCC does?

Body:
If you use the type "unsigned __int64" to declare all elements of the structure, you'll get an object with sizeof(S)=8, but the last two bytes will be unused and the first six will contain the data in the format you want.

Alternatively, if you can accept some structure reordering, this will work

#pragma pack(1)
struct S3
{
  unsigned int a:15;
  unsigned int b:15;
  unsigned int d:2;
  unsigned short c:15;
  unsigned short e:1;
};


答:
By inspiring from this question, I have developed a solution for your question. You can use the counter-reset and counter-increment property to achieve this

<right>line 1</right>

<right>line 2</right>

<right>line 3</right>

```

Title: Add Line Number to existing HTML

Body:
By inspiring from this question, I have developed a solution for your question. You can use the counter-reset and counter-increment property to achieve this

<html>
    <head>
        <style>
            .container {
              counter-reset: line;
            }
            .container .lineNum {
                display: block;
                line-height: 1.5rem;
            }

            .container .lineNum:before {
                counter-increment: line;
                content: counter(line);
                display: inline-block;
                margin-right: .5em;
            }
        </style>
    </head>
<body>
    <div class="container">
        <div id="1" class="lineNum"><right><span>line 1</span></right></div>
        <div id="2" class="lineNum"><right><span>line 2</span></right></div>
        <div id="3" class="lineNum"><right><span>line 3</span></right></div>
    </div>
</body>

</html>


问:
Writing extensible OWIN authentication
I'm working on a set of web services. I've implemented a custom OWIN authentication based on my company's security, so now the Authorize attribute works.

```<code>[Authorize]// It's working!
</code>```

I want to package it up for others, but I want to support roles first (or at least have a plan/recommendation for how to support roles). Unfortunately, my company doesn't have a standard way of handling roles, so different services (or applications) may take different approaches.

```<code>[Authorize("Member")]// It's not working. :(
</code>```

What is the best approach to make my authentication middleware easily extensible? My particular needs are geared towards supporting roles, but something more generic is fine. Some thoughts I've had:

I could expect them to extend my authentication.

This requires more maintenance by the developers.

Removes a large chunk of the value in making what I've written reusable.

I could provide events to hook into.

Many of the pre-built authentications seem to do something like this. They accept a provider in their options, and that provider supports a handful of events.

I'm not familiar with this approach; I'm not sure if it's the best solution.

My current options object is empty (like many tutorials) and I'm hesitant to change that.

I haven't written (and hardly consumed) any events before, so this would be new territory for me personally.

I'm inclined towards the latter approach, but I'm really just shooting in the dark. I'd greatly appreciate a confident confirmation of what would work or has worked best.

答:
To support a custom attribute like [Authorize("Member")] you can extend the attributes and write a custom one. Extend the System.Web.Http.AuthorizeAttribute class and perform all checks your need to do.

This explains how to do it:

https://www.codeproject.com/Tips/376810/ASP-NET-WEB-API-Custom-Authorize-and-Exception-Han

And this is an implementation in our solution.

```<code>public class ClaimsAuthorize : System.Web.Mvc.AuthorizeAttribute
    {
        public string PhenixPermissions { get; set; }
        public string[] NeededPermissions;

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            Logger.Logger.Trace("ClaimsAuthorize.AuthorizeCore");

            NeededPermissions = PhenixPermissions.Split(',');

            if (!(httpContext.User.Identity is ClaimsIdentity))
            {
                return false;
            }

            var claimsIdentity = httpContext.User.Identity as ClaimsIdentity;
            Claim encodedPermissions = claimsIdentity.FindFirst(ConfigurationManager.AppSettings["ApplicationPermissionsKey"]);
            string applicationId = ClaimsHelper.GetClaimValue("audience");

            if (encodedPermissions == null)
            {
                Logger.Logger.Warn("No PhenixPermissions found. Are you logged in?");
                return false;
            }

            var tenant = AppManager.GetApplication(applicationId);

            List<string> decodedPermissions = PermissionsDecodeHelper.BitDecodePermissions(tenant.ConnectionString, encodedPermissions.Value);

            bool hasRights = false;

            foreach (var neededPermission in NeededPermissions)
            {
                if (decodedPermissions.FirstOrDefault(x => x == neededPermission) != null)
                {
                    Logger.Logger.Debug(string.Format("User '{0}' authorized to access view '{1}'.", claimsIdentity.Name.ToString(), httpContext.Request.FilePath));
                    hasRights = true;
                }
            }

            return hasRights;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            Logger.Logger.Trace("ClaimsAuthorize.HandleUnauthorizedRequest");

            Logger.Logger.Warn(string.Format("Unauthorized to access '{0}'.", filterContext.Controller));

            filterContext.Controller.TempData["ErrorCode"] = "0123456789";
            filterContext.Controller.TempData["ErrorMessage"] = string.Format("'{0}' is not authorized to access access view '{1}'", HttpContext.Current.User.Identity.Name.ToString(), filterContext.Controller);

            filterContext.Result = new RedirectResult("~/Home/Error");
        }
    }
</code>```

Some remarks: the PhenixPermissions is the string that comes in when using the attribute like [ClaimsAuthorize(PhenixPermissions = "ConsultExternalLink")]

The rest is some specific logic for our application but you should get it.

Just return AuthorizeCore true or false when allowed to call the Controller, API, etc...

Hope this helps

Title: Writing extensible OWIN authentication

Body:
I'm working on a set of web services. I've implemented a custom OWIN authentication based on my company's security, so now the Authorize attribute works.

[Authorize]// It's working!

I want to package it up for others, but I want to support roles first (or at least have a plan/recommendation for how to support roles). Unfortunately, my company doesn't have a standard way of handling roles, so different services (or applications) may take different approaches.

[Authorize("Member")]// It's not working. :(

What is the best approach to make my authentication middleware easily extensible? My particular needs are geared towards supporting roles, but something more generic is fine. Some thoughts I've had:

I could expect them to extend my authentication.

This requires more maintenance by the developers.

Removes a large chunk of the value in making what I've written reusable.

I could provide events to hook into.

Many of the pre-built authentications seem to do something like this. They accept a provider in their options, and that provider supports a handful of events.

I'm not familiar with this approach; I'm not sure if it's the best solution.

My current options object is empty (like many tutorials) and I'm hesitant to change that.

I haven't written (and hardly consumed) any events before, so this would be new territory for me personally.

I'm inclined towards the latter approach, but I'm really just shooting in the dark. I'd greatly appreciate a confident confirmation of what would work or has worked best.

Body:
To support a custom attribute like [Authorize("Member")] you can extend the attributes and write a custom one. Extend the System.Web.Http.AuthorizeAttribute class and perform all checks your need to do.

This explains how to do it:

https://www.codeproject.com/Tips/376810/ASP-NET-WEB-API-Custom-Authorize-and-Exception-Han

And this is an implementation in our solution.

public class ClaimsAuthorize : System.Web.Mvc.AuthorizeAttribute
    {
        public string PhenixPermissions { get; set; }
        public string[] NeededPermissions;

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            Logger.Logger.Trace("ClaimsAuthorize.AuthorizeCore");

            NeededPermissions = PhenixPermissions.Split(',');

            if (!(httpContext.User.Identity is ClaimsIdentity))
            {
                return false;
            }

            var claimsIdentity = httpContext.User.Identity as ClaimsIdentity;
            Claim encodedPermissions = claimsIdentity.FindFirst(ConfigurationManager.AppSettings["ApplicationPermissionsKey"]);
            string applicationId = ClaimsHelper.GetClaimValue("audience");

            if (encodedPermissions == null)
            {
                Logger.Logger.Warn("No PhenixPermissions found. Are you logged in?");
                return false;
            }

            var tenant = AppManager.GetApplication(applicationId);

            List<string> decodedPermissions = PermissionsDecodeHelper.BitDecodePermissions(tenant.ConnectionString, encodedPermissions.Value);

            bool hasRights = false;

            foreach (var neededPermission in NeededPermissions)
            {
                if (decodedPermissions.FirstOrDefault(x => x == neededPermission) != null)
                {
                    Logger.Logger.Debug(string.Format("User '{0}' authorized to access view '{1}'.", claimsIdentity.Name.ToString(), httpContext.Request.FilePath));
                    hasRights = true;
                }
            }

            return hasRights;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            Logger.Logger.Trace("ClaimsAuthorize.HandleUnauthorizedRequest");

            Logger.Logger.Warn(string.Format("Unauthorized to access '{0}'.", filterContext.Controller));

            filterContext.Controller.TempData["ErrorCode"] = "0123456789";
            filterContext.Controller.TempData["ErrorMessage"] = string.Format("'{0}' is not authorized to access access view '{1}'", HttpContext.Current.User.Identity.Name.ToString(), filterContext.Controller);

            filterContext.Result = new RedirectResult("~/Home/Error");
        }
    }

Some remarks: the PhenixPermissions is the string that comes in when using the attribute like [ClaimsAuthorize(PhenixPermissions = "ConsultExternalLink")]

The rest is some specific logic for our application but you should get it.

Just return AuthorizeCore true or false when allowed to call the Controller, API, etc...

Hope this helps


问:
Incorrect syntax near '.'. Sql Server 2008
I'm trying to do a SQL query Join with Function it gives me error this error:

```<code>SELECT *
  FROM Tbl a
  CROSS APPLY V_TBL_STR(a.Number)
</code>```

What can be the error?
Thanks

答:
Please try & let me know.

```<code> SELECT *
 FROM
 Tbl AS a
 CROSS APPLY dbo.V_TBL_STR(a.Number) AS V
</code>```

This is sample. I only have removed your function & put static value to check. It works for you then modify your sql or may be something problem with your sql

```<code> SELECT *
 FROM Tbl
 CROSS APPLY (SELECT 'A' AS ABC UNION SELECT 'B' AS ABC) AS A
</code>```

Body:
I'm trying to do a SQL query Join with Function it gives me error this error:

SELECT *
  FROM Tbl a
  CROSS APPLY V_TBL_STR(a.Number)

What can be the error?
Thanks

Body:
Please try & let me know.

 SELECT *
 FROM
 Tbl AS a
 CROSS APPLY dbo.V_TBL_STR(a.Number) AS V

This is sample. I only have removed your function & put static value to check. It works for you then modify your sql or may be something problem with your sql

 SELECT *
 FROM Tbl
 CROSS APPLY (SELECT 'A' AS ABC UNION SELECT 'B' AS ABC) AS A


问:
Storing and extracting data in hashes with cucumber/capybara
I have a lot of tests with different login credentials on cucumber/capybara/site_prism, which are quite messy. I want to unify them as much as possible; this solution seemed to be nice https://blog.jayway.com/2012/04/03/cucumber-data-driven-testing-tips/

But when following the example I run into this for the very first line of step definition

```<code>Your block takes 1 argument, but the Regexp matched 2 arguments.
</code>```

Apparently, I misunderstand how hashes should be handled; could somebody help please? My code with less test data is below
Cucumber

```<code>Given I login as "ad" with the following data:
    |role|usern       |userpass     |
    |ad  |adcccount   |adpassword   |
    |ml  |mlaccount   |mlpassword   |
</code>```

step definition

```<code>Given /^I login as "(ad|ml)" with the following data:/ do |user|
 temp_hash = {}
    if (user == "ad")
      temp_hash = $ad
    elsif (user == "ml")
      temp_hash = $ml
    end

    usern = temp_hash["usern"]
    userpass = temp_hash["userpass"]

 @app = App.new
  @app.login.load
  @app.login.username.set usern
  @app.login.password.set userpass
  @app.login.btn_login.click
end
</code>```

答:
Thanks, Thomas; your hint lead to the following code that worked as expected</p>

```<code>Given /^I login as "(ad|ml)" with the following data:/ do |login_role, data|

  temp_hash = {}
  data.hashes.each do |hash|
    if hash[:role] == login_role
      temp_hash[:role] = hash[:role]
      temp_hash[:usern] = hash[:usern]
      temp_hash[:userpass] = hash[:userpass]
    end
  end

    usern = temp_hash[:usern]
    userpass = temp_hash[:userpass]

  @app = App.new
  @app.login.load
  @app.login.username.set usern
  @app.login.password.set userpass
  @app.login.btn_login.click
  expect(@app.dashboard).to be_displayed
end
</code>```

Body:
I have a lot of tests with different login credentials on cucumber/capybara/site_prism, which are quite messy. I want to unify them as much as possible; this solution seemed to be nice https://blog.jayway.com/2012/04/03/cucumber-data-driven-testing-tips/

But when following the example I run into this for the very first line of step definition

Your block takes 1 argument, but the Regexp matched 2 arguments.

Apparently, I misunderstand how hashes should be handled; could somebody help please? My code with less test data is below
Cucumber

Given I login as "ad" with the following data:
    |role|usern       |userpass     |
    |ad  |adcccount   |adpassword   |
    |ml  |mlaccount   |mlpassword   |

step definition

Given /^I login as "(ad|ml)" with the following data:/ do |user|
 temp_hash = {}
    if (user == "ad")
      temp_hash = $ad
    elsif (user == "ml")
      temp_hash = $ml
    end

    usern = temp_hash["usern"]
    userpass = temp_hash["userpass"]

 @app = App.new
  @app.login.load
  @app.login.username.set usern
  @app.login.password.set userpass
  @app.login.btn_login.click
end

Body:
Thanks, Thomas; your hint lead to the following code that worked as expected

Given /^I login as "(ad|ml)" with the following data:/ do |login_role, data|

  temp_hash = {}
  data.hashes.each do |hash|
    if hash[:role] == login_role
      temp_hash[:role] = hash[:role]
      temp_hash[:usern] = hash[:usern]
      temp_hash[:userpass] = hash[:userpass]
    end
  end

    usern = temp_hash[:usern]
    userpass = temp_hash[:userpass]

  @app = App.new
  @app.login.load
  @app.login.username.set usern
  @app.login.password.set userpass
  @app.login.btn_login.click
  expect(@app.dashboard).to be_displayed
end


问:
GCE firewall issue
GCE firewall rules are not allowing me to connect to ports 3000 / 270107 after creating the rules, in some old instance I was able to connect to the 27017 but now with a new one I can't. i have deleted all projects, VMs, Rules and everything to start from scratch but nothing.

I am working with ubuntu 16.04 instances any help would be appreciated.

there is the image that shows my firewall config on GCE, vncserver is working fine, the port 5901 as I can connect to it but 3000 and 27017 or ANY other I try to open will not...

is there a limit for the 300$ trial or something?

I have a static external IP assigned which is the one I use to connect via VNC but nothing else works

答:
-make sure allow the related port on your instances iptables
   settings.

-make sure thats are relevant your instances these fields: 'source
   filters', 'source IP ranges' and 'target tags' in your GCP firewall
   settings

Title: GCE firewall issue


问:
OpenIAB Xcode Build Error
I'm using Simple IAP and OpenIAB system.

I have no problem Android system but i tried Xcode for IOS I have an error.

I added StoreKit framework.

```<code>"_Inventory_removePurchase", referenced from:

    RegisterMonoModules() in RegisterMonoModules.o

"_Inventory_query", referenced from:

    RegisterMonoModules() in RegisterMonoModules.o

"_AppStore_requestProducts", referenced from:

    RegisterMonoModules() in RegisterMonoModules.o

"_Inventory_hasPurchase", referenced from:

    RegisterMonoModules() in RegisterMonoModules.o

"_AppStore_startPurchase", referenced from:

    RegisterMonoModules() in RegisterMonoModules.o

"_AppStore_restorePurchases", referenced from:

    RegisterMonoModules() in RegisterMonoModules.o
</code>```

http://i.stack.imgur.com/v0Uik.png

How can I fix this? Thanks.

答:
Ensure you have added the following files to your project:

AppStoreBridge.mm, AppStoreDelegate.h,
AppStoreDelegate.mm

Without these files present, you will encounter the above framework errors when trying to build.

Title: OpenIAB Xcode Build Error

Body:
I'm using Simple IAP and OpenIAB system.

I have no problem Android system but i tried Xcode for IOS I have an error.

I added StoreKit framework.

"_Inventory_removePurchase", referenced from:

    RegisterMonoModules() in RegisterMonoModules.o

"_Inventory_query", referenced from:

    RegisterMonoModules() in RegisterMonoModules.o

"_AppStore_requestProducts", referenced from:

    RegisterMonoModules() in RegisterMonoModules.o

"_Inventory_hasPurchase", referenced from:

    RegisterMonoModules() in RegisterMonoModules.o

"_AppStore_startPurchase", referenced from:

    RegisterMonoModules() in RegisterMonoModules.o

"_AppStore_restorePurchases", referenced from:

    RegisterMonoModules() in RegisterMonoModules.o

http://i.stack.imgur.com/v0Uik.png

How can I fix this? Thanks.


问:
using row_number() in db2
I have the following data and I am trying to count each record whenever a combo of userid+customerid appear.  If the same combo returns in between other combos, I want to start the counter from one again.  However, when I use row_number() in the following code in Db2, I can't seem to get it working so that the counter is restarting at 1 for each userid+customerid appearing over time.  Does anyone have other suggestions?  Thank you so much.

```<code>select userid, customer, event_name, event_timestamp,
       row_number() over (partition by user_id, customer_number
                          order by  event_timestamp) as steps_rownum
from trackhist
order by userid, event_timestamp;
</code>```

答:
```<code>select userid, customer, event_name, event_timestamp,
       row_number() over (partition by userid, customer, grp
                          order by event_timestamp) as steps
from
(
    select t.*,
           (row_number() over (order by event_timestamp) -
            row_number() over (partition by userid, customer order by event_timestamp)
           ) as grp
    from trackhist t
) t
order by userid, event_timestamp
</code>```

Output:

Demo here:

Rextester

Note that the demo uses SQL Server, as DB2 is not an option with Rextester (at least for now).  The query should work in DB2 however, assuming ROW_NUMBER() behaves the same in both databases.

Title: using row_number() in db2

Body:
I have the following data and I am trying to count each record whenever a combo of userid+customerid appear.  If the same combo returns in between other combos, I want to start the counter from one again.  However, when I use row_number() in the following code in Db2, I can't seem to get it working so that the counter is restarting at 1 for each userid+customerid appearing over time.  Does anyone have other suggestions?  Thank you so much.

select userid, customer, event_name, event_timestamp,
       row_number() over (partition by user_id, customer_number
                          order by  event_timestamp) as steps_rownum
from trackhist
order by userid, event_timestamp;

Body:
select userid, customer, event_name, event_timestamp,
       row_number() over (partition by userid, customer, grp
                          order by event_timestamp) as steps
from
(
    select t.*,
           (row_number() over (order by event_timestamp) -
            row_number() over (partition by userid, customer order by event_timestamp)
           ) as grp
    from trackhist t
) t
order by userid, event_timestamp

Output:

Demo here:

Rextester

Note that the demo uses SQL Server, as DB2 is not an option with Rextester (at least for now).  The query should work in DB2 however, assuming ROW_NUMBER() behaves the same in both databases.


问:
Count number of male and female
i want to count  no of male and female in a table called Gender having entry given below. Answer should be female=2 Male=3 in count.
Is there any query in SQL.</p>

```<code>Gender
MALE
MaLE
FEMALE
Female
</code>```

答:
```<code>SELECT SUM(CASE WHEN Gender = 'male' THEN 1 ELSE 0 END) as Male_count,
       SUM(CASE WHEN Gender = 'Female' THEN 1 ELSE 0 END) as Female_count
FROM some_unknown_table
</code>```

As nightfox79 mentioned, if your default collation is case sensitive, you probably should transform the text to ensure it would match.
So, use this

```<code>UPPER(GENDER) = 'MALE'
UPPER(GENDER) = 'FEMALE'
</code>```

Sidenote: I think you should use a tinyint column for Gender following this format, as Damien mentioned. https://en.wikipedia.org/wiki/ISO/IEC_5218

Title: Count number of male and female

Body:
i want to count  no of male and female in a table called Gender having entry given below. Answer should be female=2 Male=3 in count.
Is there any query in SQL.

Gender
MALE
MaLE
FEMALE
Female

Body:
SELECT SUM(CASE WHEN Gender = 'male' THEN 1 ELSE 0 END) as Male_count,
       SUM(CASE WHEN Gender = 'Female' THEN 1 ELSE 0 END) as Female_count
FROM some_unknown_table

As nightfox79 mentioned, if your default collation is case sensitive, you probably should transform the text to ensure it would match.
So, use this

UPPER(GENDER) = 'MALE'
UPPER(GENDER) = 'FEMALE'

Sidenote: I think you should use a tinyint column for Gender following this format, as Damien mentioned. https://en.wikipedia.org/wiki/ISO/IEC_5218


问:
Zenject Global Bindings
I'm well aware this might not be the best place to ask a Zenject question. I've already posted the same question on Zenject google groups page as well. I'm posting this here thinking that someone who is on here (who's not on google groups) might be able to help me out.

I have a question about Zenject Global Bindings.

My AR app at the moment have several different screens (saved as scenes). Each scene can be run on it's own that way I could keep it very compartmentalised. When I press a button on 'Screen1' it loads 'Screen2' so on and so forth. I'm using a very basic AppDelegate which contains a NavigationController class which handled all the UGUI transitions so that it appears as a normal iOS navigation based app so to speak. I'm injecting AppDelegate as Singleton on all the installers I have but since there are individual CompositionRoots for individual screens (scenes), globally they are not injected as singletons.

Is there a way to do this. Have a singleton injection all throughout the app but with different composition roots?

If not, how to use Global composition root?
I've followed instructions on the guide to create a global composition root and add the installer as a prefab and all that. I deleted installer from the scene as well. But when I play nothing happens. Am I missing something obvious here.

Thanks in advance.

答:
in your Resources folder create a project context prefab
 how to make a project context prefab.

You also absolutely have to include a "SceneContext" in your scene. this spawns the first "ProjectContext".

After the creation of said object, it will load on any scene start.
along with the installers and scriptable object installers provided on the prefab. along with bindings to singletons ie:

```<code>Container.Bind<IFoo>().To<Foo>().AsSingle().NonLazy();
</code>```

this means, on zenject initilization you will have an instance of your singelton ready and waiting.

Title: Zenject Global Bindings

Body:
in your Resources folder create a project context prefab
 how to make a project context prefab.

You also absolutely have to include a "SceneContext" in your scene. this spawns the first "ProjectContext".

After the creation of said object, it will load on any scene start.
along with the installers and scriptable object installers provided on the prefab. along with bindings to singletons ie:

Container.Bind<IFoo>().To<Foo>().AsSingle().NonLazy();

this means, on zenject initilization you will have an instance of your singelton ready and waiting.


问:
I want to decode html entity into text and then perform string.contain operation
my textbox data

```<code>txtdata = "java&#115&#99&#114&#105&#112&#116 is good."
</code>```

i want to decode it like "javascript is good."
i have used WebUtility.HtmlDecode and htmlutility.htmldecode but its not working.

when i used

```<code>String check = WebUtility.HtmlDecode(txtdata);
</code>```

or

```<code>HtmlUtility.HtmlDecode(txtdata);
</code>```

and then try to use

```<code> if  (check.Contains("javascript") == true)
</code>```

it shows false
i tried debugging and it shows the same text in check string as original "java&#115&#99&#114&#105&#112&#116 is good."

what can i do?
thank you.

答:
Your HTML string is not well encoded, you have missed semicolons.
It should be:

```<code>txtdata = "javascript is good.";
</code>```

With correctly encoded string both HttpUtility.HtmlDecode() and WebUtility.HtmlDecode() will return javascript is good.

Body:
my textbox data

txtdata = "java&#115&#99&#114&#105&#112&#116 is good."

i want to decode it like "javascript is good."
i have used WebUtility.HtmlDecode and htmlutility.htmldecode but its not working.

when i used

String check = WebUtility.HtmlDecode(txtdata);

or

HtmlUtility.HtmlDecode(txtdata);

and then try to use

 if  (check.Contains("javascript") == true)

it shows false
i tried debugging and it shows the same text in check string as original "java&#115&#99&#114&#105&#112&#116 is good."

what can i do?
thank you.

Body:
Your HTML string is not well encoded, you have missed semicolons.
It should be:

txtdata = "java&#115;&#99;&#114;&#105;&#112;&#116; is good.";

With correctly encoded string both HttpUtility.HtmlDecode() and WebUtility.HtmlDecode() will return javascript is good.


问:
Caliburn.Micro & Infragistics XamDockManager + TabGroupPane
I'm trying to get the Infragistics TabGroupPane to integrate with Caliburn.Micro as per the standard WPF TabControl.

I've tried adding a new convention in the bootstrapper (a modification of the standard WPF one) but have not had any success.

My TabGroupPane is defined as:

```<code><igDock:TabGroupPane x:Name="Items"/>
</code>```

When an item is added to the collection an exception is thrown "InvalidOperationException: A TabGroupPane can only contain 'ContentPane' and 'ContentPanePlaceholder' instances".

Also, if my TabGroupPane is inside a DockManager:

```<code><igDock:XamDockManager>
    <igDock:DocumentContentHost>
        <igDock:SplitPane>
            <igDock:TabGroupPane x:Name="Items" />
        </igDock:SplitPane>
    </igDock:DocumentContentHost>
</igDock:XamDockManager>
</code>```

It doesn't appear to be found by Caliburn at all.

Has anyone else done this before?

Cheers!

Update

I have created my own dock manager class, a blog post explaining it or just the code on bitbucket. Hopefully this will be useful to someone!

答:
Have you tried using a more explicit binding? Caliburn can only do automatic binding on certain elementtypes, and I guess Infragistics TabGroupPane is not one of them!

I guess you have to use something like this:

```<code><igDock:TabGroupPane x:Name="Items" ItemSource={Binding <what to bind to>}/>
</code>```

Note: This is just used as an example, not sure if ItemSource is the correct property!

Body:
I'm trying to get the Infragistics TabGroupPane to integrate with Caliburn.Micro as per the standard WPF TabControl.

I've tried adding a new convention in the bootstrapper (a modification of the standard WPF one) but have not had any success.

My TabGroupPane is defined as:

<igDock:TabGroupPane x:Name="Items"/>

When an item is added to the collection an exception is thrown "InvalidOperationException: A TabGroupPane can only contain 'ContentPane' and 'ContentPanePlaceholder' instances".

Also, if my TabGroupPane is inside a DockManager:

<igDock:XamDockManager>
    <igDock:DocumentContentHost>
        <igDock:SplitPane>
            <igDock:TabGroupPane x:Name="Items" />
        </igDock:SplitPane>
    </igDock:DocumentContentHost>
</igDock:XamDockManager>

It doesn't appear to be found by Caliburn at all.

Has anyone else done this before?

Cheers!

Update

I have created my own dock manager class, a blog post explaining it or just the code on bitbucket. Hopefully this will be useful to someone!

Body:
Have you tried using a more explicit binding? Caliburn can only do automatic binding on certain elementtypes, and I guess Infragistics TabGroupPane is not one of them!

I guess you have to use something like this:

<igDock:TabGroupPane x:Name="Items" ItemSource={Binding <what to bind to>}/>

Note: This is just used as an example, not sure if ItemSource is the correct property!