问:
Is try catch block necessary inside controller in laravel?
I'm currently working on a project with my friend. He follows this method of writing codes. Is it good or bad? I'm also not that much experience developer.</p>

```<code>public function store(Request $request)
 {
    try
    {
        $comment = new TicketComment();
        $comment->content = $request['comment'];
        $comment->user_id = Auth::user()->id;
        $comment->ticket_id = $request['ticketId'];
        $comment->save();
        $ticket = Ticket::where('id', '=', $comment->ticket_id)->first();
        $ticket->updated_at = $comment->created_at;
        $ticket->update();
    }
    catch(Exception $e)
    {
        request()->session()->flash('unsuccessMessage', 'Failed to add comment !!!');
        return redirect()->back();
    }
    request()->session()->flash('successMessage', 'Comment has been successfully added !!!');
    return redirect()->back();
}
</code>```

答:
It is allways good to handle the errors. However, Laravel has built in error handling, which ease this process. This does not mean you dont need the try catch block.
Read more about laravel error handling: https://laravel.com/docs/5.8/errors</p>

Body:
I'm currently working on a project with my friend. He follows this method of writing codes. Is it good or bad? I'm also not that much experience developer.

public function store(Request $request)
 {
    try
    {
        $comment = new TicketComment();
        $comment->content = $request['comment'];
        $comment->user_id = Auth::user()->id;
        $comment->ticket_id = $request['ticketId'];
        $comment->save();
        $ticket = Ticket::where('id', '=', $comment->ticket_id)->first();
        $ticket->updated_at = $comment->created_at;
        $ticket->update();
    }
    catch(Exception $e)
    {
        request()->session()->flash('unsuccessMessage', 'Failed to add comment !!!');
        return redirect()->back();
    }
    request()->session()->flash('successMessage', 'Comment has been successfully added !!!');
    return redirect()->back();
}


来源: stackexchange

问:
get specific value in each group and add it as new column in each group
I want to have something like this:

dataframe:

```<code> col1            col2             col3
A               'aa'            date1
A               'aa'            date2
A               'aa'            date3
A               'bb'            date4
B               'aa'            date5
B               'bb'            date6
B               'aa'            date7
</code>```

output:

```<code>  col1            col2             col3        col4
    A               'aa'            date1        date4
    A               'aa'            date2        date4
    A               'aa'            date3        date4
    A               'bb'            date4        date4
    B               'aa'            date5        date6
    B               'bb'            date6        date6
    B               'aa'            date7        date6

</code>```

I want to group by col1 and based on value in col2 get col3 and add a new column as col4 and set it as this value of col3

'aa' and 'bb' are examples so I can't use sort...I should compare it with a value.

答:
If there are only one bb values per groups filter them and Series.map for new column:

```<code>s = df[df['col2'].eq('bb')].set_index('col1')['col3']
#if possible multiple values per groups
#s = df[df['col2'].eq('bb')].drop_duplicates('col1').set_index('col1')['col3']
df['col4'] = df['col1'].map(s)
print (df)
  col1 col2   col3   col4
0    A   aa  date1  date4
1    A   aa  date2  date4
2    A   aa  date3  date4
3    A   bb  date4  date4
4    B   aa  date5  date6
5    B   bb  date6  date6
6    B   aa  date7  date6
</code>```

Another idea with left join in merge:

```<code>df1 = df.loc[df['col2'].eq('bb'),['col1','col3']].rename(columns={'col3':'col4'})
</code>```

If duplicated bb values per groups:

```<code>df1 = (df.loc[df['col2'].eq('bb'),['col1','col3']]
         .drop_duplicates('col1')
         .rename(columns={'col3':'col4'}))

print (df1)
  col1   col4
3    A  date4
5    B  date6

df = df.merge(df1, on='col1', how='left')
print (df)
  col1 col2   col3   col4
0    A   aa  date1  date4
1    A   aa  date2  date4
2    A   aa  date3  date4
3    A   bb  date4  date4
4    B   aa  date5  date6
5    B   bb  date6  date6
6    B   aa  date7  date6
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to have something like this:

dataframe:

 col1            col2             col3
A               'aa'            date1
A               'aa'            date2
A               'aa'            date3
A               'bb'            date4
B               'aa'            date5
B               'bb'            date6
B               'aa'            date7

output:

  col1            col2             col3        col4
    A               'aa'            date1        date4
    A               'aa'            date2        date4
    A               'aa'            date3        date4
    A               'bb'            date4        date4
    B               'aa'            date5        date6
    B               'bb'            date6        date6
    B               'aa'            date7        date6

I want to group by col1 and based on value in col2 get col3 and add a new column as col4 and set it as this value of col3

'aa' and 'bb' are examples so I can't use sort...I should compare it with a value.

Body:
If there are only one bb values per groups filter them and Series.map for new column:

s = df[df['col2'].eq('bb')].set_index('col1')['col3']
#if possible multiple values per groups
#s = df[df['col2'].eq('bb')].drop_duplicates('col1').set_index('col1')['col3']
df['col4'] = df['col1'].map(s)
print (df)
  col1 col2   col3   col4
0    A   aa  date1  date4
1    A   aa  date2  date4
2    A   aa  date3  date4
3    A   bb  date4  date4
4    B   aa  date5  date6
5    B   bb  date6  date6
6    B   aa  date7  date6

Another idea with left join in merge:

df1 = df.loc[df['col2'].eq('bb'),['col1','col3']].rename(columns={'col3':'col4'})

If duplicated bb values per groups:

df1 = (df.loc[df['col2'].eq('bb'),['col1','col3']]
         .drop_duplicates('col1')
         .rename(columns={'col3':'col4'}))

print (df1)
  col1   col4
3    A  date4
5    B  date6

df = df.merge(df1, on='col1', how='left')
print (df)
  col1 col2   col3   col4
0    A   aa  date1  date4
1    A   aa  date2  date4
2    A   aa  date3  date4
3    A   bb  date4  date4
4    B   aa  date5  date6
5    B   bb  date6  date6
6    B   aa  date7  date6


问:
python populating array using while loop
All I am trying to do is populate an array with numbers in order. So, array[0][0] = 0, array[0][1]=1, etc. Why is this not working?  I cannot figure it out.</p>

```<code>def populateArray(ar):
    count = 0
    i=0
    j=0
    while (i<len(ar)):
        while (j<len(ar[i])):
            ar[i][j] = count
            count = count + 1
            j=j+1
        j=0
        i=i+1
    return ar

numColumns = input('how many columns?')
numRows = input('how many rows?')
arr = [[0]*int(numColumns)]*int(numRows)
arr=populateArray(arr)
print(arr)
</code>```

答:
You can also make use of numpy for creating the structure, followed by using numpy.tolist() for converting it to a python list</p>

```<code>import numpy as np
numColumns = int(input('how many columns?'))
numRows = int(input('how many rows?') )
arr = np.arange(numRows*numColumns).reshape(numRows, numColumns).tolist()
print(arr)
</code>```

Body:
All I am trying to do is populate an array with numbers in order. So, array[0][0] = 0, array[0][1]=1, etc. Why is this not working?  I cannot figure it out.

def populateArray(ar):
    count = 0
    i=0
    j=0
    while (i<len(ar)):
        while (j<len(ar[i])):
            ar[i][j] = count
            count = count + 1
            j=j+1
        j=0
        i=i+1
    return ar

numColumns = input('how many columns?')
numRows = input('how many rows?')
arr = [[0]*int(numColumns)]*int(numRows)
arr=populateArray(arr)
print(arr)

Body:
You can also make use of numpy for creating the structure, followed by using numpy.tolist() for converting it to a python list

import numpy as np
numColumns = int(input('how many columns?'))
numRows = int(input('how many rows?') )
arr = np.arange(numRows*numColumns).reshape(numRows, numColumns).tolist()
print(arr)


Title: Printing a simple sudoku board array

Body:
So my code is currently missing the 8th index of the array and pushing it down 1 row. I'm new to kotlin but I honestly have no clue why its doing that.

fun main() {
    val board = arrayOf(
        arrayOf(7, 8, 0, 4, 0, 0, 1, 2, 0),
        arrayOf(6, 0, 0, 0, 7, 5, 0, 0, 9),
        arrayOf(0, 0, 0, 6, 0, 1, 0, 7, 8),
        arrayOf(0, 0, 7, 0, 4, 0, 2, 6, 0),
        arrayOf(0, 0, 1, 0, 5, 0, 9, 3, 0),
        arrayOf(9, 0, 4, 0, 6, 0, 0, 0, 5),
        arrayOf(0, 7, 0, 3, 0, 0, 0, 1, 2),
        arrayOf(1, 2, 0, 0, 0, 7, 4, 0, 0),
        arrayOf(0, 4, 9, 2, 0, 6, 0, 0, 7)
    )
    for (row in 0 until board.size) {
        if(row % 3 == 0 && row != 0) {
        println(" - - - - - - - - - " )
        }
            for(col in 0 until board.size) {
               if(col == 8){
                    println(" ")
                }
                if(col % 3 == 0 && col != 0) {
                print(" |")
                }
                print(" ")
                print(board[row][col])
            }
    }
}

With the output being

7 8 0 | 4 0 0 | 1 2
 0 6 0 0 | 0 7 5 | 0 0
 9 0 0 0 | 6 0 1 | 0 7
 8 - - - - - - - - -
 0 0 7 | 0 4 0 | 2 6
 0 0 0 1 | 0 5 0 | 9 3
 0 9 0 4 | 0 6 0 | 0 0
 5 - - - - - - - - -
 0 7 0 | 3 0 0 | 0 1
 2 1 2 0 | 0 0 7 | 4 0
 0 0 4 9 | 2 0 6 | 0 0
 7

Body:
This works flawlessly according to your requirement (as you wanted trailing spaces before and after)

Code:

val board = arrayOf(
    arrayOf(7, 8, 0, 4, 0, 0, 1, 2, 0),
    arrayOf(6, 0, 0, 0, 7, 5, 0, 0, 9),
    arrayOf(0, 0, 0, 6, 0, 1, 0, 7, 8),
    arrayOf(0, 0, 7, 0, 4, 0, 2, 6, 0),
    arrayOf(0, 0, 1, 0, 5, 0, 9, 3, 0),
    arrayOf(9, 0, 4, 0, 6, 0, 0, 0, 5),
    arrayOf(0, 7, 0, 3, 0, 0, 0, 1, 2),
    arrayOf(1, 2, 0, 0, 0, 7, 4, 0, 0),
    arrayOf(0, 4, 9, 2, 0, 6, 0, 0, 7)
)
for (row in board.indices) {
    if (row % 3 == 0 && row != 0) {
        println(" - - - - - - - - - - - ")
    }

    for (col in board.indices) {
        if (col % 3 == 0 && col != 0) {
            print(" |")
        }
        print(" " + board[row][col])
    }
    println()
}

Result:

 7 8 0 | 4 0 0 | 1 2 0
 6 0 0 | 0 7 5 | 0 0 9
 0 0 0 | 6 0 1 | 0 7 8
 - - - - - - - - - - -
 0 0 7 | 0 4 0 | 2 6 0
 0 0 1 | 0 5 0 | 9 3 0
 9 0 4 | 0 6 0 | 0 0 5
 - - - - - - - - - - -
 0 7 0 | 3 0 0 | 0 1 2
 1 2 0 | 0 0 7 | 4 0 0
 0 4 9 | 2 0 6 | 0 0 7

Edit: <>.indices is just a short extension for 0 until <>.size


问:
How can I fix the "blank page" issue in html2pdf.js?
I'm trying to convert the HTML document to PDF using html2pdf.js, but as a result I get a pdf with a blank first page and the last page of the document being half cropped. How such issue could be fixed ? Code:</p>

```<code>document.querySelector('.save-pdf').addEventListener('click', function () {
   const elementToPrint = document.getElementById('content');

   const opt = {
      margin:       0,
      filename:     'contract.pdf',
      image:        { type: 'png' },
      html2canvas:  { scale: 2 },
      jsPDF:        { unit: 'in', format: 'letter', orientation: 'p' }
   };

   html2pdf(elementToPrint, opt);
});
</code>```

答: The problem solved by switching the version of "html2canvas" library from "rc 5" to "alpha 12".</p>

Body:
I'm trying to convert the HTML document to PDF using html2pdf.js, but as a result I get a pdf with a blank first page and the last page of the document being half cropped. How such issue could be fixed ? Code:

document.querySelector('.save-pdf').addEventListener('click', function () {
   const elementToPrint = document.getElementById('content');

   const opt = {
      margin:       0,
      filename:     'contract.pdf',
      image:        { type: 'png' },
      html2canvas:  { scale: 2 },
      jsPDF:        { unit: 'in', format: 'letter', orientation: 'p' }
   };

   html2pdf(elementToPrint, opt);
});


问:
Summernote: set focus after initialization
Summernote gives you the option of giving focus to the editor when you create it, passing this options:

```<code>$('#summernote').summernote({
     focus: true
});
</code>```

But after initialization, it seems you can't give focus to the textarea by clicking a button or similar. I've tried several ways, without success.

Anyone did that?

答:
```<code><div class="col-lg-12 col-md-6 col-xs-12">
    <div class="form-group">
        <label>  Skills</label>
        <span ng-messages="EditForm.Skills.$error" ng-if="EditForm.Skills.$dirty || isEditFormSubmitted ">
            <span class="text-danger" ng-message="required" ng-bind="error msg"></span>
        </span>
        <text-angular id="Skills" name="Skills" ng-model="EditVacancyModel.Skills" ta-toolbar="[['bold','underline','italics','ul','ol']]"ng-required="true"></text-angular>
    </div>
</div>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Summernote gives you the option of giving focus to the editor when you create it, passing this options:

$('#summernote').summernote({
     focus: true
});

But after initialization, it seems you can't give focus to the textarea by clicking a button or similar. I've tried several ways, without success.

Anyone did that?


问:
static_assert in class to enforce memory layout
I'm trying use static_assert to make sure other programmers refrain to extend a certain class beyond it's intended usage since it's commonly used in low-level calculations where it's assumed that the number of bytes are as the static assert below wants to check.

```<code>template<typename T, int N>
class MyClass final
{
public:
    // This is the static_assert I need to fix
    static_assert(sizeof(MyClass<T, N>) == sizeof(T) * N, "Wrong size");

    // rest of code goes here...
};
</code>```

Unfortunately it does not work with:

```<code>    static_assert(std::is_standard_layout<T>::value, "Wrong Size");
</code>```

Since it's still possible after that to pollute the class.

I really want to add this check because if anyone changes this class, i.e. makes it virtual or adds a new member, the results of executing the code at a later stage will be undefined.

答:
static_assert(sizeof(MyClass<T, N>) == sizeof(T) * N, "Wrong size");

can not work inside class because MyClass<T, N> is incomplete at this point.
You can move the static_assert into ctor/dtor. cons - assert will trigger only at instantiation.
e.g.

```<code>template<typename T, int N>
class MyClass final
{
public:
    static_assert(std::is_standard_layout<T>::value, "T has to provide standard layout");

    MyClass()
    {
        static_assert(sizeof(MyClass<T, N>) == sizeof(T) * N, "Wrong size");
        static_assert(std::is_standard_layout<MyClass<T, N>>::value, "MyClass has to provide standard layout");

    }
    T _m[N];
    // rest of code goes here...
};
</code>```

Body:
I'm trying use static_assert to make sure other programmers refrain to extend a certain class beyond it's intended usage since it's commonly used in low-level calculations where it's assumed that the number of bytes are as the static assert below wants to check.

template<typename T, int N>
class MyClass final
{
public:
    // This is the static_assert I need to fix
    static_assert(sizeof(MyClass<T, N>) == sizeof(T) * N, "Wrong size");

    // rest of code goes here...
};

Unfortunately it does not work with:

    static_assert(std::is_standard_layout<T>::value, "Wrong Size");

Since it's still possible after that to pollute the class.

I really want to add this check because if anyone changes this class, i.e. makes it virtual or adds a new member, the results of executing the code at a later stage will be undefined.

Body:
static_assert(sizeof(MyClass<T, N>) == sizeof(T) * N, "Wrong size");

can not work inside class because MyClass<T, N> is incomplete at this point.
You can move the static_assert into ctor/dtor. cons - assert will trigger only at instantiation.
e.g.

template<typename T, int N>
class MyClass final
{
public:
    static_assert(std::is_standard_layout<T>::value, "T has to provide standard layout");

    MyClass()
    {
        static_assert(sizeof(MyClass<T, N>) == sizeof(T) * N, "Wrong size");
        static_assert(std::is_standard_layout<MyClass<T, N>>::value, "MyClass has to provide standard layout");

    }
    T _m[N];
    // rest of code goes here...
};


问:
How to force regex to capture shortest group?
I have two sentences like these:

"How is the weather of Paris in next day"

"How is the weather of Paris next day"

I want to extract "Paris" as the city name from both of them. I wrote this regular expression:

```<code>"How is the weather of (?P<city>[^.؟!?]*) (in next day|next day)"
</code>```

This expression extracts "Paris in" for the first sentence which is not right!

I want to match an input sentence with my regular expression in a way that it will be matched with the longest alternative of the second group, so I can get the shortest city name. (I thought the order of alternative in the second group matter so I put "in next day" before "next day" but It seems that the order doesn't work!) How can I rewrite my regular expression to solve this problem?

答:
You should use lazy quantifier, which matches as few characters as possible.
In your example, you should add ? in the end first group:

```<code>"How is the weather of (?P[^.؟!?]*?) (in next day|next day)"
</code>```

Body:
I have two sentences like these:

"How is the weather of Paris in next day"

"How is the weather of Paris next day"

I want to extract "Paris" as the city name from both of them. I wrote this regular expression:

"How is the weather of (?P<city>[^.؟!?]*) (in next day|next day)"

This expression extracts "Paris in" for the first sentence which is not right!

I want to match an input sentence with my regular expression in a way that it will be matched with the longest alternative of the second group, so I can get the shortest city name. (I thought the order of alternative in the second group matter so I put "in next day" before "next day" but It seems that the order doesn't work!) How can I rewrite my regular expression to solve this problem?

Body:
You should use lazy quantifier, which matches as few characters as possible.
In your example, you should add ? in the end first group:

"How is the weather of (?P[^.؟!?]*?) (in next day|next day)"


问:
How to get html element's class tags
I'm using a custom modernizer config which has selected the features I employ in my page (and only those features).

So, I'd like to simply grab the className of the  of the page so I can check to see how many no- prefixed classes are present (maybe checking classlist.match(/no-/g).length) and determine if my javascript should just give up.

It's not clear whether I should use

```<code>document.getElementsByTagName('html').className
</code>```

or

```<code>$('html').attr('class')
</code>```

or

```<code>document.documentElement.className
</code>```

答:
```<code> var allClasses = [];
 var allElements = document.querySelectorAll('*');

 for (var i = 0; i < allElements.length; i++) {
     if (allElements[i].hasAttribute("class")) {
        var classes = allElements[i].className.toString().split(/\s+/);
        for (var j = 0; j < classes.length; j++) {
             var cls = classes[j];
             if (cls && allClasses.indexOf(cls) === -1)
                allClasses.push(cls);
        }
     }
 }

 console.log(allClasses);
</code>```

Title: How to get html element's class tags

Body:
I'm using a custom modernizer config which has selected the features I employ in my page (and only those features).

So, I'd like to simply grab the className of the  of the page so I can check to see how many no- prefixed classes are present (maybe checking classlist.match(/no-/g).length) and determine if my javascript should just give up.

It's not clear whether I should use

document.getElementsByTagName('html').className

or

$('html').attr('class')

or

document.documentElement.className


问:
SQL DataReader giving "string or binary data will be truncated"
I'm trying to read a table where under normal circumstances zero rows will be returned. If any rows are returned an error message is shown. I've tested the SQL statement in on SQL Server and it works. However, I'm getting an error in the DataReader. My code is as follows:

```<code>Using sqlConn As SqlConnection = New SqlConnection(cSettings.PrimaryConnectionString)
     Dim sSQLc As String = "SELECT * FROM UnitHistory " _
                            + "WHERE Unit=" + iUnitID.ToString + " " _
                            + "AND StartDate<='" + returnSQLDateString(dAdmissionDateTime) + "' " _
                            + "AND (EndDate IS NULL OR " _
                            + "EndDate>'" + returnSQLDateString(dAdmissionDateTime) + "') " _
                            + "AND IsAmended IS NULL AND IsReversed IS NULL"
     Using sqlCMD As SqlCommand = New SqlCommand(sSQLc, sqlConn)
         Using sqlR As SqlDataReader = sqlCMD.ExecuteReader ' <--- (The error is raised at this line)
             If sqlR.HasRows Then
                 ' if rows were returned then there was someone in the unit
                 ' we're trying to admit to.
                 MsgBox("There is an admission already in this unit for this admission date")
                 Exit Sub
             End If
         End Using
     End Using
End Using
</code>```

A sample SQL Statement which this generates is:

```<code>SELECT *
FROM UnitHistory
WHERE Unit=1
AND StartDate<='2019-07-14 20:55'
AND (EndDate IS NULL OR EndDate>'2019-07-14 20:55')
AND IsAmended IS NULL
AND IsReversed IS NULL
</code>```

The columns in question (as in the SQL Statement) are int/DateTime/DateTime/Bit/Bit

I can't see why this is causing the error to be raised.

答:
As you're only using the query to test if there is anything present, perhaps it would make more sense to use a count of the relevant rows.

The using statements can be combined into one, which is sometimes neater. Also, you should always use SQL parameters for SQL queries: that prevents problems with dates, names with apostrophes, and SQL injection attacks - and the query is easier to read.

Dim sql = "SELECT COUNT(*)
FROM UnitHistory
WHERE Unit = @unit
AND StartDate <= @startDate
AND (EndDate IS NULL OR EndDate > @endDate)
AND IsAmended IS NULL
AND IsReversed IS NULL"

Using sqlConn As SqlConnection = New SqlConnection(cSettings.PrimaryConnectionString),
        cmd As New SqlCommand(sql, sqlConn)

    cmd.Parameters.Add("@unit", SqlDbType.Int).Value = iUnitID
    cmd.Parameters.Add("@startDate", SqlDbType.DateTime).Value = dAdmissionDateTime
    cmd.Parameters.Add("@endDate", SqlDbType.DateTime).Value = dAdmissionDateTime

    sqlConn.Open()
    Dim admissionCount = CInt(cmd.ExecuteScalar())

    If admissionCount > 0 Then
        ' if rows were returned then there was someone in the unit
        ' we're trying to admit to.
        MsgBox("There is an admission already in this unit for this admission date.")
        Exit Sub
    End If

End Using
```

(If your copy of Visual Studio doesn't like the multi-line string for sql, just put it all on one line.)

Body:
I'm trying to read a table where under normal circumstances zero rows will be returned. If any rows are returned an error message is shown. I've tested the SQL statement in on SQL Server and it works. However, I'm getting an error in the DataReader. My code is as follows:

Using sqlConn As SqlConnection = New SqlConnection(cSettings.PrimaryConnectionString)
     Dim sSQLc As String = "SELECT * FROM UnitHistory " _
                            + "WHERE Unit=" + iUnitID.ToString + " " _
                            + "AND StartDate<='" + returnSQLDateString(dAdmissionDateTime) + "' " _
                            + "AND (EndDate IS NULL OR " _
                            + "EndDate>'" + returnSQLDateString(dAdmissionDateTime) + "') " _
                            + "AND IsAmended IS NULL AND IsReversed IS NULL"
     Using sqlCMD As SqlCommand = New SqlCommand(sSQLc, sqlConn)
         Using sqlR As SqlDataReader = sqlCMD.ExecuteReader ' <--- (The error is raised at this line)
             If sqlR.HasRows Then
                 ' if rows were returned then there was someone in the unit
                 ' we're trying to admit to.
                 MsgBox("There is an admission already in this unit for this admission date")
                 Exit Sub
             End If
         End Using
     End Using
End Using

A sample SQL Statement which this generates is:

SELECT *
FROM UnitHistory
WHERE Unit=1
AND StartDate<='2019-07-14 20:55'
AND (EndDate IS NULL OR EndDate>'2019-07-14 20:55')
AND IsAmended IS NULL
AND IsReversed IS NULL

The columns in question (as in the SQL Statement) are int/DateTime/DateTime/Bit/Bit

I can't see why this is causing the error to be raised.

Body:
As you're only using the query to test if there is anything present, perhaps it would make more sense to use a count of the relevant rows.

The using statements can be combined into one, which is sometimes neater. Also, you should always use SQL parameters for SQL queries: that prevents problems with dates, names with apostrophes, and SQL injection attacks - and the query is easier to read.

Dim sql = "SELECT COUNT(*)
FROM UnitHistory
WHERE Unit = @unit
AND StartDate <= @startDate
AND (EndDate IS NULL OR EndDate > @endDate)
AND IsAmended IS NULL
AND IsReversed IS NULL"

Using sqlConn As SqlConnection = New SqlConnection(cSettings.PrimaryConnectionString),
        cmd As New SqlCommand(sql, sqlConn)

    cmd.Parameters.Add("@unit", SqlDbType.Int).Value = iUnitID
    cmd.Parameters.Add("@startDate", SqlDbType.DateTime).Value = dAdmissionDateTime
    cmd.Parameters.Add("@endDate", SqlDbType.DateTime).Value = dAdmissionDateTime

    sqlConn.Open()
    Dim admissionCount = CInt(cmd.ExecuteScalar())

    If admissionCount > 0 Then
        ' if rows were returned then there was someone in the unit
        ' we're trying to admit to.
        MsgBox("There is an admission already in this unit for this admission date.")
        Exit Sub
    End If

End Using

(If your copy of Visual Studio doesn't like the multi-line string for sql, just put it all on one line.)


问:
Kafka streams error : SerializationException: Size of data received by LongDeserializer is not 8
I am trying Kafka Streams. Writing a simple application where I am counting duplicate messages.

Message:

```<code>2019-02-27-11:16:56 :: session:prod-111656 :: Msg => Hello World: 2491
2019-02-27-11:16:56 :: session:prod-111656 :: Msg => Hello World: 2492
</code>```

etc.

I am trying to split such messages by session:prod-xxxx. Use it as key. And session:prod-xxxx+Hello World: xxxx use it as value. Then group by key, and see which messages got duplicated in each session.

Here's the code:

```<code>KStream<String, String> textLines = builder.stream("RegularProducer");
KTable<String, Long> ktable = textLines.map(
    (String key, String value) -> {
        try {
            String[] parts = value.split("::");
            String sessionId = parts[1];
            String message = ((parts[2]).split("=>"))[1];
            message = sessionId+":"+message;
            return new KeyValue<String,String>(sessionId.trim().toLowerCase(), message.trim().toLowerCase());
        } catch (Exception e) {
            return new KeyValue<String,String>("Invalid-Message".trim().toLowerCase(), "Invalid Message".trim().toLowerCase());
        }
    })
    .groupBy((key,value) -> value)
    .count().filter(
            (String key, Long value) -> {
                return value > 1;
            }
    );

ktable.toStream().to("RegularProducerDuplicates",
Produced.with(Serdes.String(), Serdes.Long()));
Topology topology = builder.build();
topology.describe();
KafkaStreams streams = new KafkaStreams(topology, props);
streams.start();
</code>```

KTable topic RegularProducerDuplicates gets produced. But when I use console-consumer to view it, it crashes with an error. Then I use --skip-message-on-error flag on console-consumer. Now I see thousands of lines like these

```<code>session:prod-111656 : hello world: 994  [2019-02-28 16:25:18,081] ERROR Error processing message, skipping this message:  (kafka.tools.ConsoleConsumer$)
org.apache.kafka.common.errors.SerializationException: Size of data received by LongDeserializer is not 8
</code>```

Can anyone help me what's going wrong here?

答: I had the same issue and found that if I move the filter after toStream, the null values (tombstones) are not produced.

Body:
I am trying Kafka Streams. Writing a simple application where I am counting duplicate messages.

Message:

2019-02-27-11:16:56 :: session:prod-111656 :: Msg => Hello World: 2491
2019-02-27-11:16:56 :: session:prod-111656 :: Msg => Hello World: 2492

etc.

I am trying to split such messages by session:prod-xxxx. Use it as key. And session:prod-xxxx+Hello World: xxxx use it as value. Then group by key, and see which messages got duplicated in each session.

Here's the code:

KStream<String, String> textLines = builder.stream("RegularProducer");
KTable<String, Long> ktable = textLines.map(
    (String key, String value) -> {
        try {
            String[] parts = value.split("::");
            String sessionId = parts[1];
            String message = ((parts[2]).split("=>"))[1];
            message = sessionId+":"+message;
            return new KeyValue<String,String>(sessionId.trim().toLowerCase(), message.trim().toLowerCase());
        } catch (Exception e) {
            return new KeyValue<String,String>("Invalid-Message".trim().toLowerCase(), "Invalid Message".trim().toLowerCase());
        }
    })
    .groupBy((key,value) -> value)
    .count().filter(
            (String key, Long value) -> {
                return value > 1;
            }
    );

ktable.toStream().to("RegularProducerDuplicates",
Produced.with(Serdes.String(), Serdes.Long()));
Topology topology = builder.build();
topology.describe();
KafkaStreams streams = new KafkaStreams(topology, props);
streams.start();

KTable topic RegularProducerDuplicates gets produced. But when I use console-consumer to view it, it crashes with an error. Then I use --skip-message-on-error flag on console-consumer. Now I see thousands of lines like these

session:prod-111656 : hello world: 994  [2019-02-28 16:25:18,081] ERROR Error processing message, skipping this message:  (kafka.tools.ConsoleConsumer$)
org.apache.kafka.common.errors.SerializationException: Size of data received by LongDeserializer is not 8

Can anyone help me what's going wrong here?


问:
How to install Qt5 libraries for Windows 10 for cmake development?
I want to develop in Windows 10 with cmake. I don't need QtCreator, nor any other things. Just the minimum to compile with cmake. I downloaded the qt online installed and selected Qt 5.14.1 but it has 36gb! I don't even have that amount of space.

What is the bare minimum to run Qt/QML applications with cmake?

答:
I downloaded the qt online installed and selected Qt 5.14.1 but it has 36gb!

There are many different builds of Qt 5.14.1 (one build for MSVC 2017 32-bit, one build for MSVC 2017 64-bit, one build for MinGW 7.3.0 32-bit, one build for MinGW 7.3.0 64-bit, one build for Android, and so on)

If you select "Qt 5.14.1", you select all the builds. That's why you're seeing 36 GB.

Instead of selecting "Qt 5.14.1," expand it and select a single build that matches your compiler. The libraries for MSVC 2017 32-bit is less than 600 MB:

What is the bare minimum to run Qt/QML applications with cmake?

The easiest way to get started is to use the Qt installer. You just need to select 2 components:

Qt > Qt 5.14.1 > (One build of your choice)

Qt > Developer and Designer Tools > Qt Creator 4.11.1

Note 1: You need a C++ compiler, and this compiler must match the build that you choose. Either install the MSVC compiler from Microsoft, or choose Qt > Developer and Designer Tools > MinGW 7.3.0 xx-bit

Note 2: You can't de-select Qt Creator in the installer, but that's <600 MB.

If you really, really want to avoid installing Qt Creator, then you must build the Qt libraries from source code. Here are the instructions: https://wiki.qt.io/Building_Qt_5_from_Git


问:
create a navigator does not take an argument
I am trying to create Bottom Navigation in React Native project. But I am getting the following error.

Error: Creating a navigator doesn't take an argument. Maybe you are trying to use React Navigation 4 API with React Navigation 5?

App.js

```<code>import React from 'react';
import { createMaterialBottomTabNavigator } from '@react-navigation/material-bottom-tabs';
import { createAppContainer } from 'react-navigation';
import { Icon } from 'react-native-vector-icons';

import Accounts from './src/components/Accounts';
.... importing other screens here...

const Tab = createMaterialBottomTabNavigator(
  {
    Accounts: {
      screen: Accounts,
      navigationOptions: {
        tabBarIcon: ({ tintColor }) => {
          <Icon name={'ios-home'} size={25} style={[{ color: tintColor }]} />
        }
      }
    },
    Categories: { screen: Categories },
    Transactions: { screen: Transactions },
    Budget: { screen: Budget },
    Overview: { screen: Overview }
  },
  {
    initialRouteName: 'Accounts',
    activeColor: '#f0edf6',
    inactiveColor: '#3e2465',
    barStyle: { backgroundColor: '#694fad' }
  }
);

export default createAppContainer(Tab)
</code>```

Index.js

```<code>import React from 'react';
import { AppRegistry } from 'react-native';
import App from './App';
import { name as appName } from './app.json';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import rootReducer from './src/redux/reducers/rootReducer'

const store = createStore(rootReducer)

const Root = () => (
    <Provider store={store}>
        <App />
    </Provider>
)

AppRegistry.registerComponent(appName, () => Root);
</code>```

I want Bottom Navigation with 5 tabs. What is the mistake in my coding?

答:
in v5 creating navigators changed, createMaterialBottomTabNavigator function does not any parameters, u have to use this structure

import { NavigationContainer } from '@react-navigation/native';
import { createMaterialBottomTabNavigator } from '@react-navigation/material-bottom-tabs';

const Tab = createMaterialBottomTabNavigator();

function MyTabs() {
    return (
        <NavigationContainer>
            <Tab.Navigator
                screenOptions={({ route }) => ({
                    tabBarIcon: ({ focused, color, size }) => {
                        let iconName;

                        if (route.name === 'Home') {
                            iconName = focused
                                ? 'ios-information-circle'
                                : 'ios-information-circle-outline';
                        } else if (route.name === 'Settings') {
                            iconName = focused ? 'ios-list-box' : 'ios-list';
                        }

                        // You can return any component that you like here!
                        return <Ionicons name={iconName} size={size} color={color} />;
                    },
                })}
                tabBarOptions={{
                    activeTintColor: 'tomato',
                    inactiveTintColor: 'gray',
                }}

            >
                <Tab.Screen name="Home" component={HomeScreen} />
                <Tab.Screen name="Settings" component={SettingsScreen} />
            </Tab.Navigator>
        </NavigationContainer>
    );
}
```

go here for more details https://reactnavigation.org/docs/en/tab-based-navigation.html

Body:
I am trying to create Bottom Navigation in React Native project. But I am getting the following error.

Error: Creating a navigator doesn't take an argument. Maybe you are trying to use React Navigation 4 API with React Navigation 5?

App.js

import React from 'react';
import { createMaterialBottomTabNavigator } from '@react-navigation/material-bottom-tabs';
import { createAppContainer } from 'react-navigation';
import { Icon } from 'react-native-vector-icons';

import Accounts from './src/components/Accounts';
.... importing other screens here...

const Tab = createMaterialBottomTabNavigator(
  {
    Accounts: {
      screen: Accounts,
      navigationOptions: {
        tabBarIcon: ({ tintColor }) => {
          <Icon name={'ios-home'} size={25} style={[{ color: tintColor }]} />
        }
      }
    },
    Categories: { screen: Categories },
    Transactions: { screen: Transactions },
    Budget: { screen: Budget },
    Overview: { screen: Overview }
  },
  {
    initialRouteName: 'Accounts',
    activeColor: '#f0edf6',
    inactiveColor: '#3e2465',
    barStyle: { backgroundColor: '#694fad' }
  }
);

export default createAppContainer(Tab)

Index.js

import React from 'react';
import { AppRegistry } from 'react-native';
import App from './App';
import { name as appName } from './app.json';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import rootReducer from './src/redux/reducers/rootReducer'

const store = createStore(rootReducer)

const Root = () => (
    <Provider store={store}>
        <App />
    </Provider>
)

AppRegistry.registerComponent(appName, () => Root);

I want Bottom Navigation with 5 tabs. What is the mistake in my coding?

Body:
in v5 creating navigators changed, createMaterialBottomTabNavigator function does not any parameters, u have to use this structure

import { NavigationContainer } from '@react-navigation/native';
import { createMaterialBottomTabNavigator } from '@react-navigation/material-bottom-tabs';

const Tab = createMaterialBottomTabNavigator();

function MyTabs() {
    return (
        <NavigationContainer>
            <Tab.Navigator
                screenOptions={({ route }) => ({
                    tabBarIcon: ({ focused, color, size }) => {
                        let iconName;

                        if (route.name === 'Home') {
                            iconName = focused
                                ? 'ios-information-circle'
                                : 'ios-information-circle-outline';
                        } else if (route.name === 'Settings') {
                            iconName = focused ? 'ios-list-box' : 'ios-list';
                        }

                        // You can return any component that you like here!
                        return <Ionicons name={iconName} size={size} color={color} />;
                    },
                })}
                tabBarOptions={{
                    activeTintColor: 'tomato',
                    inactiveTintColor: 'gray',
                }}

            >
                <Tab.Screen name="Home" component={HomeScreen} />
                <Tab.Screen name="Settings" component={SettingsScreen} />
            </Tab.Navigator>
        </NavigationContainer>
    );
}

go here for more details https://reactnavigation.org/docs/en/tab-based-navigation.html


问:
The smallest `max_arity` of compound terms in ISO Prolog programs
Prolog systems aiming at iso-prolog conformity do not have to support compound terms with arbitrarily large arities. The Prolog flag max_arity reflects this.

According to ISO/IEC 13211-1:1995:

7.11.2.3   Flag: max_arity

Possible values: The default value only

Default value: implementation defined

Changeable: No

Description: The maximum arity allowed for any compound term, or unbounded when the processor has no limit for the number of arguments for a compound term.

So Prolog systems may or may not impose an upper limit on max_arity ... but what about the lower limit?  Is, say, 5 okay?

NO!
ISO/IEC 13211-1:1995/Cor.2:2012, Technical Corrigendum 2, defines call/2..8 as:

8.15.4 call/2..8
 ...

NOTE — A standard-conforming processor may implement call/N in one of the following ways because error condition d is implementation dependent (3.91).

Implement only the seven built-in predicates call/2 up to call/8.

Implement call/2..N up to any N that is within 8..max_arity (7.11.2.3). Produce existence errors for larger arities below max_arity.

Implement call/9 and above only for certain execution modes.

All of these ways only imply Max_arity >= 8—but nothing more.

So my question has (at least) two sides:

Prolog User:

"What is the maximum arity I may use if I want to avoid vendor lock-in?"

Prolog Implementor:

"What is the smallest Max_arity I must support if I aim1 at ISO-Prolog conformity?"

Right now, I'm quite sure the answer is this:

Yes, Max_arity = 8 is okay.

But is it in fact so? Are there clues I am missing?

Footnotes:
 1) I do.

答:
The ISO Prolog standard predicate with the larger number of arguments is sub_atom/5. We can use this predicate to justify at least call/6 and thus a maximum arity of at least 6:

```<code>| ?- call(sub_atom, A, B, C, D, E).
</code>```

Of course, with call/6, nothing prevents the programmer to call e.g.

```<code>| ?- call(foo(A,B,C), D, E, F, G, H)
</code>```

Body:
The ISO Prolog standard predicate with the larger number of arguments is sub_atom/5. We can use this predicate to justify at least call/6 and thus a maximum arity of at least 6:

| ?- call(sub_atom, A, B, C, D, E).

Of course, with call/6, nothing prevents the programmer to call e.g.

| ?- call(foo(A,B,C), D, E, F, G, H)


问:
How should I fill na using the fillna result of the previous row?
Suppose I have the following dataframe...

```<code>money change
2     2
1     1
na    2
na    2
na    1
1     1
</code>```

I would like the na value be the previous value plus the change value from the previous row. Note that non-nan entries do not necessarily follow this pattern.
How should I fill the na entries under column money so that it looks like the following...

```<code>money change
2     2
1     1
2     2
4     2
6     1
1     1
</code>```

答:
I have solved by using simple concept of python's dictionary. Please check:

```<code>dfDict = df.to_dict(orient='records')
prevMoney = 0
prevChange = 0
outDictList = []
for aDict in dfDict:
    curMoney = aDict['money']
    curChange = aDict['change']
    if str(aDict['money'])=='nan':
        aDict['money'] = prevMoney + prevChange
    prevMoney = curMoney
    prevChange = curChange
    outDictList.append(aDict)

pd.DataFrame(outDictList)
</code>```

output:

```<code>   change  money
0     2.0    2.0
1     1.0    1.0
2     2.0    2.0
3     2.0    4.0
4     1.0    6.0
5     1.0    1.0
</code>```

Body:
Suppose I have the following dataframe...

money change
2     2
1     1
na    2
na    2
na    1
1     1

I would like the na value be the previous value plus the change value from the previous row. Note that non-nan entries do not necessarily follow this pattern.
How should I fill the na entries under column money so that it looks like the following...

money change
2     2
1     1
2     2
4     2
6     1
1     1

Body:
I have solved by using simple concept of python's dictionary. Please check:

dfDict = df.to_dict(orient='records')
prevMoney = 0
prevChange = 0
outDictList = []
for aDict in dfDict:
    curMoney = aDict['money']
    curChange = aDict['change']
    if str(aDict['money'])=='nan':
        aDict['money'] = prevMoney + prevChange
    prevMoney = curMoney
    prevChange = curChange
    outDictList.append(aDict)

pd.DataFrame(outDictList)

output:

   change  money
0     2.0    2.0
1     1.0    1.0
2     2.0    2.0
3     2.0    4.0
4     1.0    6.0
5     1.0    1.0


问:
Time Series with Pandas, Python, and Plotly
I'm trying to create a data visualization that's essentially a time series chart. But I have to use Panda, Python, and Plotly, and I'm stuck on how to actually label the dates. Right now, the x labels are just integers from 1 to 60, and when you hover over the chart, you get that integer instead of the date.

I'm pulling values from a Google spreadsheet, and for now, I'd like to avoid parsing csv things.

I'd really like some help on how to label x as dates! Here's what I have so far:

```<code>
import pandas as pd

from matplotlib import pyplot as plt

import bpr

%matplotlib inline

import chart_studio.plotly as pl

import plotly.express as px

import plotly.graph_objects as go

f = open("../credentials.txt")

u = f.readline()

plotly_user = str(u[:-1])

k = f.readline()

plotly_api_key = str(k)

pl.sign_in(username = plotly_user, api_key = plotly_api_key)

rand_x = np.arange(61)

rand_x = np.flip(rand_x)

rand_y = np.array([0.91 , 1 , 1.24 , 1.25 , 1.4 , 1.36 , 1.72 , 1.3 , 1.29 , 1.17 , 1.57 , 1.95 , 2.2 , 2.07 , 2.03 , 2.14 , 1.96 , 1.87 , 1.25 , 1.34 , 1.13 , 1.31 , 1.35 , 1.54 , 1.38 , 1.53 , 1.5 , 1.32 , 1.26 , 1.4 , 1.89 , 1.55 , 1.98 , 1.75 , 1.14 , 0.57 , 0.51 , 0.41 , 0.24 , 0.16 , 0.08 , -0.1 , -0.24 , -0.05 , -0.15 , 0.34 , 0.23 , 0.15 , 0.12 , -0.09 , 0.13 , 0.24 , 0.22 , 0.34 , 0.01 , -0.08 , -0.27 , -0.6 , -0.17 , 0.28 , 0.38])

test_data = pd.DataFrame(columns=['X', 'Y'])

test_data['X'] = rand_x

test_data['Y'] = rand_y

test_data.head()

def create_line_plot(data, x, y, chart_title="Rate by Date", labels_dict={}, c=["indianred"]):

fig = px.line(

data,

x = x,

y = y,

title = chart_title,

labels = labels_dict,

color_discrete_sequence = c

)

fig.show()

return fig

fig = create_line_plot(test_data, 'X', 'Y', labels_dict={'X': 'Date', 'Y': 'Rate (%)'}) ```
```

答:
Right now, the x labels are just integers from 1 to 60, and when you hover over the chart, you get that integer instead of the date.

This happens because you are setting rand_x as x labels, and rand_x is an array of integer. Setting labels_dict={'X': 'Date', 'Y': 'Rate (%)'} only adding text Date before x value. What you need to do is parsing an array of datetime values into x. For example:

```<code>rand_x = np.array(['2020-01-01','2020-01-02','2020-01-03'], dtype='datetime64')
</code>```

Body:
I'm trying to create a data visualization that's essentially a time series chart. But I have to use Panda, Python, and Plotly, and I'm stuck on how to actually label the dates. Right now, the x labels are just integers from 1 to 60, and when you hover over the chart, you get that integer instead of the date.

I'm pulling values from a Google spreadsheet, and for now, I'd like to avoid parsing csv things.

I'd really like some help on how to label x as dates! Here's what I have so far:

import pandas as pd

from matplotlib import pyplot as plt

import bpr

%matplotlib inline

import chart_studio.plotly as pl

import plotly.express as px

import plotly.graph_objects as go

f = open("../credentials.txt")

u = f.readline()

plotly_user = str(u[:-1])

k = f.readline()

plotly_api_key = str(k)

pl.sign_in(username = plotly_user, api_key = plotly_api_key)

rand_x = np.arange(61)

rand_x = np.flip(rand_x)

rand_y = np.array([0.91 , 1 , 1.24 , 1.25 , 1.4 , 1.36 , 1.72 , 1.3 , 1.29 , 1.17 , 1.57 , 1.95 , 2.2 , 2.07 , 2.03 , 2.14 , 1.96 , 1.87 , 1.25 , 1.34 , 1.13 , 1.31 , 1.35 , 1.54 , 1.38 , 1.53 , 1.5 , 1.32 , 1.26 , 1.4 , 1.89 , 1.55 , 1.98 , 1.75 , 1.14 , 0.57 , 0.51 , 0.41 , 0.24 , 0.16 , 0.08 , -0.1 , -0.24 , -0.05 , -0.15 , 0.34 , 0.23 , 0.15 , 0.12 , -0.09 , 0.13 , 0.24 , 0.22 , 0.34 , 0.01 , -0.08 , -0.27 , -0.6 , -0.17 , 0.28 , 0.38])

test_data = pd.DataFrame(columns=['X', 'Y'])

test_data['X'] = rand_x

test_data['Y'] = rand_y

test_data.head()

def create_line_plot(data, x, y, chart_title="Rate by Date", labels_dict={}, c=["indianred"]):

fig = px.line(

data,

x = x,

y = y,

title = chart_title,

labels = labels_dict,

color_discrete_sequence = c

)

fig.show()

return fig

fig = create_line_plot(test_data, 'X', 'Y', labels_dict={'X': 'Date', 'Y': 'Rate (%)'}) ```

Body:
Right now, the x labels are just integers from 1 to 60, and when you hover over the chart, you get that integer instead of the date.

This happens because you are setting rand_x as x labels, and rand_x is an array of integer. Setting labels_dict={'X': 'Date', 'Y': 'Rate (%)'} only adding text Date before x value. What you need to do is parsing an array of datetime values into x. For example:

rand_x = np.array(['2020-01-01','2020-01-02','2020-01-03'], dtype='datetime64')


问:
NewSoftSerial library is not working for me
I am trying to get the data from GY-NEO6MV2 GPS and I've tried every solution, but I stil get error:
C:\Users\Szymon\Documents\Arduino\libraries\NewSoftSerial\NewSoftSerial.cpp:43:10: fatal error: WConstants.h: No such file or directory

I use the most simple possible code, it only includes the library and does nothing else, so it's not a problem with my code.
None of the solutions from the internet is working, anybody has an idea why it is not working?

答:
Okay, thank you Juraj for help.
I used the Serial1 to obtain data from the GPS and it worked.
The code if someone also has that problem:</p>

```<code>void setup() {
  Serial1.begin(9600);
  SerialUSB.begin(9600);
}

void loop() {
  if (Serial1.available()) {
    char outp = Serial1.read();
    SerialUSB.print(outp);
  }
}
</code>```

Body:
Okay, thank you Juraj for help.
I used the Serial1 to obtain data from the GPS and it worked.
The code if someone also has that problem:

void setup() {
  Serial1.begin(9600);
  SerialUSB.begin(9600);
}

void loop() {
  if (Serial1.available()) {
    char outp = Serial1.read();
    SerialUSB.print(outp);
  }
}


问:
Access-Control-Allow-Origin header response in Laravel 5.4 not working for POST
I followed the instructions from this post and applied the following to my Laravel 5.4 backend which is a REST API for my Angular web client.

First I installed the Cors middleware

```<code>php artisan make:middleware Cors
</code>```

I went to app/Http/Middleware/Cors.php and added the two headers:

public function handle($request, Closure $next)
{
    return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
```

<p>I added <code>'cors' => \App\Http\Middleware\Cors::class</code> to <code>$routeMiddleware</code> in <code>app/Http/Kernel.php</code>. </p>

<pre class="lang-php prettyprint-override"><code>protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'cors' => \App\Http\Middleware\Cors::class,
];
</code>```

and finally added middleware('cors') to the api routes mapping as such:

protected function mapApiRoutes()
{
    Route::prefix('api')
         ->middleware('api')
         ->middleware('cors')
         ->namespace($this->namespace)
         ->group(base_path('routes/api.php'));
}
```

<p>However, only my <code>GET</code> request is working:</p>

<pre class="lang-js prettyprint-override"><code>onSubmit() {
  // Fails: "No 'Access-Control-Allow-Origin' header is present.."
  console.log('Submit ..');
  this.http.post('http://localhost:8080/api/register', JSON.stringify(this.registerForm.value))
    .subscribe(
        data => alert('yay'),
        err => alert(err.error.message)
    );
}

onCancel() {
  // Is working..
  console.log('Cancel ..');
  this.http.get('http://localhost:8080/api/helloworld')
    .subscribe(
      data => alert(data),
      err => alert('error')
    );
}
</code>```

Any idea why only the GET request works but not the POST?

This is how I create the routes in the api.php file:

Route::get('/helloworld', function (Request $request) {
    return ['Hello World!'];
});

Route::post('/register', function (Request $request) {
    // dd($request->input("email"));
    return ['register'];
});
```

<p>Response for the <code>GET</code> call:</p>

```Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Cache-Control:no-cache, private
Connection:close
Content-Type:application/json
Date:Sat, 28 Oct 2017 15:14:27 GMT
Host:localhost:8080
X-Powered-By:PHP/7.0.22-0ubuntu0.16.04.1
```

<p>Response for the <code>POST</code> call:</p>

```Allow:POST
Cache-Control:no-cache, private
Connection:close
Content-Type:text/html; charset=UTF-8
Date:Sat, 28 Oct 2017 15:10:30 GMT
Host:localhost:8080
X-Powered-By:PHP/7.0.22-0ubuntu0.16.04.1
```

as you can see, for some reason the headers are not set in the POST response.

答:
when working with laravel, often, that error doesnt mean its from the post request, nor from your CORS.php or KERNEL. it can mean a lot of things even database column none existence, and due to the fact the request is coming from another server, laravel tries to hide the specific error in chrome, throwing that error. to know the specific error and debug it, you should use postman, to trigger that route, and send that request, postman will give you the right error message.
but also replace your cors.php with this instead </p>

<pre class="lang-php prettyprint-override"><code>$response = $next($request);
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
$response->headers->set('Access-Control-Allow-Headers',' Origin, Content-Type, Accept, Authorization, X-Request-With, X-Auth-Token');
$response->headers->set('Access-Control-Allow-Credentials',' true');
return $response;
</code>```

Body:
I followed the instructions from this post and applied the following to my Laravel 5.4 backend which is a REST API for my Angular web client.

First I installed the Cors middleware

php artisan make:middleware Cors

I went to app/Http/Middleware/Cors.php and added the two headers:

public function handle($request, Closure $next)
{
    return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}

I added 'cors' => \App\Http\Middleware\Cors::class to $routeMiddleware in app/Http/Kernel.php.

protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'cors' => \App\Http\Middleware\Cors::class,
];

and finally added middleware('cors') to the api routes mapping as such:

protected function mapApiRoutes()
{
    Route::prefix('api')
         ->middleware('api')
         ->middleware('cors')
         ->namespace($this->namespace)
         ->group(base_path('routes/api.php'));
}

However, only my GET request is working:

onSubmit() {
  // Fails: "No 'Access-Control-Allow-Origin' header is present.."
  console.log('Submit ..');
  this.http.post('http://localhost:8080/api/register', JSON.stringify(this.registerForm.value))
    .subscribe(
        data => alert('yay'),
        err => alert(err.error.message)
    );
}

onCancel() {
  // Is working..
  console.log('Cancel ..');
  this.http.get('http://localhost:8080/api/helloworld')
    .subscribe(
      data => alert(data),
      err => alert('error')
    );
}

Any idea why only the GET request works but not the POST?

This is how I create the routes in the api.php file:

Route::get('/helloworld', function (Request $request) {
    return ['Hello World!'];
});

Route::post('/register', function (Request $request) {
    // dd($request->input("email"));
    return ['register'];
});

Response for the GET call:

Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Cache-Control:no-cache, private
Connection:close
Content-Type:application/json
Date:Sat, 28 Oct 2017 15:14:27 GMT
Host:localhost:8080
X-Powered-By:PHP/7.0.22-0ubuntu0.16.04.1

Response for the POST call:

Allow:POST
Cache-Control:no-cache, private
Connection:close
Content-Type:text/html; charset=UTF-8
Date:Sat, 28 Oct 2017 15:10:30 GMT
Host:localhost:8080
X-Powered-By:PHP/7.0.22-0ubuntu0.16.04.1

as you can see, for some reason the headers are not set in the POST response.

Body:
when working with laravel, often, that error doesnt mean its from the post request, nor from your CORS.php or KERNEL. it can mean a lot of things even database column none existence, and due to the fact the request is coming from another server, laravel tries to hide the specific error in chrome, throwing that error. to know the specific error and debug it, you should use postman, to trigger that route, and send that request, postman will give you the right error message.
but also replace your cors.php with this instead

$response = $next($request);
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
$response->headers->set('Access-Control-Allow-Headers',' Origin, Content-Type, Accept, Authorization, X-Request-With, X-Auth-Token');
$response->headers->set('Access-Control-Allow-Credentials',' true');
return $response;


问:
Uncaught TypeError: Cannot read property 'innerHTML' of null
Keep getting this error, no idea why

Uncaught TypeError: Cannot read property 'innerHTML' of null

My code is:

```<code>function write(message) {
  document.getElementById('message').innerHTML += message + '<br/>';
}

function calculateCircumference (diameter) {
    return diameter * 3.14;
}

write (calculateCircumference(4));
</code>```

答: If you have your id is set and you still get the same error, make sure you have done the opening and closing tags of your html correctly.</p>

Body:
Keep getting this error, no idea why

Uncaught TypeError: Cannot read property 'innerHTML' of null

My code is:

function write(message) {
  document.getElementById('message').innerHTML += message + '
';
}

function calculateCircumference (diameter) {
    return diameter * 3.14;
}

write (calculateCircumference(4));


问:
Oracle SQL select query compare 2 columns
I have a table with these two columns:

```<code>USERNAME    EMAIL_ADDRESS
------------------------------
username1   username1@abc.com
username2   username2@abc.com
username3   username3@abc.com
</code>```

The first column is the username and the second column is <username> with email domain along with it.

How can I compare the two columns using Oracle SQL to find if there are any rows where the email_address column doesn't have the correct corresponding username in the email address format?

答:
You can use Regex

```<code>SELECT * FROM your_table where username_col != REGEXP_SUBSTR(email_col, '([^@]+)')

//regex ([^@]+) matches any string before @ character
</code>```

Example db fiddle example

```<code>WITH  da(usr, eml) AS
       (SELECT 'username1', 'username1@abc.com' FROM DUAL UNION ALL
        SELECT 'username2', 'username2@abc.com' FROM DUAL UNION ALL
        SELECT 'username_odd', 'username3@abc.com' FROM DUAL UNION ALL
        SELECT 'username4', 'username4@abc.com' FROM DUAL)
SELECT * FROM da  where usr != REGEXP_SUBSTR(eml, '([^@]+)')
</code>```

Body:
I have a table with these two columns:

USERNAME    EMAIL_ADDRESS
------------------------------
username1   username1@abc.com
username2   username2@abc.com
username3   username3@abc.com

The first column is the username and the second column is <username> with email domain along with it.

How can I compare the two columns using Oracle SQL to find if there are any rows where the email_address column doesn't have the correct corresponding username in the email address format?

Body:
You can use Regex

SELECT * FROM your_table where username_col != REGEXP_SUBSTR(email_col, '([^@]+)')

//regex ([^@]+) matches any string before @ character

Example db fiddle example

WITH  da(usr, eml) AS
       (SELECT 'username1', 'username1@abc.com' FROM DUAL UNION ALL
        SELECT 'username2', 'username2@abc.com' FROM DUAL UNION ALL
        SELECT 'username_odd', 'username3@abc.com' FROM DUAL UNION ALL
        SELECT 'username4', 'username4@abc.com' FROM DUAL)
SELECT * FROM da  where usr != REGEXP_SUBSTR(eml, '([^@]+)')


问:
Showing error for multiple empty inputs vuejs vuetify
I have three inputs as externalIP as External Host, externalHttpPort as Port and vendor as Vendor, I want to show error message if any of them is missing. but being specific about the name,

```<code>if (!this.externalIP || !this.externalHttpPort || !this.vendor) {
</code>```

when I do if condition, this works but I am not sure how I can tell if which input is empty. only one way which left is to add 3 multiple if

something like this

```<code>  let error;
  error = !this.externalIP
    ? "External IP Address (or URL) is incorrect"
    : "" || !this.externalHttpPort
    ? "Port is missing" : "" || !this.vendor
    ? "Please choose camera vendor or add your camera snapshot URL." : ""
  if (!error == "") {
    this.setNotification({
      text: error,
      color: "warning",
      snackbar: true
    })
    return
  }
</code>```

is there any other way of doing it? Also, Eslint show warning on indentations as well

答:
Well, you may assign an error field variable within your error-checking condition.

Example for three variables and an emptyField variable denoting the empty variable name:

```<code>if ((!a && (emptyField = "a")) ||
    (!b && (emptyField = "b")) ||
    (!c && (emptyField = "c"))) {
    alert("Field " + emptyField + " is empty...");
}
</code>```

Since JS lazily evaluates its arguments, emptyField = "a" will get executed only if !a is true.

Just note that lazy evaluation also causes the evaluation of conditions stop once a condition was hit, thus if a is null and also b is null, the alert would announce that "Field a is empty..."

Body:
I have three inputs as externalIP as External Host, externalHttpPort as Port and vendor as Vendor, I want to show error message if any of them is missing. but being specific about the name,

if (!this.externalIP || !this.externalHttpPort || !this.vendor) {

when I do if condition, this works but I am not sure how I can tell if which input is empty. only one way which left is to add 3 multiple if

something like this

  let error;
  error = !this.externalIP
    ? "External IP Address (or URL) is incorrect"
    : "" || !this.externalHttpPort
    ? "Port is missing" : "" || !this.vendor
    ? "Please choose camera vendor or add your camera snapshot URL." : ""
  if (!error == "") {
    this.setNotification({
      text: error,
      color: "warning",
      snackbar: true
    })
    return
  }

is there any other way of doing it? Also, Eslint show warning on indentations as well

Body:
Well, you may assign an error field variable within your error-checking condition.

Example for three variables and an emptyField variable denoting the empty variable name:

if ((!a && (emptyField = "a")) ||
    (!b && (emptyField = "b")) ||
    (!c && (emptyField = "c"))) {
    alert("Field " + emptyField + " is empty...");
}

Since JS lazily evaluates its arguments, emptyField = "a" will get executed only if !a is true.

Just note that lazy evaluation also causes the evaluation of conditions stop once a condition was hit, thus if a is null and also b is null, the alert would announce that "Field a is empty..."


问:
Alternatives to Thread.Sleep()
Every N minutes we want to run through a list of tasks.  So we've created a task executor with a

```<code>do { DoWork(); }while(!stopRequested)
</code>```

Now we want to have a pause between work cycles.  Everyone seems to think Thread.Sleep() is the devil.  I've seen mention of using Monitor/Event stuff but we don't have someone else telling us to do work.  We just want to do stuff every N minutes like clockwork.

So is there an alternative or have I found a valid use of Thread.Sleep?

Someone in another post mentioned WaitHandle.WaitOne() as an alternative but you can't call that from a non-static method apparently?  Or at least I can't because I get a compile time error of..

An object reference is required for
  the non-static field, method, or
  property
  'System.Threading.WaitHandle.WaitOne(System.TimeSpan)'

答:
By my understanding, Thread.Sleep() is bad because it forces the thread's resources out of the cache, so they have to be loaded again afterwards.  Not a big deal, but it could aggravate performance issues in high-load situations.  And then there's the fact that the timing isn't precise, and that it effectively can't wait for durations under about 10ms...

I use this snippet:

```<code>new System.Threading.ManualResetEvent(false).WaitOne(1000);
</code>```

Easy as pie and it all fits on one line.  Creates a new event handler that will never be set, and then waits the full timeout period, which you specify as the argument to WaitOne().

Although, for this specific scenario, a Timer would probably be a more appropriate approach:

```<code>var workTimer = new System.Threading.Timer(
    (x) => DoWork(),
    null,
    1000, // initial wait period
    300000); // subsequent wait period
</code>```

Then, instead of setting a cancel variable, you would stop the timer with workTimer.Stop().

Edit:

Since people are still finding this useful, I should add that .NET 4.5 introduces the Task.Delay method, which is even more concise and also supports async:

```<code>Task.Delay(2000).Wait(); // Wait 2 seconds with blocking
await Task.Delay(2000); // Wait 2 seconds without blocking
</code>```

ContentLicense: CC BY-SA 2.5

Title: Alternatives to Thread.Sleep()

Body:
Every N minutes we want to run through a list of tasks.  So we've created a task executor with a

do { DoWork(); }while(!stopRequested)

Now we want to have a pause between work cycles.  Everyone seems to think Thread.Sleep() is the devil.  I've seen mention of using Monitor/Event stuff but we don't have someone else telling us to do work.  We just want to do stuff every N minutes like clockwork.

So is there an alternative or have I found a valid use of Thread.Sleep?

Someone in another post mentioned WaitHandle.WaitOne() as an alternative but you can't call that from a non-static method apparently?  Or at least I can't because I get a compile time error of..

An object reference is required for
  the non-static field, method, or
  property
  'System.Threading.WaitHandle.WaitOne(System.TimeSpan)'

Body:
By my understanding, Thread.Sleep() is bad because it forces the thread's resources out of the cache, so they have to be loaded again afterwards.  Not a big deal, but it could aggravate performance issues in high-load situations.  And then there's the fact that the timing isn't precise, and that it effectively can't wait for durations under about 10ms...

I use this snippet:

new System.Threading.ManualResetEvent(false).WaitOne(1000);

Easy as pie and it all fits on one line.  Creates a new event handler that will never be set, and then waits the full timeout period, which you specify as the argument to WaitOne().

Although, for this specific scenario, a Timer would probably be a more appropriate approach:

var workTimer = new System.Threading.Timer(
    (x) => DoWork(),
    null,
    1000, // initial wait period
    300000); // subsequent wait period

Then, instead of setting a cancel variable, you would stop the timer with workTimer.Stop().

Edit:

Since people are still finding this useful, I should add that .NET 4.5 introduces the Task.Delay method, which is even more concise and also supports async:

Task.Delay(2000).Wait(); // Wait 2 seconds with blocking
await Task.Delay(2000); // Wait 2 seconds without blocking


问:
Is it possible to assign a pod of StatefulSet to a specific node of a Kubernetes cluster?
I have a 5 node cluster(1-master/4-worker). Is it possible to configure a StatefulSet where I can make a pod(s) to run on a given node knowing it has sufficient capacity rather Kubernetes Scheduler making this decision?

Lets say, my StatefulSet create 4 pods(replicas: 4) as myapp-0,myapp-1,myapp-2 and myapp-3. Now what I am looking for is:

myapp-0 pod-- get scheduled over---> worker-1

myapp-1 pod-- get scheduled over---> worker-2

myapp-2 pod-- get scheduled over---> worker-3

myapp-3 pod-- get scheduled over---> worker-4

Please let me know if it can be achieved somehow? Because if I add a toleration to pods of a StatefulSet, it will be same for all the pods and all of them will get scheduled over a single node matching the taint.

Thanks, J

答:
You can use podAntiAffinity to distribute replicas to different nodes.

```<code>apiVersion: v1
kind: Service
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  ports:
  - port: 80
    name: web
  clusterIP: None
  selector:
    app: nginx
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: web
spec:
  serviceName: "nginx"
  replicas: 4
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: k8s.gcr.io/nginx-slim:0.8
        ports:
        - containerPort: 80
          name: web
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              matchExpressions:
              - key: app
                operator: In
                values:
                - nginx
            topologyKey: "kubernetes.io/hostname"
</code>```

This would deploy web-0 in worker1 , web-1 in worker2, web-2 in worker3 and web-3 in worker4.

Body:
You can use podAntiAffinity to distribute replicas to different nodes.

apiVersion: v1
kind: Service
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  ports:
  - port: 80
    name: web
  clusterIP: None
  selector:
    app: nginx
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: web
spec:
  serviceName: "nginx"
  replicas: 4
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: k8s.gcr.io/nginx-slim:0.8
        ports:
        - containerPort: 80
          name: web
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              matchExpressions:
              - key: app
                operator: In
                values:
                - nginx
            topologyKey: "kubernetes.io/hostname"

This would deploy web-0 in worker1 , web-1 in worker2, web-2 in worker3 and web-3 in worker4.


问:
ddev exec: command not found (.bash_aliases)
In a local ddev instance, I have added a few aliases and functions to .ddev/homeadditions/bash_aliases.

For example: alias ll="ls -lhA"

While ddev ssh and then ll will work, ddev exec ll returns

```<code>bash: ll: command not found
Failed to execute command ll: exit status 127
</code>```

Why?

答:
Here's an example of my setup (actually, I have scripts more than just ll)

.ddev/docker-compose.env.yaml

```<code>version: '3.6'

services:
  web:
    environment:
    - PROD_USER=foo
    - PROD_SERVER=bar.com
    - PROD_ROOT=path/to/root
    - LOCAL_ROOT=that/path/to/root
    - ASSET_DIRS=bi ba bu
</code>```

.ddev/commands/web/sync_down_files

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

# rsync prod assets to local

# download all assets
for directory in ${ASSET_DIRS} ; do
    rsync -zra \
        --delete \
        --exclude='.env' \
        ${PROD_USER}@${PROD_SERVER}:/home/${PROD_USER}/${PROD_ROOT}/$directory \
        ${LOCAL_ROOT};
done
</code>```

Now I do ddev sync_down_files and get all remote assets into the local site. Same for the db.

Body:
In a local ddev instance, I have added a few aliases and functions to .ddev/homeadditions/bash_aliases.

For example: alias ll="ls -lhA"

While ddev ssh and then ll will work, ddev exec ll returns

bash: ll: command not found
Failed to execute command ll: exit status 127

Why?

Body:
Here's an example of my setup (actually, I have scripts more than just ll)

.ddev/docker-compose.env.yaml

version: '3.6'

services:
  web:
    environment:
    - PROD_USER=foo
    - PROD_SERVER=bar.com
    - PROD_ROOT=path/to/root
    - LOCAL_ROOT=that/path/to/root
    - ASSET_DIRS=bi ba bu

.ddev/commands/web/sync_down_files

#!/bin/bash

# rsync prod assets to local

# download all assets
for directory in ${ASSET_DIRS} ; do
    rsync -zra \
        --delete \
        --exclude='.env' \
        ${PROD_USER}@${PROD_SERVER}:/home/${PROD_USER}/${PROD_ROOT}/$directory \
        ${LOCAL_ROOT};
done

Now I do ddev sync_down_files and get all remote assets into the local site. Same for the db.


问:
Combine columns from a table into a JSON object
I have a table in athena with data

```<code>type   state   city  zipcode
-------------------------------
hot     az     phx    85281
hot     tx     dal    12345
cool    wa     sea    67890
cool    ny     nyc    67856
</code>```

I want the output to be like

```<code>type   Data
-------------
hot    {state: az, city:phx, zipcode: 85281}
hot    {state: tx, city:dal, zipcode: 12345}
cool   {state: wa, city:sea, zipcode: 67890}
cool   {state: ny, city:nyc, zipcode: 67856}
</code>```

I am trying to use the aggregate function but i'm unable to use it.

SELECT type, CAST(MAP(ARRAY['state', 'city', 'zipcode'], ARRAY[state,city,zipcode] ) AS JSON) FROM "test"."alldata"

but the query fails.

答:
For Hive:

```<code>with mydata as (
select stack(4,
    'hot', 'az', 'phx', 85281,
    'hot', 'tx', 'dal', 12345,
    'cool', 'wa', 'sea', 67890,
    'cool', 'ny', 'nyc', 67856
) as  (type, state, city, zipcode)
)

select type, map('state', state, 'city', city,'zipcode',zipcode) as data
 from mydata;
</code>```

Result:

```<code>type    data
hot     {"state":"az","city":"phx","zipcode":"85281"}
hot     {"state":"tx","city":"dal","zipcode":"12345"}
cool    {"state":"wa","city":"sea","zipcode":"67890"}
cool    {"state":"ny","city":"nyc","zipcode":"67856"}
</code>```

If you need string type, use brickhouse library:

```<code>add jar /path/brickhouse-0.7.0-SNAPSHOT.jar; --compile jar and load it to the distributed cache
CREATE TEMPORARY FUNCTION to_json AS 'brickhouse.udf.json.ToJsonUDF';

select type, to_json(map('state', state, 'city', city,'zipcode',zipcode)) as data
 from mydata;
</code>```

Body:
I have a table in athena with data

type   state   city  zipcode
-------------------------------
hot     az     phx    85281
hot     tx     dal    12345
cool    wa     sea    67890
cool    ny     nyc    67856

I want the output to be like

type   Data
-------------
hot    {state: az, city:phx, zipcode: 85281}
hot    {state: tx, city:dal, zipcode: 12345}
cool   {state: wa, city:sea, zipcode: 67890}
cool   {state: ny, city:nyc, zipcode: 67856}

I am trying to use the aggregate function but i'm unable to use it.

SELECT type, CAST(MAP(ARRAY['state', 'city', 'zipcode'], ARRAY[state,city,zipcode] ) AS JSON) FROM "test"."alldata"

but the query fails.

Body:
For Hive:

with mydata as (
select stack(4,
    'hot', 'az', 'phx', 85281,
    'hot', 'tx', 'dal', 12345,
    'cool', 'wa', 'sea', 67890,
    'cool', 'ny', 'nyc', 67856
) as  (type, state, city, zipcode)
)

select type, map('state', state, 'city', city,'zipcode',zipcode) as data
 from mydata;

Result:

type    data
hot     {"state":"az","city":"phx","zipcode":"85281"}
hot     {"state":"tx","city":"dal","zipcode":"12345"}
cool    {"state":"wa","city":"sea","zipcode":"67890"}
cool    {"state":"ny","city":"nyc","zipcode":"67856"}

If you need string type, use brickhouse library:

add jar /path/brickhouse-0.7.0-SNAPSHOT.jar; --compile jar and load it to the distributed cache
CREATE TEMPORARY FUNCTION to_json AS 'brickhouse.udf.json.ToJsonUDF';

select type, to_json(map('state', state, 'city', city,'zipcode',zipcode)) as data
 from mydata;


问:
ASP.Net Using POST with Server.Execute
I'm trying to do something like

```<code>Server.Execute("page1.aspx");
</code>```

but I need to pass POST data to this page.

Does anyone know how I can achieve this? Since Server.Execute only takes in 3 params, and none of these are anything to do with POST data.

Solution: 7 Hours Later...

Unfortunately, the only way I was able to do this was to pass the parameters in the query string (using a GET request). I've searched the web for a while now, and finally felt this was good enough for my application. I tested, and somehow the GET URL size limit of 4K chars does not hold good in this context.

I was able to successfully execute a Server.Execute method with 640K+ chars to another page, and it worked beautifully.

```<code>Server.Execute("~/pageB.aspx?foo=" + new string('x', 640000));
</code>```

In pageB: Page_Load();

```<code>Response.Write(Request["foo"].ToString().Length());
</code>```

Result: 640000

So I guess this will have to do for now.

I was afraid of having to send large parameters in the query string, but since it works, who am I to complain! :)

答:
Is using Server.Execute() absolutely necessary?

If not, to get page A to post to page B, you could set page A's .PostBackURL to page B, then in page B check if (this.PreviousPage != null); if it's not null, then in page B you can use something like  this.PreviousPage.FindControl() or ((PageA)this.PreviousPage).txtFirstName.Text to get at the input values.

If some values aren't directly user-input, you could still assign the values to hidden controls, and make those hidden controls public properties of page A so that page B can access them after casting .PreviousPage to PageA.

If you don't want to require type-safe references to a specific sending class or interface, the simplest alternative would probably be to use something like this technique to encapsulate values in Context.Items:

```<code>// to store in sending page:
Context.Items("UserName") = UserName.text;
// then call server.Transfer...

// to retrieve in receiving page:
string userName = (string)Context.Items("UserName");
</code>```

Title: ASP.Net Using POST with Server.Execute

Body:
I'm trying to do something like

Server.Execute("page1.aspx");

but I need to pass POST data to this page.

Does anyone know how I can achieve this? Since Server.Execute only takes in 3 params, and none of these are anything to do with POST data.

Solution: 7 Hours Later...

Unfortunately, the only way I was able to do this was to pass the parameters in the query string (using a GET request). I've searched the web for a while now, and finally felt this was good enough for my application. I tested, and somehow the GET URL size limit of 4K chars does not hold good in this context.

I was able to successfully execute a Server.Execute method with 640K+ chars to another page, and it worked beautifully.

Server.Execute("~/pageB.aspx?foo=" + new string('x', 640000));

In pageB: Page_Load();

Response.Write(Request["foo"].ToString().Length());

Result: 640000

So I guess this will have to do for now.

I was afraid of having to send large parameters in the query string, but since it works, who am I to complain! :)

Body:
Is using Server.Execute() absolutely necessary?

If not, to get page A to post to page B, you could set page A's .PostBackURL to page B, then in page B check if (this.PreviousPage != null); if it's not null, then in page B you can use something like  this.PreviousPage.FindControl() or ((PageA)this.PreviousPage).txtFirstName.Text to get at the input values.

If some values aren't directly user-input, you could still assign the values to hidden controls, and make those hidden controls public properties of page A so that page B can access them after casting .PreviousPage to PageA.

If you don't want to require type-safe references to a specific sending class or interface, the simplest alternative would probably be to use something like this technique to encapsulate values in Context.Items:

// to store in sending page:
Context.Items("UserName") = UserName.text;
// then call server.Transfer...

// to retrieve in receiving page:
string userName = (string)Context.Items("UserName");


问:
How do you return an array of structs from a function in C?
I'm trying to create an array of structs and fread file data in to the array inside a helper function. I keep getting incompatible pointer type errors when I compile the program. This is my current code:

```<code> struct fentry *read_fentries(FILE *fp){
    fentry *files[MAXFILES];

    // EXTRACT FENTRIES AND FNODES FROM FILE
    if ((fread(files, sizeof(fentry), MAXFILES, fp)) == 0) {
        fprintf(stderr, "Error: could not read file entries\n");
        closefs(fp);
        exit(1);
    }
    return files;
}
</code>```

My main question is how can I create an array of structs of a pre-defined size (MAXFILES) and return it from a function so that I can access the struct array inside my main. Would I have to allocate memory using malloc?

答:
You have to allocate space for it with malloc for example, because as you see from the error you returning a pointer to a local address, which is a problem since once you exit this function the files array will be freed/non existent. So you returning pointer will point to an invalid memory location.

So do something like this:

```<code>struct fentry *files = malloc(MAXFILES * sizeof(fentry);
</code>```

Also in this case do not forget to free the allocated memory with free(*ptr_to_array) when does not needed anymore.

Body:
I'm trying to create an array of structs and fread file data in to the array inside a helper function. I keep getting incompatible pointer type errors when I compile the program. This is my current code:

 struct fentry *read_fentries(FILE *fp){
    fentry *files[MAXFILES];

    // EXTRACT FENTRIES AND FNODES FROM FILE
    if ((fread(files, sizeof(fentry), MAXFILES, fp)) == 0) {
        fprintf(stderr, "Error: could not read file entries\n");
        closefs(fp);
        exit(1);
    }
    return files;
}

My main question is how can I create an array of structs of a pre-defined size (MAXFILES) and return it from a function so that I can access the struct array inside my main. Would I have to allocate memory using malloc?

Body:
You have to allocate space for it with malloc for example, because as you see from the error you returning a pointer to a local address, which is a problem since once you exit this function the files array will be freed/non existent. So you returning pointer will point to an invalid memory location.

So do something like this:

struct fentry *files = malloc(MAXFILES * sizeof(fentry);

Also in this case do not forget to free the allocated memory with free(*ptr_to_array) when does not needed anymore.


问:
Increment the time by 15 mins in Java
I am able to get the time in format of 2020-02-10T11:30:00.000 as a start_time and end_time as 2020-02-10T11:45:00.000 as increment of 15 mins, now i want assign end_time into start_time, as well as end_time need to increase by 15 mins. This is where i am getting difficulty.

below is my code,

public class DateUtil {

    final static String PATTERN = "yyyy-MM-dd" +"\'T\'" +"HH:mm:00.000";
    SimpleDateFormat simpleDateFormat = null;

    DateFarmatorDemo dateFarmatorDemo = new DateFarmatorDemo();
    DateFormat dateFormat = null;

    static String start_date = null;
    static String end_date = null;
    static String temp_date = null;

    public void requiredDate() {

         Calendar start_date1 = Calendar.getInstance();
         start_date1.add(Calendar.DAY_OF_MONTH, -1);

         Calendar end_date1 = Calendar.getInstance();
         end_date1.add(Calendar.DAY_OF_MONTH, -1);
         end_date1.add(Calendar.MINUTE, +15);

         dateFormat = new SimpleDateFormat(PATTERN);
         start_date= dateFormat.format(start_date1.getTime());
         end_date= dateFormat.format(end_date1.getTime());

         for(int i=0; i <=10 ; i++) {
        //end_date= dateFormat.format(start_date1.getTime());
        //increment by 15 mins to end_date

                dateFarmatorDemo.setStart_Date(start_date);
                System.out.println("Start Date ->  "+ dateFarmatorDemo.getStart_Date());

                dateFarmatorDemo.setEnd_Date(end_date);
                System.out.println("End Date ->  " + dateFarmatorDemo.getEnd_Date());

                System.out.println("-----------------------------------------");
         }
    }
}
```

答:
You are using terrible legacy classes. Use only java.time classes instead.

Your Question is not clear as to your exact goal. But this should get you close.

Capture the current moment is seen in a particular time zone.

```<code>ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
</code>```

Add your 15 minutes.

```<code>ZonedDateTime later = zdt.plusMinutes( 15 ) ;
</code>```

If parsing input strings in standard ISO 8601 format but lacking time zone or offset, parse as LocalDateTime objects.

```<code>LocalDateTime ldt = LocalDateTime.parse( "2020-01-23T15:30:00" );
</code>```

Assign the time zone intended for that input, to determine a moment, a point on the timeline.

```<code>ZonedDateTime zdt = ldt.atZone( z ) ;
</code>```

Title: Increment the time by 15 mins in Java

Body:
You are using terrible legacy classes. Use only java.time classes instead.

Your Question is not clear as to your exact goal. But this should get you close.

Capture the current moment is seen in a particular time zone.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;

Add your 15 minutes.

ZonedDateTime later = zdt.plusMinutes( 15 ) ;

If parsing input strings in standard ISO 8601 format but lacking time zone or offset, parse as LocalDateTime objects.

LocalDateTime ldt = LocalDateTime.parse( "2020-01-23T15:30:00" );

Assign the time zone intended for that input, to determine a moment, a point on the timeline.

ZonedDateTime zdt = ldt.atZone( z ) ;


问:
Query with switch function requests parameter value
Background: Excel worksheet as front end to an Access database.  Excel contains VBA code and uses ADODB to move values into and out of the tables in Access.

One column is a composite value which describes a complex priority relationship.  One digit for priority level (1-6), one letter for more granular level (A-C), and a type of project (Safety, Security, Enviro, etc.)  The values look like "2B - Maint.", "2A - ProcCntl"

I need to sort the results of a select * query in different ways.  Sometimes with the typical Alpha sort which would list 1A values before 1B before 4C.  Other times I need to sort all the Safety as a group, Maint. as another, etc. A simple alpha sort on the project type doesn't work because the manager wants a specific order.

I am using the Switch function to assign the order.  I have found a couple of ways to make this work in Access but they all ask for a parameter value when I run the query. Entering a blank value gets the desired result.  Moving the query into the VBA of Excel returns an error complaining of an empty parameter.

Here is one of the "working" queries:

SELECT *, Mid([Priority],6,2) AS ProjClass,
  Switch(ProjClass="Sa",1,ProjClass="En",2,ProjClass="Se",3,ProjClass="6S",4,ProjClass="Qu",5,ProjClass="Pr",6,ProjClass="Ma",7,ProjClass="Bu",8)
  AS [FirstSort]

FROM tblProjects

ORDER BY [FirstSort] ASC, [Priority] ASC;

When I run this through the VBA I get

Run-time error "No value given for one or more required parameters."

When I run it in Access a "Enter Parameter Value" dialog opens asking for FirstSort. I click through and see the result is correctly sorted.

The root question: Why is Access seeing FirstSort as a parameter and not a field name?

I think I need to understand that before I can fix the VBA issue.

答:
ProjClass is a field created during execution of the query. Before that when the SQL engine is determining an execution plan for the query it will not recognize that field name so assumes it is parameter. SORT is done at the end of the query and by that time the engine knows which is the third field.

An alternative is to create another table called something like tblPriority with 2 columns ProjectClass and SortOrder

```<code>ProjClass   SortOrder
Sa          1
En          2
Se          3
6S          4
Qu          5
Pr          6
Ma          7
Bu          8
</code>```

and use a JOIN

```<code>SELECT A.* FROM tblProjects AS A
LEFT JOIN tblPriority as B
     ON B.ProjClass = Mid(A.Priority,6,2)
ORDER BY SortOrder
</code>```

Body:
ProjClass is a field created during execution of the query. Before that when the SQL engine is determining an execution plan for the query it will not recognize that field name so assumes it is parameter. SORT is done at the end of the query and by that time the engine knows which is the third field.

An alternative is to create another table called something like tblPriority with 2 columns ProjectClass and SortOrder

ProjClass   SortOrder
Sa          1
En          2
Se          3
6S          4
Qu          5
Pr          6
Ma          7
Bu          8

and use a JOIN

SELECT A.* FROM tblProjects AS A
LEFT JOIN tblPriority as B
     ON B.ProjClass = Mid(A.Priority,6,2)
ORDER BY SortOrder


问:
Qt Writing mouse position to file
I'm writing a simple application using QT that should write the mouse position inside certain widget to a file (the writing is on user double click).

The situation is as follows:

The user performs double click inside the widget.

In the Debug window i can see the current mouse position.

The mouse position is written to the file as expected.

The issue when the mouse position (X or Y) is less then 100. In case that the position is less then 100 the number that is written to the file is always 3 digits number.

For example: Mouse position in the debug window is: 34, 251 and in the file the position is 344, 251. So i can't predict if the actual X position was 34 or 344 because both of them are valid values.

This is the part that responsible on writing the data to the file.

```<code>QByteArray temp1;
char buf[2];
::sprintf(buf, "%d", X);  // X is the mouse x position
temp1.append(buf);
temp1.append(",");
::sprintf(buf, "%d", Y); // Y is the mouse y position
temp1.append(buf);
...
if (tempFile.open(QIODevice::ReadWrite)) {
    QTextStream stream(&tempFile);
    stream << temp1;
}
tempFile.close();
</code>```

This code works good only for positions larger then 100 for some reason.

Thanks

答:
Problem 1

The buffer is too small.

```<code>char buf[2];
</code>```

There needs to be place for multiple digits and a terminating NUL byte, since your are using sprintf here:

```<code>::sprintf(buf, "%d", X);
</code>```

Writing over the end of the array results in undefined behavior.

So you need to increase the size of the array to fix it.

Problem 2

the file is opened in ReadWrite mode

the X and Y value are written

the file is closed

The next time the values are written the same operations are called. ReadWrite mode does not delete the existing contents of the file. For example if you write once

```<code>128,1024
</code>```

and then the next time you write the position: 60,30 it would look like this:

```<code>60,3024
</code>```

One possible solution for this problem would be to apply Truncate mode.

```<code>if (tempFile.open(QIODevice::ReadWrite | QIODevice::Truncate)) {
</code>```

Title: Qt Writing mouse position to file

Body:
I'm writing a simple application using QT that should write the mouse position inside certain widget to a file (the writing is on user double click).

The situation is as follows:

The user performs double click inside the widget.

In the Debug window i can see the current mouse position.

The mouse position is written to the file as expected.

The issue when the mouse position (X or Y) is less then 100. In case that the position is less then 100 the number that is written to the file is always 3 digits number.

For example: Mouse position in the debug window is: 34, 251 and in the file the position is 344, 251. So i can't predict if the actual X position was 34 or 344 because both of them are valid values.

This is the part that responsible on writing the data to the file.

QByteArray temp1;
char buf[2];
::sprintf(buf, "%d", X);  // X is the mouse x position
temp1.append(buf);
temp1.append(",");
::sprintf(buf, "%d", Y); // Y is the mouse y position
temp1.append(buf);
...
if (tempFile.open(QIODevice::ReadWrite)) {
    QTextStream stream(&tempFile);
    stream << temp1;
}
tempFile.close();

This code works good only for positions larger then 100 for some reason.

Thanks

Body:
Problem 1

The buffer is too small.

char buf[2];

There needs to be place for multiple digits and a terminating NUL byte, since your are using sprintf here:

::sprintf(buf, "%d", X);

Writing over the end of the array results in undefined behavior.

So you need to increase the size of the array to fix it.

Problem 2

the file is opened in ReadWrite mode

the X and Y value are written

the file is closed

The next time the values are written the same operations are called. ReadWrite mode does not delete the existing contents of the file. For example if you write once

128,1024

and then the next time you write the position: 60,30 it would look like this:

60,3024

One possible solution for this problem would be to apply Truncate mode.

if (tempFile.open(QIODevice::ReadWrite | QIODevice::Truncate)) {


问:
How to mock services with Arquillian?
Is it possible to use some kind of mocking framework with Arquillian, or precisely how to mock injected EJBs? I know that, with using the CDI (Contexts and Dependency Injection), it is possible to inject alternatives in test. But without CDI as injection mechanism, when I'm only using EJB injection, how this is possible?

Recently I have tested my EJBs with service interface mock implementation as following:

```<code>// Service inteface
public interface Audit {
   void audit(String info);
}

// Mock implementation
@Stateless
public class MockAuditBean implements Audit {

    public static String lastInfo = null;

    @Override
    public void audit(String info) {
        this.lastInfo = info;
    }
}

// assert in test
assertTrue(MockAuditBean.lastInfo.contains("dummy"));
</code>```

This approach is possible but requires a lot of custom mock implementations. What is worse, injected instances of mocks are proxies and uses service interface. These can not be cast to mock implementation class to compare results. Only static members and methods of mock implementation can be used.

I have tested also another possibilities to set related EJBs manually. This approach has several draw-backs. It requires that target EJB of test has non-private members or setters for them. When target EJB relies on @PostConstruct lifecycle annotation, you have to call it after your manual "injection" setting.
Advantage of this solution is the ability to use mock frameworks, like mockito or jMock.

Have someone an experience to share, how to test and set-up such integration test, or even use mocking frameworks in it ?

答:
IMO, EJBs where not designed with testing in mind. Your alternative sounds like a good enough compromise and I'd go for it. Using mockito is a major plus and I use it even when working with CDI.

I'd use the "default" member scope and javadoc to other developers access them for testing purposes only.

Title: How to mock services with Arquillian?

Body:
Is it possible to use some kind of mocking framework with Arquillian, or precisely how to mock injected EJBs? I know that, with using the CDI (Contexts and Dependency Injection), it is possible to inject alternatives in test. But without CDI as injection mechanism, when I'm only using EJB injection, how this is possible?

Recently I have tested my EJBs with service interface mock implementation as following:

// Service inteface
public interface Audit {
   void audit(String info);
}

// Mock implementation
@Stateless
public class MockAuditBean implements Audit {

    public static String lastInfo = null;

    @Override
    public void audit(String info) {
        this.lastInfo = info;
    }
}

// assert in test
assertTrue(MockAuditBean.lastInfo.contains("dummy"));

This approach is possible but requires a lot of custom mock implementations. What is worse, injected instances of mocks are proxies and uses service interface. These can not be cast to mock implementation class to compare results. Only static members and methods of mock implementation can be used.

I have tested also another possibilities to set related EJBs manually. This approach has several draw-backs. It requires that target EJB of test has non-private members or setters for them. When target EJB relies on @PostConstruct lifecycle annotation, you have to call it after your manual "injection" setting.
Advantage of this solution is the ability to use mock frameworks, like mockito or jMock.

Have someone an experience to share, how to test and set-up such integration test, or even use mocking frameworks in it ?