问:
Iterate array elements in specific order
I am trying to iterate a 1D-array/vector of integers in a specific order, but I can't wrap my head around it, to get the loop conditions right.

The input data is a one-dimensional vector of integers:

```<code>{1, 5, 9, 13, 17, 21, 2, 6, 10, 14, 18, 22, 3, 7, 11, 15, 19, 23, 4, 8, 12, 16, 20, 24, 25, 29, 33, 37, 41, 45, 26, 30, 34, 38, 42, 46, 27, 31, 35, 39, 43, 47, 28, 32, 36, 40, 44, 48}
</code>```

This input data is essentially a one dimensional representation of a 2D array/grid with subgroups:

```<code>+----+----+----+----+----+----+
| 1  | 5  | 9  | 13 | 17 | 21 |
+----+----+----+----+----+----+
| 2  | 6  | 10 | 14 | 18 | 22 |
+----+----+----+----+----+----+
| 3  | 7  | 11 | 15 | 19 | 23 |
+----+----+----+----+----+----+
| 4  | 8  | 12 | 16 | 20 | 24 |
+----+----+----+----+----+----+
| 25 | 29 | 33 | 37 | 41 | 45 |
+----+----+----+----+----+----+
| 26 | 30 | 34 | 38 | 42 | 46 |
+----+----+----+----+----+----+
| 27 | 31 | 35 | 39 | 43 | 47 |
+----+----+----+----+----+----+
| 28 | 32 | 36 | 40 | 44 | 48 |
+----+----+----+----+----+----+
</code>```

This table is is grouped into multiple 2x4 subgroups:

I want to iterate this 1D input vector/array in the order that is indicated by the numbers. (Essentially going through every 2x4 subgroup, one after another).
Inside of the loop, I want to load the 8 elements of the currently processed subgroup in a vector/int for further processing.
So in the end I should process 6 subgroups, the first one holding the numbers 1 to 8, the second one 9 to 16 and so fourth ..
The groups should be processed from left to right.

Note: The numbers in the input data just serve as an example, to make clear in which order the data should be processed. The input data could contain totally random values. The order of the values in each group should be kept. There should be no sorting/reordering inside a group. What is important are the constraints for the subgroup/array dimensions etc.

Together with the 1D array/vector I do know the dimensions of the grid and the size of the subgroups:

```<code>int grid_width = 6; // Variable, but will always be a multiple of 2, to match subgroup width
int grid_height = 8;  // Variable, but will always be a multiple of 4, to match subgroup height
const int group_width = 2; // Constant, subgroup width is always 2.
const int group_height = 4; // Constant, subgroup height is always 4.
</code>```

My idea was to have one loop that iterates over the entire data, and then two loops that process the subgroups accordingly. But I really struggle getting the loop conditions and indices for the elements correct. My thought-process was something like this:

```<code>// Iterate over entire data
for (int i = 0; i < grid_width * grid_height; i += (group_width * group_height))
{
    int block[8];
    // Iterate groups in correct order
    for (int j = 0; j < group_height; j++)
    {
        for (int k = 0; k < group_width; k++)
        {
            // Grab current element in group
            int value = input_array[i * grid_width + j]; // ?? This ain't right

            // Add element to group array/vector
            block[??] = ??;
        }
    }

    // Do further processing with the group array
}
</code>```

Can someone help me to loop over this correctly?
I hope the question is clear enough. If not, let me know.

答:
is this solution simple enough? you can find a working demo here:
https://wandbox.org/permlink/5Qv9HKzpaU9ec6gF</p>

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

constexpr int rowSize        = 8;
constexpr int columnSize     = 6;
constexpr int subGroupWidth  = 2;
constexpr int subGroupHeigth = 4;

void calculate(const vector<vector<int>>& arr, vector<vector<int>>& res)
{
    int index = 0;
    for (int i = 0; i < rowSize; i+=subGroupHeigth)
    {
        for (int j = 0; j < columnSize; j+=subGroupWidth)
        {
            // This represents a sub-group!
            res[index].push_back(arr[i][j]);
            res[index].push_back(arr[i+1][j]);
            res[index].push_back(arr[i+2][j]);
            res[index].push_back(arr[i+3][j]);
            res[index].push_back(arr[i][j+1]);
            res[index].push_back(arr[i+1][j+1]);
            res[index].push_back(arr[i+2][j+1]);
            res[index].push_back(arr[i+3][j+1]);
            ++index;
        }
    }
}

int main()
{
    vector<int> vec {1, 5, 9, 13, 17, 21, 2, 6, 10, 14, 18, 22, 3, 7, 11, 15, 19, 23, 4, 8, 12, 16, 20, 24, 25, 29, 33, 37, 41, 45, 26, 30, 34, 38, 42, 46, 27, 31, 35, 39, 43, 47, 28, 32, 36, 40, 44, 48};

    // Convert the vector to 2D array
    vector<vector<int>> arr (rowSize, std::vector<int>(columnSize));
    int row = -1;
    for (size_t i = 0; i < vec.size(); ++i)
    {
        if (i%columnSize == 0) ++row;
        arr[row][i%columnSize] = vec[i];
    }

    vector<vector<int>> result (columnSize);   // reserve the space for 6 arrays
    calculate(arr, result);                    // extract the 6 sub-groups in terms of arrays

    // Print the results
    for_each (begin(result), end(result), [](vector<int> &row){
        for (auto e : row) cout << e << " ";
        cout << endl;
    });
    return 0;
}
</code>```

Body:
I am trying to iterate a 1D-array/vector of integers in a specific order, but I can't wrap my head around it, to get the loop conditions right.

The input data is a one-dimensional vector of integers:

{1, 5, 9, 13, 17, 21, 2, 6, 10, 14, 18, 22, 3, 7, 11, 15, 19, 23, 4, 8, 12, 16, 20, 24, 25, 29, 33, 37, 41, 45, 26, 30, 34, 38, 42, 46, 27, 31, 35, 39, 43, 47, 28, 32, 36, 40, 44, 48}

This input data is essentially a one dimensional representation of a 2D array/grid with subgroups:

+----+----+----+----+----+----+
| 1  | 5  | 9  | 13 | 17 | 21 |
+----+----+----+----+----+----+
| 2  | 6  | 10 | 14 | 18 | 22 |
+----+----+----+----+----+----+
| 3  | 7  | 11 | 15 | 19 | 23 |
+----+----+----+----+----+----+
| 4  | 8  | 12 | 16 | 20 | 24 |
+----+----+----+----+----+----+
| 25 | 29 | 33 | 37 | 41 | 45 |
+----+----+----+----+----+----+
| 26 | 30 | 34 | 38 | 42 | 46 |
+----+----+----+----+----+----+
| 27 | 31 | 35 | 39 | 43 | 47 |
+----+----+----+----+----+----+
| 28 | 32 | 36 | 40 | 44 | 48 |
+----+----+----+----+----+----+

This table is is grouped into multiple 2x4 subgroups:

I want to iterate this 1D input vector/array in the order that is indicated by the numbers. (Essentially going through every 2x4 subgroup, one after another).
Inside of the loop, I want to load the 8 elements of the currently processed subgroup in a vector/int for further processing.
So in the end I should process 6 subgroups, the first one holding the numbers 1 to 8, the second one 9 to 16 and so fourth ..
The groups should be processed from left to right.

Note: The numbers in the input data just serve as an example, to make clear in which order the data should be processed. The input data could contain totally random values. The order of the values in each group should be kept. There should be no sorting/reordering inside a group. What is important are the constraints for the subgroup/array dimensions etc.

Together with the 1D array/vector I do know the dimensions of the grid and the size of the subgroups:

int grid_width = 6; // Variable, but will always be a multiple of 2, to match subgroup width
int grid_height = 8;  // Variable, but will always be a multiple of 4, to match subgroup height
const int group_width = 2; // Constant, subgroup width is always 2.
const int group_height = 4; // Constant, subgroup height is always 4.

My idea was to have one loop that iterates over the entire data, and then two loops that process the subgroups accordingly. But I really struggle getting the loop conditions and indices for the elements correct. My thought-process was something like this:

// Iterate over entire data
for (int i = 0; i < grid_width * grid_height; i += (group_width * group_height))
{
    int block[8];
    // Iterate groups in correct order
    for (int j = 0; j < group_height; j++)
    {
        for (int k = 0; k < group_width; k++)
        {
            // Grab current element in group
            int value = input_array[i * grid_width + j]; // ?? This ain't right

            // Add element to group array/vector
            block[??] = ??;
        }
    }

    // Do further processing with the group array
}

Can someone help me to loop over this correctly?
I hope the question is clear enough. If not, let me know.

Body:
is this solution simple enough? you can find a working demo here:
https://wandbox.org/permlink/5Qv9HKzpaU9ec6gF

#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

constexpr int rowSize        = 8;
constexpr int columnSize     = 6;
constexpr int subGroupWidth  = 2;
constexpr int subGroupHeigth = 4;

void calculate(const vector<vector<int>>& arr, vector<vector<int>>& res)
{
    int index = 0;
    for (int i = 0; i < rowSize; i+=subGroupHeigth)
    {
        for (int j = 0; j < columnSize; j+=subGroupWidth)
        {
            // This represents a sub-group!
            res[index].push_back(arr[i][j]);
            res[index].push_back(arr[i+1][j]);
            res[index].push_back(arr[i+2][j]);
            res[index].push_back(arr[i+3][j]);
            res[index].push_back(arr[i][j+1]);
            res[index].push_back(arr[i+1][j+1]);
            res[index].push_back(arr[i+2][j+1]);
            res[index].push_back(arr[i+3][j+1]);
            ++index;
        }
    }
}

int main()
{
    vector<int> vec {1, 5, 9, 13, 17, 21, 2, 6, 10, 14, 18, 22, 3, 7, 11, 15, 19, 23, 4, 8, 12, 16, 20, 24, 25, 29, 33, 37, 41, 45, 26, 30, 34, 38, 42, 46, 27, 31, 35, 39, 43, 47, 28, 32, 36, 40, 44, 48};

    // Convert the vector to 2D array
    vector<vector<int>> arr (rowSize, std::vector<int>(columnSize));
    int row = -1;
    for (size_t i = 0; i < vec.size(); ++i)
    {
        if (i%columnSize == 0) ++row;
        arr[row][i%columnSize] = vec[i];
    }

    vector<vector<int>> result (columnSize);   // reserve the space for 6 arrays
    calculate(arr, result);                    // extract the 6 sub-groups in terms of arrays

    // Print the results
    for_each (begin(result), end(result), [](vector<int> &row){
        for (auto e : row) cout << e << " ";
        cout << endl;
    });
    return 0;
}


来源: stackexchange

问:
SQL self join table to find next row that matches a condition
I have a table that contains events generated by a vehicle tracker. The table is called tMain (as it is my main table), the important columns here are cVehicleId, cFixedId (the event ID) and cDateTime. The ID's are integers, cDateTime is datetime2(7).
cFixedId can be one of NEWTRIP (67), DEPART (63), STOP (64), PROCEED (65), and DELIVER (66). This is normally also the sequence in which the events will be generated.
The table contains events generated by a fleet of vehicles. The trackers in the vehicles supply the DateTime too, so the table is generally but not 100% necessarily (as the trackers might not be 100% synchronized) ordered by DateTime. The events of every single vehicle will not be contiguous (as there are many vehicles reporting in parallel), but they will be ordered by time.

Example (for 1 vehicle):

```<code>cId         cDateTime               cVehicleId  cFixedId
62462946    2020-06-01 15:47:35.000  27         66
62462476    2020-06-01 15:37:58.000  27         65
62461602    2020-06-01 15:14:43.000  27         64
62461422    2020-06-01 15:11:08.000  27         63
62461407    2020-06-01 15:10:47.000  27         67
</code>```

What I want is a query that returns all DELIVER events together with the preceding DEPART (or maybe NEWTRIP) events, to see how long the trip took. This should look something like this:

```<code>cVehicleId  cFixedId  cDateTime                cFixedId  cDateTime
27          67        2020-06-01 15:10:47.000  66        2020-06-01 15:47:35.000
</code>```

What I tried is finding all DEPART events and then searching forward for the next event with the same VehicleId that has EventId DELIVER. Or find all DELIVER events and searching backward for the closest DEPART event with the same VehicleId.

I have been trying a lot of queries which use self joins, also considered using LEAD or LAG functions but I don't think those will help me here. I just cannot get it to work.

What I currently have is:

```<code>DECLARE @DEPART int = 63;
DECLARE @DELIVER int = 66;

DECLARE @StartDate  DATE = '2020-05-01';
DECLARE @StopDate   DATE = '2020-05-02';

select * from
(select cVehicleid, cDatetime, cFixedId from tMain where cFixedId = @DEPART and cDateTime > @StartDate and cDateTime < @StopDate) as t1
inner join
(select top(1) cVehicleId, cDatetime, cFixedId from tMain where cFixedId = @DELIVER and cDateTime > @StartDate and cDateTime < @StopDate order by cDateTime) as t2 on t2.cVehicleId = t1.cVehicleId and t2.cDateTime > t1.cDateTime
</code>```

However, this returns nothing.

I don't see what I'm doing wrong, and I have no clue how to continue. Maybe there are even better approaches that I'm not aware of. I did a lot of searching on the web, but didn't find anything that led me to the solution. Can anyone give me a hint?

Less important extra: it would be nice if the results were grouped by VehicledId, but that is not an absolute must.

答:
What I want is a query that returns all DELIVER events together with the preceding DEPART (or maybe NEWTRIP) events, to see how long the trip took.

If I understand correctly, you can use apply:

```<code>select d.*, previous.*
from tmain d outer apply
     (select top (1) e.*
      from tmain e
      where e.cVehicleId = d.cVehicleId and
            e.cFixedId in ('DEPART', 'NEWTRIP') and
            e.cDateTime < d.cDateTime
      order by e.cDateTime desc
     ) previous
where d.ceventid = 'DELIVER';
</code>```

This uses the string versions for clarity.

ContentLicense: CC BY-SA 4.0

Body:
I have a table that contains events generated by a vehicle tracker. The table is called tMain (as it is my main table), the important columns here are cVehicleId, cFixedId (the event ID) and cDateTime. The ID's are integers, cDateTime is datetime2(7).
cFixedId can be one of NEWTRIP (67), DEPART (63), STOP (64), PROCEED (65), and DELIVER (66). This is normally also the sequence in which the events will be generated.
The table contains events generated by a fleet of vehicles. The trackers in the vehicles supply the DateTime too, so the table is generally but not 100% necessarily (as the trackers might not be 100% synchronized) ordered by DateTime. The events of every single vehicle will not be contiguous (as there are many vehicles reporting in parallel), but they will be ordered by time.

Example (for 1 vehicle):

cId         cDateTime               cVehicleId  cFixedId
62462946    2020-06-01 15:47:35.000  27         66
62462476    2020-06-01 15:37:58.000  27         65
62461602    2020-06-01 15:14:43.000  27         64
62461422    2020-06-01 15:11:08.000  27         63
62461407    2020-06-01 15:10:47.000  27         67

What I want is a query that returns all DELIVER events together with the preceding DEPART (or maybe NEWTRIP) events, to see how long the trip took. This should look something like this:

cVehicleId  cFixedId  cDateTime                cFixedId  cDateTime
27          67        2020-06-01 15:10:47.000  66        2020-06-01 15:47:35.000

What I tried is finding all DEPART events and then searching forward for the next event with the same VehicleId that has EventId DELIVER. Or find all DELIVER events and searching backward for the closest DEPART event with the same VehicleId.

I have been trying a lot of queries which use self joins, also considered using LEAD or LAG functions but I don't think those will help me here. I just cannot get it to work.

What I currently have is:

DECLARE @DEPART int = 63;
DECLARE @DELIVER int = 66;

DECLARE @StartDate  DATE = '2020-05-01';
DECLARE @StopDate   DATE = '2020-05-02';

select * from
(select cVehicleid, cDatetime, cFixedId from tMain where cFixedId = @DEPART and cDateTime > @StartDate and cDateTime < @StopDate) as t1
inner join
(select top(1) cVehicleId, cDatetime, cFixedId from tMain where cFixedId = @DELIVER and cDateTime > @StartDate and cDateTime < @StopDate order by cDateTime) as t2 on t2.cVehicleId = t1.cVehicleId and t2.cDateTime > t1.cDateTime

However, this returns nothing.

I don't see what I'm doing wrong, and I have no clue how to continue. Maybe there are even better approaches that I'm not aware of. I did a lot of searching on the web, but didn't find anything that led me to the solution. Can anyone give me a hint?

Less important extra: it would be nice if the results were grouped by VehicledId, but that is not an absolute must.

Body:
What I want is a query that returns all DELIVER events together with the preceding DEPART (or maybe NEWTRIP) events, to see how long the trip took.

If I understand correctly, you can use apply:

select d.*, previous.*
from tmain d outer apply
     (select top (1) e.*
      from tmain e
      where e.cVehicleId = d.cVehicleId and
            e.cFixedId in ('DEPART', 'NEWTRIP') and
            e.cDateTime < d.cDateTime
      order by e.cDateTime desc
     ) previous
where d.ceventid = 'DELIVER';

This uses the string versions for clarity.


问:
What data strucutre does *mutableSetOf()* return in Kotlin?
Is it implemented as a HashSet, linked HashSet or binary search tree?

I know it is hidden for encapsulation, but I need to estimate the asymptotic runtime.

答:
It can be interesting and instructive to look at the standard library's source code — but what mutableSetOf() happens to return today doesn't really matter, because that can change in future Kotlin versions.

The important thing is that the documentation doesn't mention a class, just the MutableSet interface.  That's all that JetBrains have committed to, and so that's all you can safely assume.  You should never rely on a particular implementation choice, when that's not part of the contract.

(The only other thing they specify is that ‘The returned set preserves the element iteration order.’  So you know it can't return a HashSet, which doesn't.  But that still leaves several current possibilities, and potentially many more in future.  Oracle or JetBrains may come up with a new implementation that has better general or worst-case performance, or some other desirable feature.)

Downcasting the result to a LinkedHashSet might work today, but in a future Kotlin version that might fail with a ClassCastException.  (Or even worse, it might work most of the time, and then throw a ClassCastException when you're not expecting it.)

So, if you have particular performance requirements, then you're better off creating the type you want explicitly.

mutableSetOf() is for when you don't have specific requirements, and just want something easy that's likely to behave well in general.


问:
native@0xc41bcc output for HWND to actual window ID
Hey all I am having an issue with trying to get this JNA findwindow working that gives me the windows ID (HWND) instead of some crazy output (native@0xc41bcc).

I know from working with C# that when using the findwindow it gives an ID of that found window that I can then use for moving/resizing/etc that window.

My code:

```<code>public String exec(ITestExecutionServices tes, String[] args) {
    try {
        writer = new PrintWriter("c:/temp/the-file-name.txt", "UTF-8");
    } catch (FileNotFoundException | UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }

    try {

        final User32 user32 = User32.INSTANCE;

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        user32.EnumWindows(new WNDENUMPROC() {
            @Override
            public boolean callback(HWND hWnd, Pointer arg1) {
                byte[] windowText = new byte[512];
                user32.GetWindowTextA(hWnd, windowText, 512);
                String wText = Native.toString(windowText);
                wText = (wText.isEmpty()) ? "" : wText;

                if (wText.toLowerCase().contains("- funct test -")) {
                    writer.println("text: " + wText);
                    writer.println("HWND: " + hWnd);
                    //User32.INSTANCE.SetWindowPos(hwnd, new HWND(Pointer.createConstant(HWND_BOTTOM)), 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
                    WinDef.HWND hwndFound = User32.INSTANCE.FindWindow(null, wText);
                    writer.println("hwndFound: " + hwndFound);
                    writer.println("t/f: " + User32.INSTANCE.MoveWindow(hwndFound, 500, 500, 10, 100, true));
                    //User32.INSTANCE.SetWindowPos(hWnd, new HWND(Pointer.createConstant(HWND_BOTTOM)), 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
                }
                return true;
            }
        }, null);
    } catch (Exception f) {
        String tmp = f.toString();

        for (StackTraceElement el : f.getStackTrace()) {
            tmp = tmp + System.getProperty("line.separator") + el.toString();
        }

        JOptionPane.showMessageDialog(null, "ERROR!");

        return "false";
    }
    writer.close();
    return "true";
}

public interface User32 extends StdCallLibrary {
    User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class);

    HWND FindWindow(String lpClassName, String lpWindowName);
    HWND FindWindowExA(HWND parent, HWND child, String className, String window);
    HWND GetDesktopWindow();
    HWND SetFocus(HWND hWnd);
    HWND WindowFromPoint(long point);
    HWND ChildWindowFromPointEx(HWND hwndParent, long point, int uFlags);

    HMENU GetMenu(HWND hWnd);
    HMENU GetSystemMenu(HWND hWnd, boolean bRevert);
    HMENU GetSubMenu(HMENU hMenu, int nPos);

    HDC GetWindowDC(HWND hWnd);

    LRESULT CallWindowProc(LONG_PTR proc, HWND hWnd, int uMsg, WPARAM uParam, LPARAM lParam);

    int GetWindowTextA(HWND hWnd, byte[] lpString, int nMaxCount);
    int GetWindowRect(HWND handle, int[] rect);
    int GetClassNameA(HWND in, byte[] lpString, int size);
    int SendMessageA(HWND hWnd, int msg, WPARAM wParam, LPARAM lParam);
    int PostMessageA(HWND hWnd, int msg, WPARAM wParam, LPARAM lParam);
    int ReleaseDC(HWND hWnd, HDC hDC);
    int GetTopWindow(HWND hWnd);
    int GetWindow(HWND hWnd, int flag);
    int GetWindowModuleFileName(HWND hWnd, char[] buffer2, int i);
    int GetWindowThreadProcessId(HWND hWnd, PointerByReference pref);
    int SetWindowLongPtr(HWND hWnd, int nIndex, Callback callback);
    int GetMenuString(HMENU hMenu, int uIDItem, char[] buffer, int nMaxCount, int uFlag);
    int GetMenuItemCount(HMENU hMenu);
    int GetMenuItemID(HMENU hMenu, int nPos);
    int GetDlgCtrlID(HWND hwndCtl);
    int GetDlgItemText(HWND hDlg, int nIDDlgItem, byte[] buffer, int nMaxCount);

    boolean MoveWindow(WinDef.HWND hWnd,int X, int Y, int nWidth, int nHeight, boolean bRepaint);
    boolean InvalidateRect(HWND hWnd, long lpRect, boolean bErase);
    boolean UpdateWindow(HWND hWnd);
    boolean RedrawWindow(HWND hWnd, long lprcUpdate, long hrgnUpdate, int flags);
    boolean EnumWindows(WNDENUMPROC lpEnumFunc, Pointer arg);
    boolean EnumChildWindows(HWND parent, WNDENUMPROC callback, LPARAM info);
    boolean SetForegroundWindow(HWND in);
    boolean EnumWindows(WinUser.WNDENUMPROC lpEnumFunc, Pointer arg);
    boolean DestroyWindow(HWND hWnd);
    boolean IsWindowVisible(HWND hWnd);
    boolean IsWindow(HWND hWnd);
    boolean ShowWindow(HWND hWnd, int nCmdShow);
    boolean GetCursorPos(long[] lpPoint); //use macros POINT_X() and POINT_Y() on long lpPoint[0]
    boolean ClientToScreen(HWND hWnd, long[] lpPoint);//use macros POINT_X() and POINT_Y() on long lpPoint[0]
    boolean ScreenToClient(HWND hWnd, long[] lpPoint);//use macros POINT_X() and POINT_Y() on long lpPoint[0]
    boolean IsMenu(HMENU hMenu);
    boolean TrackPopupMenu(HMENU hMenu, int uFlags, int x, int y, int nReserved, HWND hWnd, long prcRect);
    boolean GetMenuItemRect(HWND hWnd, HMENU hMenu, int uItem, RECT rect);

    void SwitchToThisWindow(HWND hWnd, boolean fAltTab);

    long GetWindowLong(HWND hWnd, int index);

    interface WNDENUMPROC extends StdCallCallback {boolean callback(HWND hWnd, Pointer arg);}
}
</code>```

答:
I think this may help:

```<code>import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
</code>```

And this function:

```<code>public long getWindowId(String title) {
  WinDef.HWND hwnd = User32.INSTANCE.FindWindow(null, title);

  return Pointer.nativeValue(hwnd.getPointer());
}
</code>```

Body:
Hey all I am having an issue with trying to get this JNA findwindow working that gives me the windows ID (HWND) instead of some crazy output (native@0xc41bcc).

I know from working with C# that when using the findwindow it gives an ID of that found window that I can then use for moving/resizing/etc that window.

My code:

public String exec(ITestExecutionServices tes, String[] args) {
    try {
        writer = new PrintWriter("c:/temp/the-file-name.txt", "UTF-8");
    } catch (FileNotFoundException | UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }

    try {

        final User32 user32 = User32.INSTANCE;

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        user32.EnumWindows(new WNDENUMPROC() {
            @Override
            public boolean callback(HWND hWnd, Pointer arg1) {
                byte[] windowText = new byte[512];
                user32.GetWindowTextA(hWnd, windowText, 512);
                String wText = Native.toString(windowText);
                wText = (wText.isEmpty()) ? "" : wText;

                if (wText.toLowerCase().contains("- funct test -")) {
                    writer.println("text: " + wText);
                    writer.println("HWND: " + hWnd);
                    //User32.INSTANCE.SetWindowPos(hwnd, new HWND(Pointer.createConstant(HWND_BOTTOM)), 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
                    WinDef.HWND hwndFound = User32.INSTANCE.FindWindow(null, wText);
                    writer.println("hwndFound: " + hwndFound);
                    writer.println("t/f: " + User32.INSTANCE.MoveWindow(hwndFound, 500, 500, 10, 100, true));
                    //User32.INSTANCE.SetWindowPos(hWnd, new HWND(Pointer.createConstant(HWND_BOTTOM)), 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
                }
                return true;
            }
        }, null);
    } catch (Exception f) {
        String tmp = f.toString();

        for (StackTraceElement el : f.getStackTrace()) {
            tmp = tmp + System.getProperty("line.separator") + el.toString();
        }

        JOptionPane.showMessageDialog(null, "ERROR!");

        return "false";
    }
    writer.close();
    return "true";
}

public interface User32 extends StdCallLibrary {
    User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class);

    HWND FindWindow(String lpClassName, String lpWindowName);
    HWND FindWindowExA(HWND parent, HWND child, String className, String window);
    HWND GetDesktopWindow();
    HWND SetFocus(HWND hWnd);
    HWND WindowFromPoint(long point);
    HWND ChildWindowFromPointEx(HWND hwndParent, long point, int uFlags);

    HMENU GetMenu(HWND hWnd);
    HMENU GetSystemMenu(HWND hWnd, boolean bRevert);
    HMENU GetSubMenu(HMENU hMenu, int nPos);

    HDC GetWindowDC(HWND hWnd);

    LRESULT CallWindowProc(LONG_PTR proc, HWND hWnd, int uMsg, WPARAM uParam, LPARAM lParam);

    int GetWindowTextA(HWND hWnd, byte[] lpString, int nMaxCount);
    int GetWindowRect(HWND handle, int[] rect);
    int GetClassNameA(HWND in, byte[] lpString, int size);
    int SendMessageA(HWND hWnd, int msg, WPARAM wParam, LPARAM lParam);
    int PostMessageA(HWND hWnd, int msg, WPARAM wParam, LPARAM lParam);
    int ReleaseDC(HWND hWnd, HDC hDC);
    int GetTopWindow(HWND hWnd);
    int GetWindow(HWND hWnd, int flag);
    int GetWindowModuleFileName(HWND hWnd, char[] buffer2, int i);
    int GetWindowThreadProcessId(HWND hWnd, PointerByReference pref);
    int SetWindowLongPtr(HWND hWnd, int nIndex, Callback callback);
    int GetMenuString(HMENU hMenu, int uIDItem, char[] buffer, int nMaxCount, int uFlag);
    int GetMenuItemCount(HMENU hMenu);
    int GetMenuItemID(HMENU hMenu, int nPos);
    int GetDlgCtrlID(HWND hwndCtl);
    int GetDlgItemText(HWND hDlg, int nIDDlgItem, byte[] buffer, int nMaxCount);

    boolean MoveWindow(WinDef.HWND hWnd,int X, int Y, int nWidth, int nHeight, boolean bRepaint);
    boolean InvalidateRect(HWND hWnd, long lpRect, boolean bErase);
    boolean UpdateWindow(HWND hWnd);
    boolean RedrawWindow(HWND hWnd, long lprcUpdate, long hrgnUpdate, int flags);
    boolean EnumWindows(WNDENUMPROC lpEnumFunc, Pointer arg);
    boolean EnumChildWindows(HWND parent, WNDENUMPROC callback, LPARAM info);
    boolean SetForegroundWindow(HWND in);
    boolean EnumWindows(WinUser.WNDENUMPROC lpEnumFunc, Pointer arg);
    boolean DestroyWindow(HWND hWnd);
    boolean IsWindowVisible(HWND hWnd);
    boolean IsWindow(HWND hWnd);
    boolean ShowWindow(HWND hWnd, int nCmdShow);
    boolean GetCursorPos(long[] lpPoint); //use macros POINT_X() and POINT_Y() on long lpPoint[0]
    boolean ClientToScreen(HWND hWnd, long[] lpPoint);//use macros POINT_X() and POINT_Y() on long lpPoint[0]
    boolean ScreenToClient(HWND hWnd, long[] lpPoint);//use macros POINT_X() and POINT_Y() on long lpPoint[0]
    boolean IsMenu(HMENU hMenu);
    boolean TrackPopupMenu(HMENU hMenu, int uFlags, int x, int y, int nReserved, HWND hWnd, long prcRect);
    boolean GetMenuItemRect(HWND hWnd, HMENU hMenu, int uItem, RECT rect);

    void SwitchToThisWindow(HWND hWnd, boolean fAltTab);

    long GetWindowLong(HWND hWnd, int index);

    interface WNDENUMPROC extends StdCallCallback {boolean callback(HWND hWnd, Pointer arg);}
}

Body:
I think this may help:

import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;

And this function:

public long getWindowId(String title) {
  WinDef.HWND hwnd = User32.INSTANCE.FindWindow(null, title);

  return Pointer.nativeValue(hwnd.getPointer());
}


问:
How to appropriately use selenium and parallel processing
I am trying to scrape a bunch of urls using Selenium and BeautifulSoup. Because they are thousands and the processing that I need to do is complex and uses a lot of CPU, I need to do multiprocessing (as opposed to multithreading).

The problem right now is that I am opening and closing a Chromedriver instance once for each URL, which adds a lot of overhead and makes the process slow.

What I want to do is instead have a chromedriver instance for each subprocess, only open it once and keep it open until the subprocess finishes. However, my attempts to do it have been unsuccessful.

I tried creating the instances in the main process, dividing the set of URLS into the number of processes and sending each subprocess its subset of urls and a single driver as arguments, so that each subprocess would cycle through the urls that it got. But that didn't run at all, it did not give either results or error.

A solution similar to this with multiprocessing instead of threading got me a recursion-limit error (changing the recursion limit using sys would not help at all).

What else could I do to make this faster?

Below are the relevant parts of the code that actually works.

```<code>from bs4 import BeautifulSoup
import re
import csv
from datetime import datetime
import numpy as np
import concurrent.futures
import multiprocessing
from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--window-size=1920x1080')
options.add_argument('--no-sandbox')

def runit(row):
    driver = webdriver.Chrome(chrome_options=options)
    driver.set_page_load_timeout(500)
    driver.implicitly_wait(500)
    url = row[1]
    driver.get(url)
    html_doc = driver.page_source
    driver.quit()
    soup = BeautifulSoup(html_doc, 'html.parser')

    # Some long processing code that uses the soup object and generates the result object that is returned below with what I want

    return result, row

if __name__ == '__main__':
    multiprocessing.freeze_support()
    print(datetime.now())
    # The file below has the list of all the pages that I need to process, along with some other pieces of relevant data
    # The URL is the second field in the csv file
    with open('D:\\Users\\shina\\OneDrive\\testTiles.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        # I have 4 cores but Windows shows 8 logical processors, I have tried other numbers below 8, but 8 seems to bring the fastest results
        with concurrent.futures.ProcessPoolExecutor(max_workers=8) as executor:
            results = executor.map(runit, csv_reader)

        #At a later time I will code here what I will do with the results after all the processes finish.

    print(datetime.now())
</code>```

答:
I found a possible solution to my question myself.

The error I was making in my alternative solutions (not shown above) was that I was trying to create all the drivers in the main process and pass it as argument to each subprocess. This did not work well. So what I did instead is to create each chromedriver instance inside each subprocess, as you will see in my code below. Please note, however, that this code is not entirely efficient. This is because the rows are divided evenly by count between all the subprocesses, and not all pages are equal. This means that some subprocesses finish earlier than others, leading to subutilization of the CPU at the end. This, however, takes 42% less time than having the chromedirver instance open and quit for each URL. If anyone has a solution that would allow to do both things (efficient use of the CPU and each subprocess having its own chromedriver instance), I would be thankful.

```<code>def runit(part):
    driver = webdriver.Chrome(options=options)
    driver.implicitly_wait(500)
    driver.set_page_load_timeout(500)
    debug = False
    results = []
    keys = []
    #the subprocess now receives a bunch of rows instead of just one
    #so I have to cycle through them now
    for row in part:
        result = None
        try:
            #processFile is a function that does the processing of each URL
            result = processFile(row[1], debug, driver)
        except Exception as e:
            exc = str(e)
            print(f"EXCEPTION: {row[0]} caused {exc}")
        results.append(results)
        keys.append(row[0])
    driver.quit()
    return results, keys

if __name__ == '__main__':
    multiprocessing.freeze_support()
    maxprocessors = 8

    print(datetime.now())
    rows = []
    with open('D:\\Users\\shina\\OneDrive\\testTiles.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        for row in csv_reader:
            rows.append(row)
    parts = []
    # I separate the rows into equal parts by count
    # However these parts are not equal in terms of required CPU time
    # Which creates CPU subutilization at the end
    for i in range(0, maxprocessors):
        parts.append(rows[i::maxprocessors])
    with concurrent.futures.ProcessPoolExecutor(max_workers=maxprocessors) as executor:
        results = executor.map(runit, parts)

    print(datetime.now())
</code>```

Body:
I am trying to scrape a bunch of urls using Selenium and BeautifulSoup. Because they are thousands and the processing that I need to do is complex and uses a lot of CPU, I need to do multiprocessing (as opposed to multithreading).

The problem right now is that I am opening and closing a Chromedriver instance once for each URL, which adds a lot of overhead and makes the process slow.

What I want to do is instead have a chromedriver instance for each subprocess, only open it once and keep it open until the subprocess finishes. However, my attempts to do it have been unsuccessful.

I tried creating the instances in the main process, dividing the set of URLS into the number of processes and sending each subprocess its subset of urls and a single driver as arguments, so that each subprocess would cycle through the urls that it got. But that didn't run at all, it did not give either results or error.

A solution similar to this with multiprocessing instead of threading got me a recursion-limit error (changing the recursion limit using sys would not help at all).

What else could I do to make this faster?

Below are the relevant parts of the code that actually works.

from bs4 import BeautifulSoup
import re
import csv
from datetime import datetime
import numpy as np
import concurrent.futures
import multiprocessing
from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--window-size=1920x1080')
options.add_argument('--no-sandbox')

def runit(row):
    driver = webdriver.Chrome(chrome_options=options)
    driver.set_page_load_timeout(500)
    driver.implicitly_wait(500)
    url = row[1]
    driver.get(url)
    html_doc = driver.page_source
    driver.quit()
    soup = BeautifulSoup(html_doc, 'html.parser')

    # Some long processing code that uses the soup object and generates the result object that is returned below with what I want

    return result, row

if __name__ == '__main__':
    multiprocessing.freeze_support()
    print(datetime.now())
    # The file below has the list of all the pages that I need to process, along with some other pieces of relevant data
    # The URL is the second field in the csv file
    with open('D:\\Users\\shina\\OneDrive\\testTiles.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        # I have 4 cores but Windows shows 8 logical processors, I have tried other numbers below 8, but 8 seems to bring the fastest results
        with concurrent.futures.ProcessPoolExecutor(max_workers=8) as executor:
            results = executor.map(runit, csv_reader)

        #At a later time I will code here what I will do with the results after all the processes finish.

    print(datetime.now())

Body:
I found a possible solution to my question myself.

The error I was making in my alternative solutions (not shown above) was that I was trying to create all the drivers in the main process and pass it as argument to each subprocess. This did not work well. So what I did instead is to create each chromedriver instance inside each subprocess, as you will see in my code below. Please note, however, that this code is not entirely efficient. This is because the rows are divided evenly by count between all the subprocesses, and not all pages are equal. This means that some subprocesses finish earlier than others, leading to subutilization of the CPU at the end. This, however, takes 42% less time than having the chromedirver instance open and quit for each URL. If anyone has a solution that would allow to do both things (efficient use of the CPU and each subprocess having its own chromedriver instance), I would be thankful.

def runit(part):
    driver = webdriver.Chrome(options=options)
    driver.implicitly_wait(500)
    driver.set_page_load_timeout(500)
    debug = False
    results = []
    keys = []
    #the subprocess now receives a bunch of rows instead of just one
    #so I have to cycle through them now
    for row in part:
        result = None
        try:
            #processFile is a function that does the processing of each URL
            result = processFile(row[1], debug, driver)
        except Exception as e:
            exc = str(e)
            print(f"EXCEPTION: {row[0]} caused {exc}")
        results.append(results)
        keys.append(row[0])
    driver.quit()
    return results, keys

if __name__ == '__main__':
    multiprocessing.freeze_support()
    maxprocessors = 8

    print(datetime.now())
    rows = []
    with open('D:\\Users\\shina\\OneDrive\\testTiles.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        for row in csv_reader:
            rows.append(row)
    parts = []
    # I separate the rows into equal parts by count
    # However these parts are not equal in terms of required CPU time
    # Which creates CPU subutilization at the end
    for i in range(0, maxprocessors):
        parts.append(rows[i::maxprocessors])
    with concurrent.futures.ProcessPoolExecutor(max_workers=maxprocessors) as executor:
        results = executor.map(runit, parts)

    print(datetime.now())


问:
Selecting items in a listview
I want to select a particular subitem in a row of a listview. For example if the row contains
5 subitems, if I click the 3rd subitem it only gets selected.

I solved the issue successfully

答:
First you have to detect which subitem the user clicked.

To achieve that check this example. Basically it will loop through the subitems collection of the ListViewItem and see whether the mouse pointer is over one of them.

Later... with the clicked subitem detected... you can change it ForeColor and Background to show it as "selected".

To be able to do that, you must set the ListViewItem's UseItemStyleForSubItems property to false. That will allow you to set background and other properties to a single subitem.

OwnerDisplayName: karthik

LastEditorDisplayName: karthik

ContentLicense: CC BY-SA 3.0

Title: Selecting items in a listview

OwnerDisplayName: Romias

ContentLicense: CC BY-SA 2.5


问:
In MS Access, how to select record on form1 after adding from form2?
This is my scenario (MS Access 2007):

On Form1 I have a list of records (Orders). Form1 has a button that launches Form2.

Form2 is used for creating new Orders. The "Save" button on Form2 uses VBA to save the record, close the form and requery Form1:

```<code>DoCmd.RunCommand acCmdSaveRecord
DoCmd.RunCommand acCmdCloseWindow
Forms!Orders.Requery
</code>```

The next step I'd like to be able to do is have the new record selected automatically on Form1. My guess is it's somehow done with DoCmd.FindRecord? I can't figure it out -- any help is very appreciated.

Thanks,
Stewart

答:
The answer would depend on whether the application has a single user or multiple users.  In a multiuser scenario, simply getting the most recently added Order would not necessarily return the one YOU have just entered. But if it's only you, getting the most recently added value would do that.

You can find the row with  the max(orderid) if you're using an autoincrementing key; or find the row with the max(orderDateTime) if your orders are timestamped; or simply have the datasource for the  Orderslist form be sorted by either of those values, descending, and reposition to the first record after a Requery.

Body:
This is my scenario (MS Access 2007):

On Form1 I have a list of records (Orders). Form1 has a button that launches Form2.

Form2 is used for creating new Orders. The "Save" button on Form2 uses VBA to save the record, close the form and requery Form1:

DoCmd.RunCommand acCmdSaveRecord
DoCmd.RunCommand acCmdCloseWindow
Forms!Orders.Requery

The next step I'd like to be able to do is have the new record selected automatically on Form1. My guess is it's somehow done with DoCmd.FindRecord? I can't figure it out -- any help is very appreciated.

Thanks,
Stewart


问:
How to test that catch (Exception e) { e.printStackTrace();} invoked
I need to reach 95% test coverage (my task). I have problems with following class

```<code>    public class Context {

    public static <T> T getObject(Class<T> clazz) {
        Object bean = null;

        try {
            bean = clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return (T) bean;
    }

    private Context() {
    }
}
</code>```

to reach 95% I need to check that e.printStackTrace(); invoked when Exception thrown.
I tried different ways but none of them work. I will appreciate any support.

答:
This is how I solved this issue. I refactored code a little bit:

 private static final Logger LOGGER = Logger.getLogger(Context.class.getName());

    public <T> T getObject(Class<T> clazz) {
        T bean = null;

        try {
            bean = clazz.getConstructor().newInstance();
        } catch (Exception e) {
            LOGGER.log(Level.INFO, e, () -> "Exception occurred during Context usage whilst created " + clazz.getName());
        }
        return bean;
    }
```

<p>and here it is the test:</p>

<pre class="lang-java prettyprint-override"><code>    @Test
    void getObject_ShouldThrowException() throws Exception {
        Exception mockedException = mock(InstantiationException.class);
        Logger mockedLogger = mock(Logger.class);

        class Dummy {

            public Dummy() throws Exception {
                throw mockedException;
            }
        }

        try {
            Dummy dummy = context.getObject(Dummy.class);
        } catch (Exception e) {
            verify(mockedLogger, times(1)).log(Level.INFO, anyString());
        }
    }
</code>```

Body:
I need to reach 95% test coverage (my task). I have problems with following class

    public class Context {

    public static <T> T getObject(Class<T> clazz) {
        Object bean = null;

        try {
            bean = clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return (T) bean;
    }

    private Context() {
    }
}

to reach 95% I need to check that e.printStackTrace(); invoked when Exception thrown.
I tried different ways but none of them work. I will appreciate any support.

Body:
This is how I solved this issue. I refactored code a little bit:

 private static final Logger LOGGER = Logger.getLogger(Context.class.getName());

    public <T> T getObject(Class<T> clazz) {
        T bean = null;

        try {
            bean = clazz.getConstructor().newInstance();
        } catch (Exception e) {
            LOGGER.log(Level.INFO, e, () -> "Exception occurred during Context usage whilst created " + clazz.getName());
        }
        return bean;
    }

and here it is the test:

    @Test
    void getObject_ShouldThrowException() throws Exception {
        Exception mockedException = mock(InstantiationException.class);
        Logger mockedLogger = mock(Logger.class);

        class Dummy {

            public Dummy() throws Exception {
                throw mockedException;
            }
        }

        try {
            Dummy dummy = context.getObject(Dummy.class);
        } catch (Exception e) {
            verify(mockedLogger, times(1)).log(Level.INFO, anyString());
        }
    }


问:
Is there a way to code a large array of objects in a much shorter way?
I am doing a personal project in react.js but at this moment I am trying to write clean code. Could exist a way to write shorter this code in two lines? or something like that. I tried to make objects of arrays like

```<code>const apps= {app_name:['Maps','Meet'], position:['0 2323', '0 2323'}
</code>```

but It does not work

const apps = [
  {
    app_name: 'Maps',
    position: '0 -828px'
  },
  {
    app_name: 'Gmail',
    position: '0 -483px'
  },
  {
    app_name: 'Calendar',
    position: '0 -2553px'
  },
  {
    app_name: 'Drive',
    position: '0 -2277px'
  }
];
```

<p>There is not a way to rewrite it in a more shorter way in order to make the map's function works?</p>

<pre class="lang-js prettyprint-override"><code>{apps.map((el, i) =>
    <li className='items'>

            <div className='img_box'>
                <span className='img'
                  style={ { backgroundPosition: el.position } }></span>
            </div>
            <span className='app_name'>{el.app_name}</span>

    </li>
)}

</code>```

答:
Well typically, your array should not be a part of your code. It should be a separate JSON file.

From your code I see that you want to display a list with the content of the array. So my point still holds. Data should not be part of code.

Even if you are writing a jest file, data ideally should be a separate file.
You can then write a neater logic to get it from the JSON file or say a web API based on a configuration.

Good day to you.

Body:
I am doing a personal project in react.js but at this moment I am trying to write clean code. Could exist a way to write shorter this code in two lines? or something like that. I tried to make objects of arrays like

const apps= {app_name:['Maps','Meet'], position:['0 2323', '0 2323'}

but It does not work

const apps = [
  {
    app_name: 'Maps',
    position: '0 -828px'
  },
  {
    app_name: 'Gmail',
    position: '0 -483px'
  },
  {
    app_name: 'Calendar',
    position: '0 -2553px'
  },
  {
    app_name: 'Drive',
    position: '0 -2277px'
  }
];

There is not a way to rewrite it in a more shorter way in order to make the map's function works?

{apps.map((el, i) =>

            {el.app_name}

)}


问:
Terraform interpreting locals expression when it shouldn't be
I have a Kafka client container running on AWS ECS, which should receive a regular expression for which topics to subscribe to from the containers environment variables. In my terraform I define the environment variable like so:

```<code>..
      {
        "name": "KAFKA_TOPIC_REGEX",
        "value": "${local.kafka_topic_regex[local.environment]}"
      }
..
</code>```

With a corresponding value in the locals.tf file like so:

```<code>..
  kafka_topic_regex = {
    development = "^(ab\..*\..*)$|^(foo\.bar)$"
  }
..
</code>```

However I'm having difficulty getting this to work as expected. When I terraform plan, the following error is shown:

```<code>The symbol "." is not a valid escape sequence selector.
</code>```

Unfortunately I need the backward slash there for the regex to use the literal dot as a character in the topic name. I can't escape the backward slash as I actually require it be there for the regex.

I have equally tried the regex like so:

```<code>^(ab[.].*[.].*)$|^(foo[.]bar)$
</code>```

Again, Terraform does some strange interpretation of this and in the plan the value appears as:

```<code>^ab.(.*)
</code>```

This will mean that the literal dot I require isn't in the regex as it is required to be escaped in the regex.

It appears Terraform is interpreting my string and causing a failed plan / apply, when it shouldn't be interpreting it.

Any help would be appreciated, thank you

答:
It seems the plan / apply breakdown of what is actually applied is wrong. The regex which escapes the dot using square brackets will apply with the correct value but is displayed incorrectly on plan and apply.
Working version:
 ^(ab[.].*[.].*)$|^(foo[.]bar)$

Body:
I have a Kafka client container running on AWS ECS, which should receive a regular expression for which topics to subscribe to from the containers environment variables. In my terraform I define the environment variable like so:

..
      {
        "name": "KAFKA_TOPIC_REGEX",
        "value": "${local.kafka_topic_regex[local.environment]}"
      }
..

With a corresponding value in the locals.tf file like so:

..
  kafka_topic_regex = {
    development = "^(ab\..*\..*)$|^(foo\.bar)$"
  }
..

However I'm having difficulty getting this to work as expected. When I terraform plan, the following error is shown:

The symbol "." is not a valid escape sequence selector.

Unfortunately I need the backward slash there for the regex to use the literal dot as a character in the topic name. I can't escape the backward slash as I actually require it be there for the regex.

I have equally tried the regex like so:

^(ab[.].*[.].*)$|^(foo[.]bar)$

Again, Terraform does some strange interpretation of this and in the plan the value appears as:

^ab.(.*)

This will mean that the literal dot I require isn't in the regex as it is required to be escaped in the regex.

It appears Terraform is interpreting my string and causing a failed plan / apply, when it shouldn't be interpreting it.

Any help would be appreciated, thank you


问:
How to invoke code in C# optional package from a UWP app written in C#
It is now possible to create optional package in C#. However, it is not clear how to invoke the code in the optional package from a C# UWP main app, especially if we need to invoke it in a generic fashion.

Say, I have a plugins within the optional package and they all implement IPlugin interface with an Execute  method and Name property. I would like to display the Names of all the plugins in a menu and invoke the Execute method of plugin when user clicks on it.

We can iterate over all the optional packages of the main app, something like

    // Obtain the app's package first to then find all related packages
    var currentAppPackage = Windows.ApplicationModel.Package.Current;

    // The dependencies list is where the list of optional packages (OP) can be determined
    var dependencies = currentAppPackage.Dependencies;

    for (var package in dependencies)
    {
        //  If it is optional, then add it to our results vector
        if (package.IsOptional)
        {
            WriteLine("Optional Package found - {package.Id.FullName}");
        }
    }
```

How do I invoke the code that is present in these optional packages.

答:
How to invoke code in C# optional package from a UWP app written in C#

Please check create optional package in C# step 8, we need add the .winmd file to the main project. If we do this step we could call the optional package api directly.

Add a reference from the main app project to the .winmd file found in this folder. Every time you change the API surface area in the optional package project, this .winmd file must be updated.

Body:
It is now possible to create optional package in C#. However, it is not clear how to invoke the code in the optional package from a C# UWP main app, especially if we need to invoke it in a generic fashion.

Say, I have a plugins within the optional package and they all implement IPlugin interface with an Execute  method and Name property. I would like to display the Names of all the plugins in a menu and invoke the Execute method of plugin when user clicks on it.

We can iterate over all the optional packages of the main app, something like

    // Obtain the app's package first to then find all related packages
    var currentAppPackage = Windows.ApplicationModel.Package.Current;

    // The dependencies list is where the list of optional packages (OP) can be determined
    var dependencies = currentAppPackage.Dependencies;

    for (var package in dependencies)
    {
        //  If it is optional, then add it to our results vector
        if (package.IsOptional)
        {
            WriteLine("Optional Package found - {package.Id.FullName}");
        }
    }

How do I invoke the code that is present in these optional packages.


问:
Laravel-admin: relation many-to-many does't work
I use laravel-admin (https://laravel-admin.org) in my laravel project. I wish to show on User admin panel role names of user. But I get error message:

SQLSTATE[42703]: Undefined column: 7 ERROR: column users_roles.role___id does not exist LINE 1: ...les" inner join "users_roles" on "roles"."__id" = "users_rol... ^ (SQL: select "roles".*, "users_roles"."user___id" as "pivot_user___id", "users_roles"."role___id" as "pivot_role___id" from "roles" inner join "users_roles" on "roles"."__id" = "users_roles"."role___id" where "users_roles"."user___id" in (1, 2, 3))

Here are my classes and controller:

User.php:

```<code>
namespace App\Models;

/**
 * Class User
 * @package App\Models
 *
 * @property integer $__id
 * @property string $email
 * @property string $password
 * @property string|null $firstname
 * @property string|null $lastname
 * @property \DateTime|null $visited_at
 * @property string|null $phone
 * @property string|null $avatar
 * @property string|null $remember_token
 * @property \DateTime $created_at
 * @property \DateTime $updated_at
 */
class User extends Authenticatable
{
    use Notifiable;

    protected $primaryKey = '__id';

    public function roles() :BelongsToMany
    {
        return $this->belongsToMany(Role::class,'users_roles');
    }
}

Role.php:
<?php

namespace App\Models;

/**
 * Class Role
 * @package App\Models
 *
 * @property integer $__id
 * @property string $key
 * @property string $name
 */
class Role extends Model
{
    protected $primaryKey = '__id';

    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class,'users_roles');
    }
}

UserController.php:

<?php
namespace App\Admin\Controllers;

class UserController extends AdminController
{
    protected $title = 'User';

    protected function grid()
    {
        $grid = new Grid(new User());

        $grid->column('__id', __('  id'));
        $grid->column('email', __('Email'));
        $grid->column('password', __('Password'));
        $grid->column('firstname', __('Firstname'));
        $grid->column('lastname', __('Lastname'));

        $grid->roles()->display(function($roles) {

            $roles = array_map(function ($role) {
                return "<span class='label label-success'>{$role['name']}</span>";
            }, $roles);

            return join(' ', $roles);
        });
        .......
         .........
}

Pivot table users_roles:

create table if not exists users_roles
(
    __user_id bigint not null
        constraint users_roles___user_id_foreign
            references users,
    __role_id bigint not null
        constraint users_roles___role_id_foreign
            references roles,
    become_at timestamp(0) not null,
    left_at timestamp(0)
);
</code>```

I have noticed that name of column  __role_id the pivot table is transformed in the query  as role___id (as error message tells me: "ERROR: column users_roles.role___id"). How to solve this problem?

答:
I had to make some correction:

```<code> public function roles() :BelongsToMany
    {
      return $this->belongsToMany(Role::class,'users_roles',
          '__user_id','__role_id');
    }
</code>```

and error message disappeared.

Body:
I use laravel-admin (https://laravel-admin.org) in my laravel project. I wish to show on User admin panel role names of user. But I get error message:

SQLSTATE[42703]: Undefined column: 7 ERROR: column users_roles.role___id does not exist LINE 1: ...les" inner join "users_roles" on "roles"."__id" = "users_rol... ^ (SQL: select "roles".*, "users_roles"."user___id" as "pivot_user___id", "users_roles"."role___id" as "pivot_role___id" from "roles" inner join "users_roles" on "roles"."__id" = "users_roles"."role___id" where "users_roles"."user___id" in (1, 2, 3))

Here are my classes and controller:

User.php:

namespace App\Models;

/**
 * Class User
 * @package App\Models
 *
 * @property integer $__id
 * @property string $email
 * @property string $password
 * @property string|null $firstname
 * @property string|null $lastname
 * @property \DateTime|null $visited_at
 * @property string|null $phone
 * @property string|null $avatar
 * @property string|null $remember_token
 * @property \DateTime $created_at
 * @property \DateTime $updated_at
 */
class User extends Authenticatable
{
    use Notifiable;

    protected $primaryKey = '__id';

    public function roles() :BelongsToMany
    {
        return $this->belongsToMany(Role::class,'users_roles');
    }
}

Role.php:
<?php

namespace App\Models;

/**
 * Class Role
 * @package App\Models
 *
 * @property integer $__id
 * @property string $key
 * @property string $name
 */
class Role extends Model
{
    protected $primaryKey = '__id';

    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class,'users_roles');
    }
}

UserController.php:

<?php
namespace App\Admin\Controllers;

class UserController extends AdminController
{
    protected $title = 'User';

    protected function grid()
    {
        $grid = new Grid(new User());

        $grid->column('__id', __('  id'));
        $grid->column('email', __('Email'));
        $grid->column('password', __('Password'));
        $grid->column('firstname', __('Firstname'));
        $grid->column('lastname', __('Lastname'));

        $grid->roles()->display(function($roles) {

            $roles = array_map(function ($role) {
                return "{$role['name']}";
            }, $roles);

            return join(' ', $roles);
        });
        .......
         .........
}

Pivot table users_roles:

create table if not exists users_roles
(
    __user_id bigint not null
        constraint users_roles___user_id_foreign
            references users,
    __role_id bigint not null
        constraint users_roles___role_id_foreign
            references roles,
    become_at timestamp(0) not null,
    left_at timestamp(0)
);

I have noticed that name of column  __role_id the pivot table is transformed in the query  as role___id (as error message tells me: "ERROR: column users_roles.role___id"). How to solve this problem?

Body:
I had to make some correction:

 public function roles() :BelongsToMany
    {
      return $this->belongsToMany(Role::class,'users_roles',
          '__user_id','__role_id');
    }

and error message disappeared.


问:
How to make an alterable Xamarin.Form Xaml Page?
I'd like to realize a Xaml Page in Xamarin.Form which can be modified by a user input. For example if the user click on a button, the app displays a Date Picker, and if the user click on another button the app removes the Date Picker and displays a Text entry at the exact same place.
I've tried to use the 'IsVisible' attribute but it doesn't work as I expected (the xaml object is still there but is just invisible, so I can't replace it).

Any suggestions ?

答:
If you want to let your xaml page display like an alert , you could use the plugin Rg.Plugins.Popup from nuget .

Usage

```<code><?xml version="1.0" encoding="utf-8" ?>
<pages:PopupPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"
    xmlns:animations="clr-namespace:Rg.Plugins.Popup.Animations;assembly=Rg.Plugins.Popup"
    x:Class="MyProject.MyPopupPage">
    <!--You can set an animation in the xaml file or in the csharp code behind-->
    <pages:PopupPage.Animation>
        <animations:ScaleAnimation
            PositionIn="Center"
            PositionOut="Center"
            ScaleIn="1.2"
            ScaleOut="0.8"
            DurationIn="400"
            DurationOut="300"
            EasingIn="SinOut"
            EasingOut="SinIn"
            HasBackgroundAnimation="True"/>
    </pages:PopupPage.Animation>

    <!--You can use any elements here which are extended from Xamarin.Forms.View-->
    <StackLayout
        VerticalOptions="Center"
        HorizontalOptions="Center"
        Padding="20, 20, 20, 20">
        <Label
            Text="Test"/>
    </StackLayout>
</pages:PopupPage>
</code>```
```<code>public partial class MyPopupPage : Rg.Plugins.Popup.Pages.PopupPage
    {
        public MyPopupPage()
        {
            InitializeComponent();
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();
        }

        protected override void OnDisappearing()
        {
            base.OnDisappearing();
        }

        // ### Methods for supporting animations in your popup page ###

        // Invoked before an animation appearing
        protected override void OnAppearingAnimationBegin()
        {
            base.OnAppearingAnimationBegin();
        }

        // Invoked after an animation appearing
        protected override void OnAppearingAnimationEnd()
        {
            base.OnAppearingAnimationEnd();
        }

        // Invoked before an animation disappearing
        protected override void OnDisappearingAnimationBegin()
        {
            base.OnDisappearingAnimationBegin();
        }

        // Invoked after an animation disappearing
        protected override void OnDisappearingAnimationEnd()
        {
            base.OnDisappearingAnimationEnd();
        }

        protected override Task OnAppearingAnimationBeginAsync()
        {
            return base.OnAppearingAnimationBeginAsync();
        }

        protected override Task OnAppearingAnimationEndAsync()
        {
            return base.OnAppearingAnimationEndAsync();
        }

        protected override Task OnDisappearingAnimationBeginAsync()
        {
            return base.OnDisappearingAnimationBeginAsync();
        }

        protected override Task OnDisappearingAnimationEndAsync()
        {
            return base.OnDisappearingAnimationEndAsync();
        }

        // ### Overrided methods which can prevent closing a popup page ###

        // Invoked when a hardware back button is pressed
        protected override bool OnBackButtonPressed()
        {
            // Return true if you don't want to close this popup page when a back button is pressed
            return base.OnBackButtonPressed();
        }

        // Invoked when background is clicked
        protected override bool OnBackgroundClicked()
        {
            // Return false if you don't want to close this popup page when a background of the popup page is clicked
            return base.OnBackgroundClicked();
        }
    }
</code>```

The plugin has default animations which you can use very simply . For more details you could check https://github.com/rotorgames/Rg.Plugins.Popup/wiki/PopupPage .

Body:
If you want to let your xaml page display like an alert , you could use the plugin Rg.Plugins.Popup from nuget .

Usage

<?xml version="1.0" encoding="utf-8" ?>
<pages:PopupPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"
    xmlns:animations="clr-namespace:Rg.Plugins.Popup.Animations;assembly=Rg.Plugins.Popup"
    x:Class="MyProject.MyPopupPage">
    <!--You can set an animation in the xaml file or in the csharp code behind-->
    <pages:PopupPage.Animation>
        <animations:ScaleAnimation
            PositionIn="Center"
            PositionOut="Center"
            ScaleIn="1.2"
            ScaleOut="0.8"
            DurationIn="400"
            DurationOut="300"
            EasingIn="SinOut"
            EasingOut="SinIn"
            HasBackgroundAnimation="True"/>
    </pages:PopupPage.Animation>

    <!--You can use any elements here which are extended from Xamarin.Forms.View-->
    <StackLayout
        VerticalOptions="Center"
        HorizontalOptions="Center"
        Padding="20, 20, 20, 20">
        <Label
            Text="Test"/>
    </StackLayout>
</pages:PopupPage>

public partial class MyPopupPage : Rg.Plugins.Popup.Pages.PopupPage
    {
        public MyPopupPage()
        {
            InitializeComponent();
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();
        }

        protected override void OnDisappearing()
        {
            base.OnDisappearing();
        }

        // ### Methods for supporting animations in your popup page ###

        // Invoked before an animation appearing
        protected override void OnAppearingAnimationBegin()
        {
            base.OnAppearingAnimationBegin();
        }

        // Invoked after an animation appearing
        protected override void OnAppearingAnimationEnd()
        {
            base.OnAppearingAnimationEnd();
        }

        // Invoked before an animation disappearing
        protected override void OnDisappearingAnimationBegin()
        {
            base.OnDisappearingAnimationBegin();
        }

        // Invoked after an animation disappearing
        protected override void OnDisappearingAnimationEnd()
        {
            base.OnDisappearingAnimationEnd();
        }

        protected override Task OnAppearingAnimationBeginAsync()
        {
            return base.OnAppearingAnimationBeginAsync();
        }

        protected override Task OnAppearingAnimationEndAsync()
        {
            return base.OnAppearingAnimationEndAsync();
        }

        protected override Task OnDisappearingAnimationBeginAsync()
        {
            return base.OnDisappearingAnimationBeginAsync();
        }

        protected override Task OnDisappearingAnimationEndAsync()
        {
            return base.OnDisappearingAnimationEndAsync();
        }

        // ### Overrided methods which can prevent closing a popup page ###

        // Invoked when a hardware back button is pressed
        protected override bool OnBackButtonPressed()
        {
            // Return true if you don't want to close this popup page when a back button is pressed
            return base.OnBackButtonPressed();
        }

        // Invoked when background is clicked
        protected override bool OnBackgroundClicked()
        {
            // Return false if you don't want to close this popup page when a background of the popup page is clicked
            return base.OnBackgroundClicked();
        }
    }

The plugin has default animations which you can use very simply . For more details you could check https://github.com/rotorgames/Rg.Plugins.Popup/wiki/PopupPage .


问:
Plot based on group
I have dataset with total of 500 rows: 250 pop, 250 heavy-metal. How can i produce this plot in R?

My actual dataset is not seperated like the example i give though. Should i just seperate it?

What i have done so far

```<code>ggplot(data = playlist, aes(x = genre, y = danceability)) +
  geom_jitter(aes(col = genre))
</code>```

答:
Please see this post about creating a simple self-contained example.

Given the screenshots you've given us, I don't see how you can produce the plot you're after because you have only one numeric variable - danceability.  The scatter plot needs two - Data on the x-axis in your example.

That said, once you've got your second numeric variable, you've almost answered your own question.  Something like

```<code>ggplot(data = playlist, aes(x = Data, y = danceability)) +
  geom_jitter(aes(col = genre))
</code>```

will give you what you want.

Title: Plot based on group

Body:
I have dataset with total of 500 rows: 250 pop, 250 heavy-metal. How can i produce this plot in R?

My actual dataset is not seperated like the example i give though. Should i just seperate it?

What i have done so far

ggplot(data = playlist, aes(x = genre, y = danceability)) +
  geom_jitter(aes(col = genre))

Body:
Please see this post about creating a simple self-contained example.

Given the screenshots you've given us, I don't see how you can produce the plot you're after because you have only one numeric variable - danceability.  The scatter plot needs two - Data on the x-axis in your example.

That said, once you've got your second numeric variable, you've almost answered your own question.  Something like

ggplot(data = playlist, aes(x = Data, y = danceability)) +
  geom_jitter(aes(col = genre))

will give you what you want.


问:
How to get element id using alias attribute in Mootools
How to get element id using alias attribute in Mootools</p>

```<code><input type="text" alias="school_name" value="" id="test_school" name="test_school">
</code>```

答:
You can use the $$ function to return an element based on a css selector. You can use the css attribute selector syntax to retrieve elements based on an attribute.

```<code>// Returns all inputs with an alias of school_name
var els = $$('input[alias=school_name]');
</code>```

This will return an array of elements.

You can then do els[0].id to retrieve the id of the first element (or loop through the elements as you see fit)

Body:
How to get element id using alias attribute in Mootools

<input type="text" alias="school_name" value="" id="test_school" name="test_school">

Body:
You can use the $$ function to return an element based on a css selector. You can use the css attribute selector syntax to retrieve elements based on an attribute.

// Returns all inputs with an alias of school_name
var els = $$('input[alias=school_name]');

This will return an array of elements.

You can then do els[0].id to retrieve the id of the first element (or loop through the elements as you see fit)


问:
Query Google Adsense data by URL?
Is there any way to query data in the Google Adsense Python API by URL? For example, find the number of ad clicks on a specific page?

I can find no direct method listed in the documentation. The only possible workaround I see is to manually create an "Ad Channel" for each unique URL, then use that channel Id in the ad code on each page, and then query by that channel. However, that's not practical for sites with hundreds, much less thousands of pages. You'd either have weeks of tedious manual work creating channels and copy and pasting ad code, or would have to build out a sophisticated tool to automate ad channels for each URL.

I find it hard to believe no one working at Google nor anyone using Google tools has never wanted to find the ad value of a specific webpage.

Is there a simpler or more direct way to find this information?

答: You can use URL Channels to declare the specific pages you want to track, and then in the API you can include the URL_CHANNEL_ID or URL_CHANNEL_NAME dimension in your report to break down by page. </p>

Title: Query Google Adsense data by URL?


问:
Correct S3 Policy For Pre-Signed URLs
I need to issue pre-signed URLs for allowing users to GET and PUT files into a specific S3 bucket. I created an IAM user and use its keys to create the pre-signed URLs, and added a custom policy embedded in that user (see below). When I use the generated URL, I get an AccessDenied error with my policy. If I add the FullS3Access policy to the IAM user, the file can be GET or PUT with the same URL, so obviously, my custom policy is lacking. What is wrong with it?

Here's the custom policy I am using that is not working:

```<code>{
    "Statement": [
        {
            "Action": [
                "s3:ListBucket"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::MyBucket"
            ]
        },
        {
            "Action": [
                "s3:AbortMultipartUpload",
                "s3:CreateBucket",
                "s3:DeleteBucket",
                "s3:DeleteBucketPolicy",
                "s3:DeleteObject",
                "s3:GetBucketPolicy",
                "s3:GetLifecycleConfiguration",
                "s3:GetObject",
                "s3:ListBucket",
                "s3:ListBucketMultipartUploads",
                "s3:ListMultipartUploadParts",
                "s3:PutBucketPolicy",
                "s3:PutLifecycleConfiguration",
                "s3:PutObject"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::MyBucket/*"
            ]
        }
    ]
}
</code>```

答:
I was also working on a feature that used presigned GET and put URLs, specifically by a role associated with an AWS Lambda function. I found a bit of a twist though in that I also needed to also allow permission to use the KMS key that was encrypting the bucket.

I ran across this off-the-beaten-path article the pointed me in the right direction.  It's not necessary to allow bucket-level permissions for URL presigning, only a handful of object-level permissions.

In short, my lambda role policy to support presigned URLs looked like the following.  Note that the cloudwatch log permission is irrelevant for signing, but generally important for lambda functions:

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*",
      "Effect": "Allow"
    },
    {
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Resource": "<my-bucket-arn-expression>/*",
      "Effect": "Allow"
    },
    {
      "Sid": "KMSAccess",
      "Action": [
        "kms:Decrypt",
        "kms:DescribeKey",
        "kms:Encrypt",
        "kms:GenerateDataKey*",
        "kms:ReEncrypt*"
      ],
      "Effect": "Allow",
      "Resource": "<my-key-arn>"
    }
  ]
}
</code>```

If you are using the built-in AES encryption (or no encryption), your policy can be simplified to this:

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*",
      "Effect": "Allow"
    },
    {
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Resource": "<my-bucket-arn-expression>/*",
      "Effect": "Allow"
    }
  ]
}
</code>```

Title: Correct S3 Policy For Pre-Signed URLs

Body:
I need to issue pre-signed URLs for allowing users to GET and PUT files into a specific S3 bucket. I created an IAM user and use its keys to create the pre-signed URLs, and added a custom policy embedded in that user (see below). When I use the generated URL, I get an AccessDenied error with my policy. If I add the FullS3Access policy to the IAM user, the file can be GET or PUT with the same URL, so obviously, my custom policy is lacking. What is wrong with it?

Here's the custom policy I am using that is not working:

{
    "Statement": [
        {
            "Action": [
                "s3:ListBucket"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::MyBucket"
            ]
        },
        {
            "Action": [
                "s3:AbortMultipartUpload",
                "s3:CreateBucket",
                "s3:DeleteBucket",
                "s3:DeleteBucketPolicy",
                "s3:DeleteObject",
                "s3:GetBucketPolicy",
                "s3:GetLifecycleConfiguration",
                "s3:GetObject",
                "s3:ListBucket",
                "s3:ListBucketMultipartUploads",
                "s3:ListMultipartUploadParts",
                "s3:PutBucketPolicy",
                "s3:PutLifecycleConfiguration",
                "s3:PutObject"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::MyBucket/*"
            ]
        }
    ]
}

Body:
I was also working on a feature that used presigned GET and put URLs, specifically by a role associated with an AWS Lambda function. I found a bit of a twist though in that I also needed to also allow permission to use the KMS key that was encrypting the bucket.

I ran across this off-the-beaten-path article the pointed me in the right direction.  It's not necessary to allow bucket-level permissions for URL presigning, only a handful of object-level permissions.

In short, my lambda role policy to support presigned URLs looked like the following.  Note that the cloudwatch log permission is irrelevant for signing, but generally important for lambda functions:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*",
      "Effect": "Allow"
    },
    {
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Resource": "<my-bucket-arn-expression>/*",
      "Effect": "Allow"
    },
    {
      "Sid": "KMSAccess",
      "Action": [
        "kms:Decrypt",
        "kms:DescribeKey",
        "kms:Encrypt",
        "kms:GenerateDataKey*",
        "kms:ReEncrypt*"
      ],
      "Effect": "Allow",
      "Resource": "<my-key-arn>"
    }
  ]
}

If you are using the built-in AES encryption (or no encryption), your policy can be simplified to this:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*",
      "Effect": "Allow"
    },
    {
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Resource": "<my-bucket-arn-expression>/*",
      "Effect": "Allow"
    }
  ]
}


问:
SQL Query syntax in Laravel Controller
The following code is trying to update a column itself by multiplying by an input variable:

```<code>$multiplier = $request->input("disc");

DB::statement('SET entries UPDATE dp = dp * :multiplier', array('multiplier' => $multiplier));
</code>```

When I run this I get an error regarding my syntax.

I used https://fideloper.com/laravel-raw-queries to try and create my query.

答:
The query syntax is wrong, please check for the correct (assuming it is mysql) one</p>

```<code>$multiplier = $request->input("disc");

DB::statement('UPDATE entries SET dp = dp * :multiplier', ['multiplier' => $multiplier]);
</code>```

Title: SQL Query syntax in Laravel Controller

Body:
The following code is trying to update a column itself by multiplying by an input variable:

$multiplier = $request->input("disc");

DB::statement('SET entries UPDATE dp = dp * :multiplier', array('multiplier' => $multiplier));

When I run this I get an error regarding my syntax.

I used https://fideloper.com/laravel-raw-queries to try and create my query.

Body:
The query syntax is wrong, please check for the correct (assuming it is mysql) one

$multiplier = $request->input("disc");

DB::statement('UPDATE entries SET dp = dp * :multiplier', ['multiplier' => $multiplier]);


问:
Set input integer value in reference to other integer input value to performe a search
I'm trying to create a search filter that allows me to search items in my store. So I have 2 inputs and I want to be able to do the following.

If my minimum price is empty then return 0 as a value to perform the search

If maximum price is lower than minimum price then change the maximum price input into minimum price + 1 to perform the search

If maximum price is empty then return infinite (or a really big number like 1000000) to perform the search

I've tried to create the script following that, but it didn't work. So I'm not sure what I'm doing wrong.

I've updated the script with the help of @Craicerjack, but it still doesn't work.

This is the html with the script.

Thank you so much for taking the time to help me!!

```<code><form method="get" action="https://magiccarpets.online/shop/" target="_self">
  <div class="custom_range_widget">
    <input type="number" name="min_price" min="0" max="50000" placeholder="Min." contenteditable="true" id="minprice" />
    <input type="number" name="max_price" min="0" max="50000" placeholder="Max." contenteditable="true" id="maxprice" />

    <script>
      function  PriceRange() {
        var max = document.getElementById("maxprice"),
        min = document.getElementById("minprice");

        if (min == "") {
          (int)document.getElementById("minprice").value = 0;
        }

        if (parseInt(max) <= parseInt(min){
          (int)document.getElementById("maxprice").value = ((int)document.getElementById("minprice").innerHTML + (int)1);
        }

        if (max == "") {
          (int)document.getElementById("maxprice").value = 1000000;
        }
      }
    </script>
  </div>
  <button type="submit" class="button">Filter</button>
</form>
</code>```

答:
I think, you should replace innerHTML with value in the second if.

function PriceRange() {
    var max = document.getElementById("maxprice").value,
        min = document.getElementById("minprice").value;

    if (min == "") {
      document.getElementById("minprice").value = 0;
    }

    if (parseInt(max) <= parseInt(min)) {
        document.getElementById("maxprice").value = Number(document.getElementById("minprice").value) + 1;
    }

    if (max == "") {
      document.getElementById("maxprice").value = 1000000;
    }
}
```

Body:
I'm trying to create a search filter that allows me to search items in my store. So I have 2 inputs and I want to be able to do the following.

If my minimum price is empty then return 0 as a value to perform the search

If maximum price is lower than minimum price then change the maximum price input into minimum price + 1 to perform the search

If maximum price is empty then return infinite (or a really big number like 1000000) to perform the search

I've tried to create the script following that, but it didn't work. So I'm not sure what I'm doing wrong.

I've updated the script with the help of @Craicerjack, but it still doesn't work.

This is the html with the script.

Thank you so much for taking the time to help me!!

<form method="get" action="https://magiccarpets.online/shop/" target="_self">

    <input type="number" name="min_price" min="0" max="50000" placeholder="Min." contenteditable="true" id="minprice" />
    <input type="number" name="max_price" min="0" max="50000" placeholder="Max." contenteditable="true" id="maxprice" />

  <button type="submit" class="button">Filter</button>
</form>


问:
How to Create a C# COM Object using Visual Studio 2019
I have upgraded from Windows 7/Visual Studio 2015 to Windows10/Visual Studio 2019.
I wish to create a C# COM object which I can call from Excel(365) VBA code.

Using Win 7/Visual Studio 2015 the following very simple code compiles as a C# class library and creates a COM object that I can call successfully from Excel 2013 VBA:-

```<code>using System.Runtime.InteropServices;
namespace TestLib {
    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.AutoDual)]
    public class C_Hello {
        public string Hello() {
            return "Hello";
        }
    }
}
</code>```

In the Assembly Info I have ticked the checkbox "Make the Assembly COM Visible" and in the Build info I have ticked the checkbox "Register for COM interop"

The Excel 2013 VBA code is equally simple:

```<code>Sub Test()
    Dim x As TestLib.C_Hello
    Set x = New TestLib.C_Hello
    ActiveSheet.Range("C3").Value = x.Hello
End Sub
</code>```

where TestLib is the C# COM module created in Visual Studio.

In the Win 7/VS2015/Excel 2013 environment everything works fine, but under after transferring and compiling under Win 10/ VS2019 the Excel 365 VBA code errors at the line:-

```<code>Set x = New TestLib.C_Hello
</code>```

with the error message

Run Time error '-2147221164 (80040154)'

Class not registered

Can anyone tell me what I have to do to get this working in the Windows 10 / VS2019 / Excel 365 environment.? Is it Windows 10 or Visual Studio 2019 that is doing things differently?

答:
Make sure the bitness of excel matches your build in VS. You will likely need to add an x86 or x64 build for your project.

It is possible to register an AnyCpu assembly, but visual studio does not do so with the “Register for COM interop” for both.  You can manually do so by running both the 32- and 64-bit versions of regasm manually or from a post-build script.

Failing that, you might use ProcMon to check what registration or file Excel is looking for and not finding. Warning, though, that unless you are familiar with the “normal” errors which occur when running it is easy to troubleshoot a red herring. I would recommend filtering by “Path” contains “TestLib.C_Hello” then chase it from there.

Body:
I have upgraded from Windows 7/Visual Studio 2015 to Windows10/Visual Studio 2019.
I wish to create a C# COM object which I can call from Excel(365) VBA code.

Using Win 7/Visual Studio 2015 the following very simple code compiles as a C# class library and creates a COM object that I can call successfully from Excel 2013 VBA:-

using System.Runtime.InteropServices;
namespace TestLib {
    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.AutoDual)]
    public class C_Hello {
        public string Hello() {
            return "Hello";
        }
    }
}

In the Assembly Info I have ticked the checkbox "Make the Assembly COM Visible" and in the Build info I have ticked the checkbox "Register for COM interop"

The Excel 2013 VBA code is equally simple:

Sub Test()
    Dim x As TestLib.C_Hello
    Set x = New TestLib.C_Hello
    ActiveSheet.Range("C3").Value = x.Hello
End Sub

where TestLib is the C# COM module created in Visual Studio.

In the Win 7/VS2015/Excel 2013 environment everything works fine, but under after transferring and compiling under Win 10/ VS2019 the Excel 365 VBA code errors at the line:-

Set x = New TestLib.C_Hello

with the error message

Run Time error '-2147221164 (80040154)'

Class not registered

Can anyone tell me what I have to do to get this working in the Windows 10 / VS2019 / Excel 365 environment.? Is it Windows 10 or Visual Studio 2019 that is doing things differently?


问:
Persisting java.time.LocalTime into oracle with Types.TIME loses fractional seconds precision
I have a behavior with Oracle which I'm not sure is intended or not.

I am playing with the various types of the java date/time API, using them at the JDBC level.

I am trying to persist an instance of java.time.LocalTime into an oracle database.

At the JDBC level, my understanding is that I'm supposed to use :

A JDBC 4.2 compliant driver

PreparedStatement.setObject(int parameterIndex, Object x, int targetSqlType)

Types.TIME as the targetSqlType for a java.time.LocalTime instance

Since oracle doesn't provide a TIME type, I use a TIMESTAMP field.

The problem is if I use Types.TIME at the JDBC level, I'm losing the fractional second precision.

If I use Types.TIMESTAMP, the precision is kept intact.

I'd like to use the JDBC intended standard mapping for LocalTime, if possible with Oracle.

Here the tests showing the behavior :

```<code>@Test
public void testSetObjectWithSqlTypeTimestamp() {
    testSetObjectWithSqlType("java.sql.Types.TIMESTAMP", Types.TIMESTAMP);
}

@Test
public void testSetObjectWithSqlTypeTime() {
    testSetObjectWithSqlType("java.sql.Types.TIME", Types.TIME);
}

private void testSetObjectWithSqlType(String sqlTypeLabel, Integer sqlTypeValue) {
    logger.info("Testing setObject with {} (value={})", sqlTypeLabel, sqlTypeValue);

    LocalTime willBeInserted = LocalTime.of(21, 17, 23, 678_987_000);

    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = dataSource.getConnection();
        con.setAutoCommit(false);
        ps = con.prepareStatement("insert into LOCAL_TIME_TABLE (FOO) values (?)");
        ps.setObject(1, willBeInserted, sqlTypeValue);

        ps.executeUpdate();
        con.commit();
    } catch (SQLException e) {
        rollbackQuietly(con);
        throw new RuntimeException("Error inserting test value", e);
    } finally {
        JdbcUtils.closeStatement(ps);
        JdbcUtils.closeConnection(con);
    }

    List<LocalTime> results = jdbcTemplate.queryForList("select FOO from LOCAL_TIME_TABLE", LocalTime.class);
    assertThat(results)
        .containsExactlyInAnyOrder(willBeInserted)
        .hasSize(1);
}
</code>```

The Types.TIMESTAMP test works fine.

The Types.TIME test has the following error :

```<code> [ERROR] Failures:
 [ERROR]   LocalTimeSetObjectWithSqlTypeOracleBugTest.testSetObjectWithSqlTypeTime:44->testSetObjectWithSqlType:72
 Expecting:
   <[21:17:23]>
 to contain exactly in any order:
   <[21:17:23.678987]>
 elements not found:
   <[21:17:23.678987]>
 and elements not expected:
   <[21:17:23]>
</code>```

This is a spring-boot test (DataSource and JdbcTemplate are provided by spring).
I didn't detail all the spring boilerplate code, this didn't seem relevant to the problem; but I'll add it if need be.

My FOO table looks like this :

```<code>create table LOCAL_TIME_TABLE (
    FOO timestamp
);
</code>```

I'm using the following Oracle image : https://hub.docker.com/r/wnameless/oracle-xe-11g-r2

And the following driver (maven coordinates) : com.oracle.database.jdbc:ojdbc10:19.3.0.0

So I guess my question is two fold :

Am I correct in assuming that the intended standard JDBC mapping for LocalTime is : ps.setObject(1, localTime, Types.TIME) ? If Not, what is the supposed intended JDBC way?

Is the Oracle behavior intended? If yes, is it documented somewhere?

Also, this is my first SO question, so any feedback is welcome.

Happy coding!

答:
Oracle Database stores TIME values in the Oracle SQL DATE format. Oracle SQL DATE does not store fractional seconds. If fractional seconds are significant then use JDBCType.TIMESTAMP.

The SQL spec is subtle (an understatement). All vendors have slightly different implementations of SQL. The SQL spec is sufficiently flexible that all of the major SQL databases are in compliance, very much including Oracle Database. There are significant differences between the vendors' databases and a casual reading of the SQL spec can be misleading. Oracle Database representing TIME as DATE is allowed as is not storing fractional seconds.

Edited to add: https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/Data-Types.html#GUID-7B72E154-677A-4342-A1EA-C74C1EA928E6

Body:
I have a behavior with Oracle which I'm not sure is intended or not.

I am playing with the various types of the java date/time API, using them at the JDBC level.

I am trying to persist an instance of java.time.LocalTime into an oracle database.

At the JDBC level, my understanding is that I'm supposed to use :

A JDBC 4.2 compliant driver

PreparedStatement.setObject(int parameterIndex, Object x, int targetSqlType)

Types.TIME as the targetSqlType for a java.time.LocalTime instance

Since oracle doesn't provide a TIME type, I use a TIMESTAMP field.

The problem is if I use Types.TIME at the JDBC level, I'm losing the fractional second precision.

If I use Types.TIMESTAMP, the precision is kept intact.

I'd like to use the JDBC intended standard mapping for LocalTime, if possible with Oracle.

Here the tests showing the behavior :

@Test
public void testSetObjectWithSqlTypeTimestamp() {
    testSetObjectWithSqlType("java.sql.Types.TIMESTAMP", Types.TIMESTAMP);
}

@Test
public void testSetObjectWithSqlTypeTime() {
    testSetObjectWithSqlType("java.sql.Types.TIME", Types.TIME);
}

private void testSetObjectWithSqlType(String sqlTypeLabel, Integer sqlTypeValue) {
    logger.info("Testing setObject with {} (value={})", sqlTypeLabel, sqlTypeValue);

    LocalTime willBeInserted = LocalTime.of(21, 17, 23, 678_987_000);

    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = dataSource.getConnection();
        con.setAutoCommit(false);
        ps = con.prepareStatement("insert into LOCAL_TIME_TABLE (FOO) values (?)");
        ps.setObject(1, willBeInserted, sqlTypeValue);

        ps.executeUpdate();
        con.commit();
    } catch (SQLException e) {
        rollbackQuietly(con);
        throw new RuntimeException("Error inserting test value", e);
    } finally {
        JdbcUtils.closeStatement(ps);
        JdbcUtils.closeConnection(con);
    }

    List<LocalTime> results = jdbcTemplate.queryForList("select FOO from LOCAL_TIME_TABLE", LocalTime.class);
    assertThat(results)
        .containsExactlyInAnyOrder(willBeInserted)
        .hasSize(1);
}

The Types.TIMESTAMP test works fine.

The Types.TIME test has the following error :

 [ERROR] Failures:
 [ERROR]   LocalTimeSetObjectWithSqlTypeOracleBugTest.testSetObjectWithSqlTypeTime:44->testSetObjectWithSqlType:72
 Expecting:
   <[21:17:23]>
 to contain exactly in any order:
   <[21:17:23.678987]>
 elements not found:
   <[21:17:23.678987]>
 and elements not expected:
   <[21:17:23]>

This is a spring-boot test (DataSource and JdbcTemplate are provided by spring).
I didn't detail all the spring boilerplate code, this didn't seem relevant to the problem; but I'll add it if need be.

My FOO table looks like this :

create table LOCAL_TIME_TABLE (
    FOO timestamp
);

I'm using the following Oracle image : https://hub.docker.com/r/wnameless/oracle-xe-11g-r2

And the following driver (maven coordinates) : com.oracle.database.jdbc:ojdbc10:19.3.0.0

So I guess my question is two fold :

Am I correct in assuming that the intended standard JDBC mapping for LocalTime is : ps.setObject(1, localTime, Types.TIME) ? If Not, what is the supposed intended JDBC way?

Is the Oracle behavior intended? If yes, is it documented somewhere?

Also, this is my first SO question, so any feedback is welcome.

Happy coding!