问:
Going Fullscreen in win32 without 2 WM_SIZE message
So I am creating a fullscreen function in win32 c++ doing:

uint8_t isFullscreen = 0;

RECT winRect;           //Current Window Rect
RECT nonFullScreenRect; //Rect Not In Full Screen Position (used to restore window to not full screen position when coming out of fullscreen)

uint32_t screen_width = DEFAULT_SCREEN_WIDTH;
uint32_t screen_height = DEFAULT_SCREEN_HEIGHT;

void Fullscreen( HWND WindowHandle )
{
    isFullscreen = isFullscreen ^ 1;
    if( isFullscreen )
    {
        //saving off current window rect
        nonFullScreenRect.left = winRect.left;
        nonFullScreenRect.right = winRect.right;
        nonFullScreenRect.bottom = winRect.bottom;
        nonFullScreenRect.top = winRect.top;
        SetWindowLongPtr( WindowHandle, GWL_STYLE,  WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE );  //causes a resize msg
        HMONITOR hmon = MonitorFromWindow(WindowHandle, MONITOR_DEFAULTTONEAREST);
        MONITORINFO mi = { sizeof( mi ) };
        GetMonitorInfo( hmon, &mi );
        screen_width = mi.rcMonitor.right - mi.rcMonitor.left;
        screen_height = mi.rcMonitor.bottom - mi.rcMonitor.top;
        MoveWindow( WindowHandle, mi.rcMonitor.left, mi.rcMonitor.top, (int32_t)screen_width, (int32_t)screen_height, FALSE );
    }
    else
    {
        SetWindowLongPtr( WindowHandle, GWL_STYLE, WS_OVERLAPPEDWINDOW | WS_VISIBLE );
        screen_width = nonFullScreenRect.right - nonFullScreenRect.left;
        screen_height = nonFullScreenRect.bottom - nonFullScreenRect.top;
        MoveWindow( WindowHandle, nonFullScreenRect.left, nonFullScreenRect.top, (int32_t)screen_width, (int32_t)screen_height, FALSE );
    }
}
```
<p>However when it goes fullscreen, the function generates 2 WM_SIZE messages. While when it goes windowed, it generates only 1.</p>
<p>Why is that the case? And how can I make it generate only 1 WM_SIZE message for the proper full screen size?</p>
<p>How can I update an HWND's style and position atomically? asks about it but no one answers it</p>
<p>The reasons I need this is because I am using DirectX12 and on WM_SIZE I wait for all the signals at the end of the command queues before resizing all the swap chain back buffers. And I don't want to have to resize the swap chain twice when switching to fullscreen mode.</p>
<pre class="lang-cpp prettyprint-override"><code>    case WM_SIZE:
    {
        screen_width = LOWORD( LParam );
        screen_height = HIWORD( LParam );
        //DirectX stuff here
    }break;
</code>```

Thanks in advance!

答:
Updated Answer:

The Win32 API allows you to modify parameters of the window one at a time. When a parameter is modified, the API may or may not update the window and trigger a WM_SIZE that will be the size of the window given the current parameters.

Since to have a complete full screen window you need to make at least 2 calls, one to update GWL_STYLE and another to update GWL_EXSTYLE, you have a big chance of getting 2 WM_SIZE calls. One of them will give you the window size without the menu, and the other the full screen window size. It depends in which order you call SetWindowLongPtr, but you'll probably get 2 WM_SIZE and only the second one is "correct", i.e. the one you want in the end.

The more reliable solution to your problem is to use a variable at the top of Main.cpp:

int isTogglingFullScreen = false;

Then inside your full screen toggle code (note where isTogglingFullScreen  is being set):

```<code>   case WM_SYSKEYDOWN:
        if (wParam == VK_RETURN && (lParam & 0x60000000) == 0x20000000)
        {
            // Implements the classic ALT+ENTER fullscreen toggle
            if (s_fullscreen)
            {
                isTogglingFullScreen = true;
                SetWindowLongPtr(hWnd, GWL_STYLE, WS_OVERLAPPEDWINDOW);
                isTogglingFullScreen = false;
                SetWindowLongPtr(hWnd, GWL_EXSTYLE, 0);

                int width = 800;
                int height = 600;
                if (game)
                    game->GetDefaultSize(width, height);

                SetWindowPos(hWnd, HWND_TOP, 0, 0, width, height, SWP_NOMOVE | SWP_NOZORDER | SWP_FRAMECHANGED);

                ShowWindow(hWnd, SW_SHOWNORMAL);

            }
            else
            {
                isTogglingFullScreen = true;
                SetWindowLongPtr(hWnd, GWL_EXSTYLE, WS_EX_TOPMOST);
                SetWindowLongPtr(hWnd, GWL_STYLE, WS_POPUP);
                SetWindowPos(hWnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);

                isTogglingFullScreen = false;

                ShowWindow(hWnd, SW_SHOWMAXIMIZED);
            }

            s_fullscreen = !s_fullscreen;
        }
        break;
</code>```

Finally, inside WM_SIZE, change

```<code>        else if (!s_in_sizemove && game)
        {
            game->OnWindowSizeChanged(LOWORD(lParam), HIWORD(lParam));
        }
</code>```

to

```<code>        else if (!s_in_sizemove && game && !isTogglingFullScreen)
        {
            game->OnWindowSizeChanged(LOWORD(lParam), HIWORD(lParam));
        }
</code>```

This will give you a single call to OnWindowSizeChanged() when you toggle full screen, and the call will be with the correct final size.

--

Old Answer:

If you only want a single WM_SIZE to trigger, when you switch to full screen then you should go for something like this:

```<code>    SetWindowLongPtr(hWnd, GWL_EXSTYLE, WS_EX_TOPMOST);
    SetWindowPos(hWnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
    ShowWindow(hWnd, SW_SHOWMAXIMIZED);
</code>```

Any SetWindowLongPtr call to GWL_STYLE will trigger a WM_SIZE, so make sure it's only called with GWL_EXSTYLE. For example, if you both set GWL_EXSTYLE to what you want, and reset GWL_STYLE to 0, you'll trigger WM_SIZE twice.

To make it clearer:

Don't use GWL_STYLE in SetWindowLongPtr because it triggers a useless WM_SIZE

ShowWindow will trigger WM_SIZE

The above code will ultimately only trigger WM_SIZE once.

It turns out that YMMV. It's entirely possible that the first time you switch fullscreen, you'll get 2 WM_SIZE. One will be with the original size, and the other with the new size. Subsequent calls will trigger only one WM_SIZE.

Hence, the really bulletproof solution (which I was using anyway before playing around with the SetWindowLongPtr to answer this question, is to validate that the window size has actually changed. Because one thing that I can guarantee in the above call is that you'll never get more than 1 call with the new size. At most you'll get a WM_SIZE call with the old size, which you'll discard by checking that it's the same as the current size.

If you use the DevicesResources template for DX12, you'll see that there's a check in OnWindowSizeChanged() that does nothing if the size hasn't changed.

Body:
So I am creating a fullscreen function in win32 c++ doing:

uint8_t isFullscreen = 0;

RECT winRect;           //Current Window Rect
RECT nonFullScreenRect; //Rect Not In Full Screen Position (used to restore window to not full screen position when coming out of fullscreen)

uint32_t screen_width = DEFAULT_SCREEN_WIDTH;
uint32_t screen_height = DEFAULT_SCREEN_HEIGHT;

void Fullscreen( HWND WindowHandle )
{
    isFullscreen = isFullscreen ^ 1;
    if( isFullscreen )
    {
        //saving off current window rect
        nonFullScreenRect.left = winRect.left;
        nonFullScreenRect.right = winRect.right;
        nonFullScreenRect.bottom = winRect.bottom;
        nonFullScreenRect.top = winRect.top;
        SetWindowLongPtr( WindowHandle, GWL_STYLE,  WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE );  //causes a resize msg
        HMONITOR hmon = MonitorFromWindow(WindowHandle, MONITOR_DEFAULTTONEAREST);
        MONITORINFO mi = { sizeof( mi ) };
        GetMonitorInfo( hmon, &mi );
        screen_width = mi.rcMonitor.right - mi.rcMonitor.left;
        screen_height = mi.rcMonitor.bottom - mi.rcMonitor.top;
        MoveWindow( WindowHandle, mi.rcMonitor.left, mi.rcMonitor.top, (int32_t)screen_width, (int32_t)screen_height, FALSE );
    }
    else
    {
        SetWindowLongPtr( WindowHandle, GWL_STYLE, WS_OVERLAPPEDWINDOW | WS_VISIBLE );
        screen_width = nonFullScreenRect.right - nonFullScreenRect.left;
        screen_height = nonFullScreenRect.bottom - nonFullScreenRect.top;
        MoveWindow( WindowHandle, nonFullScreenRect.left, nonFullScreenRect.top, (int32_t)screen_width, (int32_t)screen_height, FALSE );
    }
}

However when it goes fullscreen, the function generates 2 WM_SIZE messages. While when it goes windowed, it generates only 1.

Why is that the case? And how can I make it generate only 1 WM_SIZE message for the proper full screen size?

How can I update an HWND's style and position atomically? asks about it but no one answers it

The reasons I need this is because I am using DirectX12 and on WM_SIZE I wait for all the signals at the end of the command queues before resizing all the swap chain back buffers. And I don't want to have to resize the swap chain twice when switching to fullscreen mode.

    case WM_SIZE:
    {
        screen_width = LOWORD( LParam );
        screen_height = HIWORD( LParam );
        //DirectX stuff here
    }break;

Thanks in advance!

Body:
Updated Answer:

The Win32 API allows you to modify parameters of the window one at a time. When a parameter is modified, the API may or may not update the window and trigger a WM_SIZE that will be the size of the window given the current parameters.

Since to have a complete full screen window you need to make at least 2 calls, one to update GWL_STYLE and another to update GWL_EXSTYLE, you have a big chance of getting 2 WM_SIZE calls. One of them will give you the window size without the menu, and the other the full screen window size. It depends in which order you call SetWindowLongPtr, but you'll probably get 2 WM_SIZE and only the second one is "correct", i.e. the one you want in the end.

The more reliable solution to your problem is to use a variable at the top of Main.cpp:

int isTogglingFullScreen = false;

Then inside your full screen toggle code (note where isTogglingFullScreen  is being set):

   case WM_SYSKEYDOWN:
        if (wParam == VK_RETURN && (lParam & 0x60000000) == 0x20000000)
        {
            // Implements the classic ALT+ENTER fullscreen toggle
            if (s_fullscreen)
            {
                isTogglingFullScreen = true;
                SetWindowLongPtr(hWnd, GWL_STYLE, WS_OVERLAPPEDWINDOW);
                isTogglingFullScreen = false;
                SetWindowLongPtr(hWnd, GWL_EXSTYLE, 0);

                int width = 800;
                int height = 600;
                if (game)
                    game->GetDefaultSize(width, height);

                SetWindowPos(hWnd, HWND_TOP, 0, 0, width, height, SWP_NOMOVE | SWP_NOZORDER | SWP_FRAMECHANGED);

                ShowWindow(hWnd, SW_SHOWNORMAL);

            }
            else
            {
                isTogglingFullScreen = true;
                SetWindowLongPtr(hWnd, GWL_EXSTYLE, WS_EX_TOPMOST);
                SetWindowLongPtr(hWnd, GWL_STYLE, WS_POPUP);
                SetWindowPos(hWnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);

                isTogglingFullScreen = false;

                ShowWindow(hWnd, SW_SHOWMAXIMIZED);
            }

            s_fullscreen = !s_fullscreen;
        }
        break;

Finally, inside WM_SIZE, change

        else if (!s_in_sizemove && game)
        {
            game->OnWindowSizeChanged(LOWORD(lParam), HIWORD(lParam));
        }

to

        else if (!s_in_sizemove && game && !isTogglingFullScreen)
        {
            game->OnWindowSizeChanged(LOWORD(lParam), HIWORD(lParam));
        }

This will give you a single call to OnWindowSizeChanged() when you toggle full screen, and the call will be with the correct final size.

--

Old Answer:

If you only want a single WM_SIZE to trigger, when you switch to full screen then you should go for something like this:

    SetWindowLongPtr(hWnd, GWL_EXSTYLE, WS_EX_TOPMOST);
    SetWindowPos(hWnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
    ShowWindow(hWnd, SW_SHOWMAXIMIZED);

Any SetWindowLongPtr call to GWL_STYLE will trigger a WM_SIZE, so make sure it's only called with GWL_EXSTYLE. For example, if you both set GWL_EXSTYLE to what you want, and reset GWL_STYLE to 0, you'll trigger WM_SIZE twice.

To make it clearer:

Don't use GWL_STYLE in SetWindowLongPtr because it triggers a useless WM_SIZE

ShowWindow will trigger WM_SIZE

The above code will ultimately only trigger WM_SIZE once.

It turns out that YMMV. It's entirely possible that the first time you switch fullscreen, you'll get 2 WM_SIZE. One will be with the original size, and the other with the new size. Subsequent calls will trigger only one WM_SIZE.

Hence, the really bulletproof solution (which I was using anyway before playing around with the SetWindowLongPtr to answer this question, is to validate that the window size has actually changed. Because one thing that I can guarantee in the above call is that you'll never get more than 1 call with the new size. At most you'll get a WM_SIZE call with the old size, which you'll discard by checking that it's the same as the current size.

If you use the DevicesResources template for DX12, you'll see that there's a check in OnWindowSizeChanged() that does nothing if the size hasn't changed.


来源: stackexchange

问:
jQuery Validation using third party plugin
```<code><!DOCTYPE html>
<html>
<head>
    <title>Site :: </title>
    <link rel="stylesheet" media="screen" href="css/wicahost.css" />
    <link rel="stylesheet" media="screen" href="css/global.css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script>
    <script type="text/javascript" src="inc/js/valid.js"></script>
    <SCRIPT TYPE="TEXT/JAVASCRIPT">
    $(document).ready(function() {
        $("#splashtease").RSV({
          onCompleteHandler: myOnComplete,
                rules: [
                        "required,emAdd,Please enter your email address.",
                        "valid_email,emAdd,Please enter a valid email address.",
                       ]
        });
});
    </SCRIPT>
</head>

<body>
    <div id="splashTeaserBox">
    <h1>Signup!</h1>

    <form id="splashtease" action="inc/subscribe.php" method="post">
    <?php $usrBrowser = $_SERVER['HTTP_USER_AGENT']; $todayDt = date('Y-m-d');  ?>
    <input type="text" name="emAdd" />
            <input type="hidden" name="brwsr" value="<?php echo $usrBrowser ?>" />
            <input type="hidden" name="dt" value="<?php echo $todayDt ?>" />
        <input type="submit" name="submit" value="" class="splashteasesub" />
    </form>
    </div><!--splashTeaserBox-->
</body>
</html>
</code>```

Trying to implement this simple example above to validate an email address:
http://www.benjaminkeen.com/software/rsv/jquery/demo.php

The above code isn't doing anything and is just submitting to the database. I checked to make sure my jquery library link reference and jquery script for this 3rd party script to make sure they linked fine and both do link fine.

Anyone see what is going wrong here? Thanks :)

答:
myOnComplete isn't defined.
rules has an extra comma after the second item</p>

ContentLicense: CC BY-SA 3.0

Body:
<!DOCTYPE html>

    <title>Site :: </title>
    <link rel="stylesheet" media="screen" href="css/wicahost.css" />
    <link rel="stylesheet" media="screen" href="css/global.css" />

Signup!

    <form id="splashtease" action="inc/subscribe.php" method="post">
    <?php $usrBrowser = $_SERVER['HTTP_USER_AGENT']; $todayDt = date('Y-m-d');  ?>
    <input type="text" name="emAdd" />
            <input type="hidden" name="brwsr" value="<?php echo $usrBrowser ?>" />
            <input type="hidden" name="dt" value="<?php echo $todayDt ?>" />
        <input type="submit" name="submit" value="" class="splashteasesub" />
    </form>

Trying to implement this simple example above to validate an email address:
http://www.benjaminkeen.com/software/rsv/jquery/demo.php

The above code isn't doing anything and is just submitting to the database. I checked to make sure my jquery library link reference and jquery script for this 3rd party script to make sure they linked fine and both do link fine.

Anyone see what is going wrong here? Thanks :)


问:
Ktor REST response and async code execution
Problem:
I would like to unblock my KTOR response from portions of the code that take longer and can be executed in async manner after the fact.

The core business logic for REST response should not wait for the async tasks such as sending email, kafka event etc..

What I have tried:
I get the desired results with this code example. I can see that the rest response is returned immediately and does not wait on the delayed tasks (email and Kafka message).

I am unclear at this point if I need to keep these lines inside the runBlocking code

```<code>val patient = PatientService.addPatient()
//Return REST response
call.respond(patient)
</code>```

Question
If I keep it out of the runblocking code, the entire rest response is blocked until the email and kafka event code is complete.
Is this the right approach to offload certain delayed code execution
logic from the main REST API response in KTOR?

```<code>fun Route.patientRoute(){
    route("/patient") {
        post (""){
        runBlocking {

            val patient = PatientService.addPatient() //..Business logic to add a new patient

            launch { //unblock the REST response from certain async. tasks
                sendKafkaEvent()
                sendEmail()
            }

            call.respond(patient) //Return REST response
            }
        }
    }
}

suspend fun sendEmail() {
    delay(5000L)    //Mock some delay in the operation
}

suspend fun sendKafkaMessage() {
    delay(5000L) //Mock some delay in the operation
}
</code>```

答:
I would firstly run asynchronous tasks and then call to PatientService.addPatient() to pass its returned value for call.respond.
Additionally, you can specify a different dispatcher for your tasks.

```<code>post("") {
    launch(Dispatchers.IO) {
        sendEmail()
    }

    launch(Dispatchers.IO) {
        sendKafkaEvent()
    }

    call.respond(PatientService.addPatient())
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Problem:
I would like to unblock my KTOR response from portions of the code that take longer and can be executed in async manner after the fact.

The core business logic for REST response should not wait for the async tasks such as sending email, kafka event etc..

What I have tried:
I get the desired results with this code example. I can see that the rest response is returned immediately and does not wait on the delayed tasks (email and Kafka message).

I am unclear at this point if I need to keep these lines inside the runBlocking code

val patient = PatientService.addPatient()
//Return REST response
call.respond(patient)

Question
If I keep it out of the runblocking code, the entire rest response is blocked until the email and kafka event code is complete.
Is this the right approach to offload certain delayed code execution
logic from the main REST API response in KTOR?

fun Route.patientRoute(){
    route("/patient") {
        post (""){
        runBlocking {

            val patient = PatientService.addPatient() //..Business logic to add a new patient

            launch { //unblock the REST response from certain async. tasks
                sendKafkaEvent()
                sendEmail()
            }

            call.respond(patient) //Return REST response
            }
        }
    }
}

suspend fun sendEmail() {
    delay(5000L)    //Mock some delay in the operation
}

suspend fun sendKafkaMessage() {
    delay(5000L) //Mock some delay in the operation
}

Body:
I would firstly run asynchronous tasks and then call to PatientService.addPatient() to pass its returned value for call.respond.
Additionally, you can specify a different dispatcher for your tasks.

post("") {
    launch(Dispatchers.IO) {
        sendEmail()
    }

    launch(Dispatchers.IO) {
        sendKafkaEvent()
    }

    call.respond(PatientService.addPatient())
}


问:
How to insert model from list into stored procedure
My program is making a query from one database and I want that query to be added to a stored procedure in another database.
At first I was insert each parameter as a List, but I want to optimize the code and insert all parameters into one List.
I add all select options to list:

```<code>public void GetResult(SqlCommand command)
        {

            var list = new List<Models>;

            using(var reader = command.ExecuteReader())
                while (reader.Read())
                {
                    var rows = new Models;
                    rows.Md1 = Convert.ToInt32(reader["md1"]);
                    rows.Md2 = Convert.ToInt32(reader["md2"]);

                    list.Add(rows);
                }

            using var InsertCommand = new OracleCommand();
            InsertCommand.CommandText = "PathToProcedure";

            var Param1 = new OracleParameter("param1", OracleDbType.Int32, ParameterDirecion.Input);
            Param1.CollectionType = OracleCollectionType.PLSQLAssociativeArray;
            Param1.Value =
            Param2.Size =

        }
</code>```

Question: How to create a link to these rows to insert them in parameters?
Thanks in advance!

SP:

```<code>create or replace package body transfer_package is

procedure getdt(param1 in t_number,
                param2 in t_number)
        is
  begin
    if param1.count > 0 then
       for i in 1 .. param1.count loop
    insert into table
          (parameter1,
           parameter2)
        values
          (param1(i),
           param2(i));

        end loop;
end;
</code>```

答:
The solution of my question is a Linq library...

```<code>Param1.Value = list.Select(Models => Models.Md1).ToArray();
Param2.Size = list.Select(Models => Models.Md2).ToArray();
</code>```

and so on

Body:
My program is making a query from one database and I want that query to be added to a stored procedure in another database.
At first I was insert each parameter as a List, but I want to optimize the code and insert all parameters into one List.
I add all select options to list:

public void GetResult(SqlCommand command)
        {

            var list = new List<Models>;

            using(var reader = command.ExecuteReader())
                while (reader.Read())
                {
                    var rows = new Models;
                    rows.Md1 = Convert.ToInt32(reader["md1"]);
                    rows.Md2 = Convert.ToInt32(reader["md2"]);

                    list.Add(rows);
                }

            using var InsertCommand = new OracleCommand();
            InsertCommand.CommandText = "PathToProcedure";

            var Param1 = new OracleParameter("param1", OracleDbType.Int32, ParameterDirecion.Input);
            Param1.CollectionType = OracleCollectionType.PLSQLAssociativeArray;
            Param1.Value =
            Param2.Size =

        }

Question: How to create a link to these rows to insert them in parameters?
Thanks in advance!

SP:

create or replace package body transfer_package is

procedure getdt(param1 in t_number,
                param2 in t_number)
        is
  begin
    if param1.count > 0 then
       for i in 1 .. param1.count loop
    insert into table
          (parameter1,
           parameter2)
        values
          (param1(i),
           param2(i));

        end loop;
end;

Body:
The solution of my question is a Linq library...

Param1.Value = list.Select(Models => Models.Md1).ToArray();
Param2.Size = list.Select(Models => Models.Md2).ToArray();

and so on


问:
Find a specific string between 2 strings
This is for Notepad++. I am trying to Find a word between two words; and if found, mark the whole thing.

```<code>    <lootgroup name="Random1" count="1">
      <item group="filler"/>
      <item group="filler"/>
    </lootgroup>

    <lootgroup name="Random2" count="1">
      <item group="filler"/>
      <item group="schematics"/>
      <item group="filler"/>
    </lootgroup>

    <lootgroup name="Random2" count="1">
      <item group="filler"/>
      <item group="schematics"/>
      <item group="filler"/>
      <item group="schematics"/>
    </lootgroup>

</code>```

So I want to Find "schematics" between <lootgroup   and   </lootgroup>; and if found, mark/select all lines including <lootgroup   and   </lootgroup>.

I know about <lootgroup(.*?)</lootgroup> will select everything in between but I cannot figure out what to replace (.*?) with to match only if schematics is present between the two.

Number of "Item Groups" varies and "Item Group" is not always the name. That's why I'm searching for "schematic".

Using Notepad++ Find and Mark function.

Much appreciated.

答:
Ctrl+M

Find what: <lootgroup (?:(?!</lootgroup>).)+\bschematics\b(?:(?!</lootgroup>).)+</lootgroup>

Replace with: LEAVE EMPTY

CHECK Match case

CHECK Wrap around

CHECK Regular expression

CHECK . matches newline

Mark All

Explanation:

<lootgroup                  # opening tag
(?:(?!</lootgroup>).)+      # Tempered greedy token, make sure we don't encounter closing tag
\bschematics\b              # literally
(?:(?!</lootgroup>).)+      # Tempered greedy token, make sure we don't encounter closing tag
</lootgroup>                # closing tag
```

Screenshot:

Body:
This is for Notepad++. I am trying to Find a word between two words; and if found, mark the whole thing.

    <lootgroup name="Random1" count="1">
      <item group="filler"/>
      <item group="filler"/>
    </lootgroup>

    <lootgroup name="Random2" count="1">
      <item group="filler"/>
      <item group="schematics"/>
      <item group="filler"/>
    </lootgroup>

    <lootgroup name="Random2" count="1">
      <item group="filler"/>
      <item group="schematics"/>
      <item group="filler"/>
      <item group="schematics"/>
    </lootgroup>

So I want to Find "schematics" between <lootgroup   and   </lootgroup>; and if found, mark/select all lines including <lootgroup   and   </lootgroup>.

I know about <lootgroup(.*?)</lootgroup> will select everything in between but I cannot figure out what to replace (.*?) with to match only if schematics is present between the two.

Number of "Item Groups" varies and "Item Group" is not always the name. That's why I'm searching for "schematic".

Using Notepad++ Find and Mark function.

Much appreciated.

Body:
Ctrl+M

Find what: <lootgroup (?:(?!</lootgroup>).)+\bschematics\b(?:(?!</lootgroup>).)+</lootgroup>

Replace with: LEAVE EMPTY

CHECK Match case

CHECK Wrap around

CHECK Regular expression

CHECK . matches newline

Mark All

Explanation:

<lootgroup                  # opening tag
(?:(?!</lootgroup>).)+      # Tempered greedy token, make sure we don't encounter closing tag
\bschematics\b              # literally
(?:(?!</lootgroup>).)+      # Tempered greedy token, make sure we don't encounter closing tag
</lootgroup>                # closing tag

Screenshot:


问:
Yii2 UrlManager rules
What would be the Urlmanager rule for changing a url like site/product?name=[name] to product/[name]?

I tried

```<code>'<action:\w+>' => 'site/<action>',
'product/<id:\d+>' => 'product',
</code>```

But it gives me a 404

答:
Before answering to your question a short explain what is wrong.
You try to pass alpha chars to an action that handles only integers.
The rule 'product/<id:\d+>' indicate that the url should be like:

```<code>product/1
product/777
product/8888
</code>```

The regular expression \d+ limits this url part to an integer.

Answer

For url like product/[name], you should add this pattern:

```<code>//...
'product/<name:[\w]+>' => 'product/item',
//...
</code>```

Where 'product/<name:[\w]+>' will match any url like:

```<code>product/any
product/alpha
product/productname
</code>```

The <name:[\w]+> will be the parameter that will hold matched url part and and creates a variable named $name that will contain only the alpha chars, due the regular expression [\w]+. This variable will be passed to controller action.

And 'product/item' is the controller / action that will handle request, in this example is ProductController and actionItem with parameter $name.

Now in ProductController you need to add an action:

```<code>//...
/**
 * Handle products by name
 * @param string $name
 */
public function actionItem($name) {
   // ... do stuff here
}
//...
</code>```

More information can be found here Yii2 Routing and URL Creation.

Title: Yii2 UrlManager rules

Body:
What would be the Urlmanager rule for changing a url like site/product?name=[name] to product/[name]?

I tried

'<action:\w+>' => 'site/<action>',
'product/<id:\d+>' => 'product',

But it gives me a 404

Body:
Before answering to your question a short explain what is wrong.
You try to pass alpha chars to an action that handles only integers.
The rule 'product/<id:\d+>' indicate that the url should be like:

product/1
product/777
product/8888

The regular expression \d+ limits this url part to an integer.

Answer

For url like product/[name], you should add this pattern:

//...
'product/<name:[\w]+>' => 'product/item',
//...

Where 'product/<name:[\w]+>' will match any url like:

product/any
product/alpha
product/productname

The <name:[\w]+> will be the parameter that will hold matched url part and and creates a variable named $name that will contain only the alpha chars, due the regular expression [\w]+. This variable will be passed to controller action.

And 'product/item' is the controller / action that will handle request, in this example is ProductController and actionItem with parameter $name.

Now in ProductController you need to add an action:

//...
/**
 * Handle products by name
 * @param string $name
 */
public function actionItem($name) {
   // ... do stuff here
}
//...

More information can be found here Yii2 Routing and URL Creation.


问:
Android SDK file not found C:\Users\ASUS\AppData\Local\Android\sdk\platforms\android-29\android.jar
The output of

```<code> flutter doctor
</code>```

**

```<code>> Doctor summary (to see all details, run flutter doctor -v): [√]
> Flutter (Channel master, 2.1.0-13.0.pre.288, on Microsoft Windows
> [Version 10.0.19042.867], locale ) [!] Android toolchain - develop for
> Android devices (Android SDK version 29.0.2)
>     X Android SDK file not found: C:\Users\ASUS\AppData\Local\Android\sdk\platforms\android-29\android.jar.
> [√] Chrome - develop for the web [!] Visual Studio - develop for
> Windows (Visual Studio Community 2019 16.9.2)
>     X The current Visual Studio installation is incomplete. Please reinstall Visual Studio. [√] Android Studio (version 4.1.0) [√] VS
> Code (version 1.54.3) [√] Connected device (3 available
</code>```

**
Is there a solution to this problem?

答:
in order to solve the problem of android toolchain—> install the latest API from the SDK platforms in Settings.

If Android Toolchain showing the problem of 32, install Android API 32, if other version, install the one with that version.

Its probably the easiest way

Body:
The output of

 flutter doctor

**

> Doctor summary (to see all details, run flutter doctor -v): [√]
> Flutter (Channel master, 2.1.0-13.0.pre.288, on Microsoft Windows
> [Version 10.0.19042.867], locale ) [!] Android toolchain - develop for
> Android devices (Android SDK version 29.0.2)
>     X Android SDK file not found: C:\Users\ASUS\AppData\Local\Android\sdk\platforms\android-29\android.jar.
> [√] Chrome - develop for the web [!] Visual Studio - develop for
> Windows (Visual Studio Community 2019 16.9.2)
>     X The current Visual Studio installation is incomplete. Please reinstall Visual Studio. [√] Android Studio (version 4.1.0) [√] VS
> Code (version 1.54.3) [√] Connected device (3 available

**
Is there a solution to this problem?


问:
Can't display the values from my data base with Laravel Livewire
I'm using a Livewire component, this is my code:

Search.php :

```<code><?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Recipe;
use App\Models\Vegetable;
use App\Models\VegetablesRecipe;

class Search extends Component
{
    public $query = '';
    public $vegetables;

    public function mount()
    {
        $this->resetQuery();
    }

    public function resetQuery()
    {
        $this->vegetables = [];
    }

    public function render()
    {
        if ($this->query != null) {
            return view('livewire.search', [
                'vegetables' => Vegetable::where('name', 'like', '%'.$this->query.'%')->get()->toArray()
            ]);
        } else {
            return view('livewire.search', [
                'vegetables' => Vegetable::all()->toArray()
            ]);
        }
    }
}
</code>```

search.blade.php :

```<code><div class="searchcomponent">
    <h1>Search</h1>
    <input wire:model="query" type="text" placeholder="Rechercher...">

    @if(!empty($query))
        <ul>
            @if(!empty($vegetables))
                <div class="vegetables">

                    @foreach($vegetables as $vegetable)
                        <li><span class="material-icons">lunch_dining</span>{{ $vegetable['name'] }}</li>
                    @endforeach

                </div>
            @else
                <li>No result</li>
            @endif
       </ul>
    @endif
</div>
</code>```

My vegetable Model:

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Vegetable extends Model
{
    use HasFactory;

    public $timestamps = false;

    protected $fillable = ['name'];

    public function recipes(){
        return $this->belongsToMany(Recipe::class, 'vegetables_recipes', 'vegetable_id', 'recipe_id');
    }

    public function getName($id) {
        return $this->name;
    }
}
</code>```

My problem is, every time im typing something in my search bar, I just have a No result appearing on my screen even tho i seeded my data base with some vegetables already. Why doesn't it show me for example Carrot when i type it?
Or how can i fill my array vegetables with all the names of my vegetables datatable ?

答:
Also, you can remove the @if(!empty($query)) and the @if(!empty($vegetables)) in place of a @forelse utilising the @empty statement rather than a @foreach. E.g.

```<code>@forelse($vegetables as $vegetable)
    <li><span class="material-icons">lunch_dining</span>{{ $vegetable['name'] }}</li>
@empty
    <li>No result</li>
@endforelse
</code>```

That way, you will still get a list of your vegetables when the search box is empty, and if it's not empty but there's no matching results, you'll get your "No result" message.

Body:
I'm using a Livewire component, this is my code:

Search.php :

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Recipe;
use App\Models\Vegetable;
use App\Models\VegetablesRecipe;

class Search extends Component
{
    public $query = '';
    public $vegetables;

    public function mount()
    {
        $this->resetQuery();
    }

    public function resetQuery()
    {
        $this->vegetables = [];
    }

    public function render()
    {
        if ($this->query != null) {
            return view('livewire.search', [
                'vegetables' => Vegetable::where('name', 'like', '%'.$this->query.'%')->get()->toArray()
            ]);
        } else {
            return view('livewire.search', [
                'vegetables' => Vegetable::all()->toArray()
            ]);
        }
    }
}

search.blade.php :

Search

    <input wire:model="query" type="text" placeholder="Rechercher...">

    @if(!empty($query))

            @if(!empty($vegetables))

                    @foreach($vegetables as $vegetable)

lunch_dining{{ $vegetable['name'] }}

                    @endforeach

            @else

No result

            @endif

    @endif

My vegetable Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Vegetable extends Model
{
    use HasFactory;

    public $timestamps = false;

    protected $fillable = ['name'];

    public function recipes(){
        return $this->belongsToMany(Recipe::class, 'vegetables_recipes', 'vegetable_id', 'recipe_id');
    }

    public function getName($id) {
        return $this->name;
    }
}

My problem is, every time im typing something in my search bar, I just have a No result appearing on my screen even tho i seeded my data base with some vegetables already. Why doesn't it show me for example Carrot when i type it?
Or how can i fill my array vegetables with all the names of my vegetables datatable ?

Body:
Also, you can remove the @if(!empty($query)) and the @if(!empty($vegetables)) in place of a @forelse utilising the @empty statement rather than a @foreach. E.g.

@forelse($vegetables as $vegetable)
    <li><span class="material-icons">lunch_dining</span>{{ $vegetable['name'] }}</li>
@empty
    <li>No result</li>
@endforelse

That way, you will still get a list of your vegetables when the search box is empty, and if it's not empty but there's no matching results, you'll get your "No result" message.


问:
How can I undo discard changes in GitHub Desktop?
Is there any way to undo discard changes in GitHub Desktop, after the Undo button has disappeared?

I am talking about GitHub Desktop's undo feature, not git in general.

答: I got he same situation, just went to the Bin and the files were there. Just needed to replace the code manually again. My machine: Mac.</p>


问:
Take URL to open larger map from iFrame?
I want to get a link to open a larger map from the iFrame URL:

```<code><iframe
src='https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d414225.88930329087!2d14.068999827954114!3d46.99590051638977!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x47707345308f7e65%3A0x687eb6df8c618d2b!2sKlagenfurt%2C%20Austria!5e0!3m2!1sen!2srs!4v1643793775072!5m2!1sen!2srs'
style='border:0;' allowfullscreen='' loading='lazy'></iframe>

</code>```

This URL from iframe to open in a new tab is invalid :

```<code>https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d414225.88930329087!2d14.068999827954114!3d46.99590051638977!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x47707345308f7e65%3A0x687eb6df8c618d2b!2sKlagenfurt%2C%20Austria!5e0!3m2!1sen!2srs!4v1643793775072!5m2!1sen!2srs
</code>```

I tried to take the URL from iFrame :

But in website mounting time, JS cannot read iFrame DOM... Any suggestions?

答:
The right solution is to use the Google Maps API. However, if you need to parse data from this URL, it is possible. URL contains lat and lng so you can (somehow) recreate target URL. The subsequent solution is only a rough example and is not production ready:

const url = 'https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d414225.88930329087!2d14.068999827954114!3d46.99590051638977!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x47707345308f7e65%3A0x687eb6df8c618d2b!2sKlagenfurt%2C%20Austria!5e0!3m2!1sen!2srs!4v1643793775072!5m2!1sen!2srs';
const partOne = url.split('2d');
const partTwo = partOne[1].split('!3d');
const partThree = partTwo[1].split('!');
const lng = partTwo[0];
const latAndZ = partTwo[1].split('!')[0];
const z = latAndZ[latAndZ.length - 1]
const lat = latAndZ.slice(0,-1);
const result = `https://www.google.com/maps/@${lat},${lng},${z}z`;
console.log(result);```

Body:
I want to get a link to open a larger map from the iFrame URL:

This URL from iframe to open in a new tab is invalid :

https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d414225.88930329087!2d14.068999827954114!3d46.99590051638977!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x47707345308f7e65%3A0x687eb6df8c618d2b!2sKlagenfurt%2C%20Austria!5e0!3m2!1sen!2srs!4v1643793775072!5m2!1sen!2srs

I tried to take the URL from iFrame :

But in website mounting time, JS cannot read iFrame DOM... Any suggestions?


问:
flutter app is crashing on iOS with AppBar
my app is working fine on android but for ios its crashing ,
if i comment the AppBar , its working in ios, but with app its not working.

appBar: AppBar(), // here is the problem

```<code> @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(), // here is the problem
      backgroundColor: Colors.black,
      body: SafeArea(
</code>```

main.dart code,

```<code> @override
  Widget build(BuildContext context) {
    pushNotificationMessage();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    return MultiProvider(
      providers: [
        ChangeNotifierProvider<AppData>(create: (_) => AppData()),
      ],
      child: GetMaterialApp(
        title: 'ABC App',
        debugShowCheckedModeBanner: false,
</code>```

答:
I think your issue here is Appbar conflicting with the non safe area in your iOS device (upper notch for example), so you can fix that by one of two ways:

First way(encouraged), you can wrap your scaffold itself in the SafeArea widget instead of the body of the scaffold:

```<code> @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return SafeArea(
      Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(), // here is the problem
      backgroundColor: Colors.black,
      body: Container(
</code>```

Second way, you can remove AppBar() from the scaffold and add it inside your body widget, for example:

```<code> @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      key: _scaffoldKey,
      backgroundColor: Colors.black,
      body: SafeArea(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Container(
                  margin: const EdgeInsets.only(bottom: 30), child: AppBar()),
</code>```

Body:
my app is working fine on android but for ios its crashing ,
if i comment the AppBar , its working in ios, but with app its not working.

appBar: AppBar(), // here is the problem

 @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(), // here is the problem
      backgroundColor: Colors.black,
      body: SafeArea(

main.dart code,

 @override
  Widget build(BuildContext context) {
    pushNotificationMessage();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    return MultiProvider(
      providers: [
        ChangeNotifierProvider<AppData>(create: (_) => AppData()),
      ],
      child: GetMaterialApp(
        title: 'ABC App',
        debugShowCheckedModeBanner: false,

Body:
I think your issue here is Appbar conflicting with the non safe area in your iOS device (upper notch for example), so you can fix that by one of two ways:

First way(encouraged), you can wrap your scaffold itself in the SafeArea widget instead of the body of the scaffold:

 @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return SafeArea(
      Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(), // here is the problem
      backgroundColor: Colors.black,
      body: Container(

Second way, you can remove AppBar() from the scaffold and add it inside your body widget, for example:

 @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      key: _scaffoldKey,
      backgroundColor: Colors.black,
      body: SafeArea(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Container(
                  margin: const EdgeInsets.only(bottom: 30), child: AppBar()),


问:
htaccess show holding page
Hi I want to show a holding page to outside users but from my machine gain access to the site. Can I do this with htaccess?</p>

答:
```<code>RewriteEngine On
RewriteCond !REMOTE_ADDR=127.0.0.1
RewriteRule .* /holdingPage.html [R,L]
</code>```

Replace 127.0.0.1 with your machine's IP.

http://httpd.apache.org/docs/2.2/howto/access.html

http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html

OwnerDisplayName: Ben Robinson

ContentLicense: CC BY-SA 2.5

Title: htaccess show holding page

Body:
RewriteEngine On
RewriteCond !REMOTE_ADDR=127.0.0.1
RewriteRule .* /holdingPage.html [R,L]

Replace 127.0.0.1 with your machine's IP.

http://httpd.apache.org/docs/2.2/howto/access.html

http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html

OwnerDisplayName: vartec

LastEditorDisplayName: vartec


问:
Is the non-intrusive claimed by the framework a false proposition
No matter what the language direction, generally speaking, a framework is too intrusive, which is a voice of criticism, so I guess it is not because of this that non-intrusive has become a "selling point" of publicity.

For example, spring and struts 2 use annotations, configuration files, conventions or reflection (other languages may be other ways) to achieve non-invasive, and the compilation and operation does not have formal dependence on the framework API.

But in essence, without this framework, our program simply cannot run correctly. These so-called annotations are customized. When and how they are processed are different. Think about the migration from gson to Jackson. The migration has costs and risks. Do you need users to write a new one?

In addition, how high is the probability of real migration? It feels very small.

答:
I think your question is very interesting but a little subjective..

My thought is that we must be build applications that are robust to changes, but remain pragmatic. We need to find the good point between abstraction and implementation (as described in the Clean Architecture book).

In the Java eco-system, The standard JSRs is very often defined around interfaces and  not implementations, offering you a good way to avoid tight coupling to a specific framework (ex: JPA instead of Hibernate, JAX-RS instead of Jackson..).

In the Spring ecosystem, you can use these standards annotation (@Inject vs @Autowired), and it will work perfectly, but you will often loose some functionalities offered by the implementations.

Some architectures tends to separate totally the layers between your business code and the framework code (the hexagonal architecture call it the infrastructure and application layers), but it comes at a price..

The probability of this type of migration is unknown and depends on the changing needs of your project (I've never encountered a change of JPA vendor implementation). But I believe that with the most active project (Hibernate, Jackson..), you can try to reduce it.

So... Be pragmatic :)


问:
Modify char* in GDB while debugging
While I debug with GDB I can print string:

```<code>x/s $r0
</code>```

The output is

```<code>IDog123456
</code>```

I want to change the value so when I print x/s $r0 I will see

```<code>ICat45555
</code>```

I have tried to :

```<code>set $r0+1 ={int} 0x43617434 #Cat4
set $r0+5 ={int} 0x35353535 #5555
</code>```

But it doesn't work , How can I do that without malloc ? only with hex string please?

答:
Generally, the gdb expression parser operates similar to the current language, so, in the above, when you write:

```<code>set $r0+1 ={int} 0x43617434 #Cat4
</code>```

The left hand side is an integer constant, which can't be assigned to.

Instead, you should write this as you would in C:

```<code>set *($r0+1) = (int) 0x43617434
</code>```

Which should do the job.

Sometime, you might end up needing to cast the pointer of the LHS too, like this:

```<code>set *((int *) ($r0+1)) = (int) 0x43617434
</code>```

But I suspect in your case you'll be OK.

Title: Modify char* in GDB while debugging

Body:
While I debug with GDB I can print string:

x/s $r0

The output is

IDog123456

I want to change the value so when I print x/s $r0 I will see

ICat45555

I have tried to :

set $r0+1 ={int} 0x43617434 #Cat4
set $r0+5 ={int} 0x35353535 #5555

But it doesn't work , How can I do that without malloc ? only with hex string please?

Body:
Generally, the gdb expression parser operates similar to the current language, so, in the above, when you write:

set $r0+1 ={int} 0x43617434 #Cat4

The left hand side is an integer constant, which can't be assigned to.

Instead, you should write this as you would in C:

set *($r0+1) = (int) 0x43617434

Which should do the job.

Sometime, you might end up needing to cast the pointer of the LHS too, like this:

set *((int *) ($r0+1)) = (int) 0x43617434

But I suspect in your case you'll be OK.


问:
Updating label with UIProgressView progress
I am using the ASIHTTPRequest Queue in a seperate class file from my main view to download multiple files from my web server. I have set an UIProgressView as the download progress delegate as follows:

```<code>UIProgressView *myProgressView = [[UIProgressView alloc] init];
[myQueue setDownloadProgressDelegate:myProgressView];
</code>```

I can then successfully NSLog the progress in the requestFinished method by using:

```<code>NSLog(@"Progress: %f", [myProgressView progress]);
</code>```

All works fine and am able to see the correct amounts displayed in the log.

What I want to be able to do is update my label text on the main view but can't seem to figure out to do this.....another words, how to pass the progress in real time to another view/class for updating the label text.

Any pointers in the right direction would be greatly appreciated!

Thanks!

答:
In your delegate class set a property which is a reference pointer back to the main class (make it an assign property).

```<code>MyMainView *myMainView
@property (nonatomic, assign) MyMainView *myMainView
</code>```

At the time you create the ASIHTTPRequestQueue and set its delegate, also set the myMainView property on the delegate.

On your main view class add a method, e.g.

```<code>-(void) updateProgress:(double) progress {
    // code to update the label text
}
</code>```

In your delegate method (i.e. where you currently log the progress):

```<code>[self.myMainView updateProgress:[progressView progress]];
</code>```

Body:
I am using the ASIHTTPRequest Queue in a seperate class file from my main view to download multiple files from my web server. I have set an UIProgressView as the download progress delegate as follows:

UIProgressView *myProgressView = [[UIProgressView alloc] init];
[myQueue setDownloadProgressDelegate:myProgressView];

I can then successfully NSLog the progress in the requestFinished method by using:

NSLog(@"Progress: %f", [myProgressView progress]);

All works fine and am able to see the correct amounts displayed in the log.

What I want to be able to do is update my label text on the main view but can't seem to figure out to do this.....another words, how to pass the progress in real time to another view/class for updating the label text.

Any pointers in the right direction would be greatly appreciated!

Thanks!

Body:
In your delegate class set a property which is a reference pointer back to the main class (make it an assign property).

MyMainView *myMainView
@property (nonatomic, assign) MyMainView *myMainView

At the time you create the ASIHTTPRequestQueue and set its delegate, also set the myMainView property on the delegate.

On your main view class add a method, e.g.

-(void) updateProgress:(double) progress {
    // code to update the label text
}

In your delegate method (i.e. where you currently log the progress):

[self.myMainView updateProgress:[progressView progress]];


问:
Measure actual clock speed via powershell during an intensive task
I have the following script to measure the current cpu clock rate from this [link][1].

```<code>$MaxClockSpeed = (Get-CimInstance CIM_Processor).MaxClockSpeed
$ProcessorPerformance = (Get-Counter -Counter "\Processor Information(_Total)\% Processor Performance").CounterSamples.CookedValue
$CurrentClockSpeed = $MaxClockSpeed*($ProcessorPerformance/100)
</code>```

I am looking to test the performance of the CPU to see how far it can go in terms of frequency.

The reason for this is that we have a few machines that are faulty out of our hundreds of machines, and it turns out that when you push them a bit, their clock rate doesn't change and stays at around 20% utilization. This would allow us, via our monitoring system, to find them easily.

Is there a way to programmatically via powershell to make an intensive task during or just before capturing the actual clock speed to know how far it can get? Something like a loop or something?
[1]: Unable to get current CPU frequency in Powershell or Python

答:
I found something interesting on this website.
So to make the cpu work at 100% for a short time, I can use a background job:

```<code>$NumberOfLogicalProcessors = Get-WmiObject win32_processor | Select-Object -ExpandProperty NumberOfLogicalProcessors

ForEach ($core in 1..$NumberOfLogicalProcessors){

start-job -ScriptBlock{

    $result = 1;
    foreach ($loopnumber in 1..2147483647){
        $result=1;

        foreach ($loopnumber1 in 1..2147483647){
        $result=1;

            foreach($number in 1..2147483647){
                $result = $result * $number
            }
        }

            $result
        }
    }
}

Read-Host "Press any key to exit..."
Stop-Job *
</code>```

It makes the cpu go usually at 100% of utilization. During that time I can easily run the script:

```<code>$MaxClockSpeed = (Get-CimInstance CIM_Processor).MaxClockSpeed
$ProcessorPerformance = (Get-Counter -Counter "\Processor Information(_Total)\% Processor Performance").CounterSamples.CookedValue
$CurrentClockSpeed = $MaxClockSpeed*($ProcessorPerformance/100)
</code>```

For instance, in my case, when I test the $processorPerformance I get "107.998029830411" as an example, so this shows My processor works fine when I push it.

N.B I must add the Start-sleep -Seconds 20 parameter while the background tasks are running, because on all the machines it takes around 15 seconds until the x logical processors are running at 100%.

Body:
I have the following script to measure the current cpu clock rate from this [link][1].

$MaxClockSpeed = (Get-CimInstance CIM_Processor).MaxClockSpeed
$ProcessorPerformance = (Get-Counter -Counter "\Processor Information(_Total)\% Processor Performance").CounterSamples.CookedValue
$CurrentClockSpeed = $MaxClockSpeed*($ProcessorPerformance/100)

I am looking to test the performance of the CPU to see how far it can go in terms of frequency.

The reason for this is that we have a few machines that are faulty out of our hundreds of machines, and it turns out that when you push them a bit, their clock rate doesn't change and stays at around 20% utilization. This would allow us, via our monitoring system, to find them easily.

Is there a way to programmatically via powershell to make an intensive task during or just before capturing the actual clock speed to know how far it can get? Something like a loop or something?
[1]: Unable to get current CPU frequency in Powershell or Python

Body:
I found something interesting on this website.
So to make the cpu work at 100% for a short time, I can use a background job:

$NumberOfLogicalProcessors = Get-WmiObject win32_processor | Select-Object -ExpandProperty NumberOfLogicalProcessors

ForEach ($core in 1..$NumberOfLogicalProcessors){

start-job -ScriptBlock{

    $result = 1;
    foreach ($loopnumber in 1..2147483647){
        $result=1;

        foreach ($loopnumber1 in 1..2147483647){
        $result=1;

            foreach($number in 1..2147483647){
                $result = $result * $number
            }
        }

            $result
        }
    }
}

Read-Host "Press any key to exit..."
Stop-Job *

It makes the cpu go usually at 100% of utilization. During that time I can easily run the script:

$MaxClockSpeed = (Get-CimInstance CIM_Processor).MaxClockSpeed
$ProcessorPerformance = (Get-Counter -Counter "\Processor Information(_Total)\% Processor Performance").CounterSamples.CookedValue
$CurrentClockSpeed = $MaxClockSpeed*($ProcessorPerformance/100)

For instance, in my case, when I test the $processorPerformance I get "107.998029830411" as an example, so this shows My processor works fine when I push it.

N.B I must add the Start-sleep -Seconds 20 parameter while the background tasks are running, because on all the machines it takes around 15 seconds until the x logical processors are running at 100%.


答:
You are trying to bind an onCompleteHandler handler, but the variable you're providing does not reference a function. Rather, it is undefined. Remove it, and you'll be OK.

http://jsfiddle.net/XNXj3/

Title: jQuery Validation using third party plugin

Body:
<!DOCTYPE html>

    <title>Site :: </title>
    <link rel="stylesheet" media="screen" href="css/wicahost.css" />
    <link rel="stylesheet" media="screen" href="css/global.css" />

Signup!

    <form id="splashtease" action="inc/subscribe.php" method="post">
    <?php $usrBrowser = $_SERVER['HTTP_USER_AGENT']; $todayDt = date('Y-m-d');  ?>
    <input type="text" name="emAdd" />
            <input type="hidden" name="brwsr" value="<?php echo $usrBrowser ?>" />
            <input type="hidden" name="dt" value="<?php echo $todayDt ?>" />
        <input type="submit" name="submit" value="" class="splashteasesub" />
    </form>

Trying to implement this simple example above to validate an email address:
http://www.benjaminkeen.com/software/rsv/jquery/demo.php

The above code isn't doing anything and is just submitting to the database. I checked to make sure my jquery library link reference and jquery script for this 3rd party script to make sure they linked fine and both do link fine.

Anyone see what is going wrong here? Thanks :)


问:
How to write a python function to return True when there's even number of 0 in a integer and return False otherwise using recursion?
I am asked to write a function that returns True if there's even number of 0 digits in a positive integer and return False otherwise (using recursion). As an attempt, I have written a function that counts the number of 0 in an integer. May I know how can I modify the program so that it will return True and False?</p>
```<code>def valid(n):
    number = str(n)
    position = number.find("0")

    if "0" not in number:
        return 0

    return 1 + valid(number[(position+1):])

print(valid(12340006))

</code>```

答:
You have a number, don't convert to string but rather use divmod and division by 10:

```<code>def valid(num, count=0):
    num, r = divmod(num, 10) # extract the last digit (r)
    if num == 0:             # we exhausted the number
        return count%2==0    # is there an even number of zeros?
    else:
        return valid(num, count=count+int(r==0))
</code>```

handling 0 -> False:

```<code>def valid(num, count=None):
    if count is None:
        count = int(num==0)
    num, r = divmod(num, 10)
    if num == 0:
        return count%2==0
    else:
        return valid(num, count=count+int(r==0))
</code>```

Example:

```<code>>>> valid(12340006)
False

>>> valid(10203)
True

>>> valid(0)
False
</code>```

Body:
I am asked to write a function that returns True if there's even number of 0 digits in a positive integer and return False otherwise (using recursion). As an attempt, I have written a function that counts the number of 0 in an integer. May I know how can I modify the program so that it will return True and False?

def valid(n):
    number = str(n)
    position = number.find("0")

    if "0" not in number:
        return 0

    return 1 + valid(number[(position+1):])

print(valid(12340006))

Body:
You have a number, don't convert to string but rather use divmod and division by 10:

def valid(num, count=0):
    num, r = divmod(num, 10) # extract the last digit (r)
    if num == 0:             # we exhausted the number
        return count%2==0    # is there an even number of zeros?
    else:
        return valid(num, count=count+int(r==0))

handling 0 -> False:

def valid(num, count=None):
    if count is None:
        count = int(num==0)
    num, r = divmod(num, 10)
    if num == 0:
        return count%2==0
    else:
        return valid(num, count=count+int(r==0))

Example:

>>> valid(12340006)
False

>>> valid(10203)
True

>>> valid(0)
False


问:
Identity equality for arguments of types Int and Int is deprecated
Just fyi, this is my first question on StackOverflow and I'm really new in Kotlin.

While working on a project that's fully Kotlin (ver 1.1.3-2), I see a warning on the following code (with the comments for you curious lads):

```<code>    // Code below is to handle presses of Volume up or Volume down.
    // Without this, after pressing volume buttons, the navigation bar will
    // show up and won't hide
    val decorView = window.decorView
    decorView
        .setOnSystemUiVisibilityChangeListener { visibility ->
            if (visibility and View.SYSTEM_UI_FLAG_FULLSCREEN === 0) {
                 decorView.systemUiVisibility = flags
            }
        }
</code>```

The warning is for visibility and View.SYSTEM_UI_FLAG_FULLSCREEN === 0, and it says Identity equality for arguments of types Int and Int is deprecated.

How should I change the code and why was it deprecated in the first place (for knowledge's sake)?

答:
For type Int the referential equality === (this is used if left and right part are pointing to the same object) is equal to ==

Refer to https://kotlinlang.org/docs/equality.html#referential-equality for more information on this.

Body:
Just fyi, this is my first question on StackOverflow and I'm really new in Kotlin.

While working on a project that's fully Kotlin (ver 1.1.3-2), I see a warning on the following code (with the comments for you curious lads):

    // Code below is to handle presses of Volume up or Volume down.
    // Without this, after pressing volume buttons, the navigation bar will
    // show up and won't hide
    val decorView = window.decorView
    decorView
        .setOnSystemUiVisibilityChangeListener { visibility ->
            if (visibility and View.SYSTEM_UI_FLAG_FULLSCREEN === 0) {
                 decorView.systemUiVisibility = flags
            }
        }

The warning is for visibility and View.SYSTEM_UI_FLAG_FULLSCREEN === 0, and it says Identity equality for arguments of types Int and Int is deprecated.

How should I change the code and why was it deprecated in the first place (for knowledge's sake)?


问:
Visual Studio Help - The "RunCommand" property is not defined
I'm using Microsoft Visual Studio Community 2017. I have created a project with multiple classes to be compiled. The primary class I want the application to run first has public static void Main(string[] args) in it already. In the library, I've set properties to the following:

Target Framework: .NET standard 2.0

Output type: Console Application

Startup object: Main.Game

Still, the error persists with all the forums I have visited.
If you have encountered this problem, please guide me through so I can compile my program. Thank you :)

答:
From here

Try adding the following to you <PropertyGroup>:

```<code><AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<RunCommand>$(MSBuildExtensionsPath64)\..\IIS Express\iisexpress</RunCommand>
<RunArguments>/path:"$(MSBuildProjectDirectory)" /port:18082</RunArguments>
</code>```

Body:
From here

Try adding the following to you <PropertyGroup>:

<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<RunCommand>$(MSBuildExtensionsPath64)\..\IIS Express\iisexpress</RunCommand>
<RunArguments>/path:&quot;$(MSBuildProjectDirectory)&quot; /port:18082</RunArguments>


问:
Nested append in javascript
I want to wrap both select and button under one div
. I have the below code working but unable to wrap it. I can't put
 in static HTML and append it.  Structure should be -

```<code><div id="container" class="row">
<div class="row">

<select id="SelColid0" name="SelColid0">
</select>

<select id="nameid0" name="nameid0">
</select>

<button id="clearid0" title="Clear Filter">
<i class="far fa-trash-alt"></i>
</button>

</div>
</div>
</code>```

$('#container')
      .append(
        $(document.createElement('select')).prop({
          id: "SelColid0",
          name: "SelColid0"
        })
      )
      .append(
        $(document.createElement('select')).prop({
          id: "nameid0",
          name: "nameid0"
        })
      )
      .append(
        $(document.createElement('button')).prop({
          id: "clearid0",
          innerHTML: '',
          title : 'Clear Filter'
        })
      )
    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>

 <div id="container" class= "row"></div></code>```

Select Column
name

Select Value

答:
I think it's better use only jQuery or only js, in your case seems like you want use jQuery:

$('#container')
  .append(
    $('

').addClass("row")
    .append(
      $('<select></select>').prop({
        id: "SelColid0",
        name: "SelColid0"
      })
    )
    .append(
      $('<select></select>').prop({
        id: "nameid0",
        name: "nameid0"
      })
    )
    .append(
      $('<button></button>').prop({
        id: "clearid0",
        innerHTML: '',
        title: 'Clear Filter'
      })
    )
  )```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" integrity="sha512-Fo3rlrZj/k7ujTnHg4CGR2D7kSs0v4LLanw2qksYuRlEzO+tcaEPQogQ0KaoGN26/zrn20ImR1DfuLWnOo7aBA==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<div id="container" class="row"></div></code>```

So instead of use document.createElement use directly $('whatyouneed')

If instead you wanted to use only pure JS:

const container = document.querySelector('#container');
const div = document.createElement('div');
div.classList.add('row');
let select1 = document.createElement('select');
select1.id = 'SelColid0';
select1.name = 'SelColid0';
div.append(select1);
let select2 = document.createElement('select');
select2.id = 'nameid0';
select2.name = 'nameid0';
div.append(select2);
let button = document.createElement('button');
button.id = 'clearid0';
button.innerHTML = '';
button.title = 'Clear Filter';
div.append(button);
container.append(div);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" integrity="sha512-Fo3rlrZj/k7ujTnHg4CGR2D7kSs0v4LLanw2qksYuRlEzO+tcaEPQogQ0KaoGN26/zrn20ImR1DfuLWnOo7aBA==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>

<div id="container" class="row"></div></code>```

Title: Nested append in javascript

Body:
I want to wrap both select and button under one div
. I have the below code working but unable to wrap it. I can't put
 in static HTML and append it.  Structure should be -

<select id="SelColid0" name="SelColid0">
</select>

<select id="nameid0" name="nameid0">
</select>

<button id="clearid0" title="Clear Filter">

</button>

$('#container')
      .append(
        $(document.createElement('select')).prop({
          id: "SelColid0",
          name: "SelColid0"
        })
      )
      .append(
        $(document.createElement('select')).prop({
          id: "nameid0",
          name: "nameid0"
        })
      )
      .append(
        $(document.createElement('button')).prop({
          id: "clearid0",
          innerHTML: '',
          title : 'Clear Filter'
        })
      )

Select Column
name

Select Value

Body:
I think it's better use only jQuery or only js, in your case seems like you want use jQuery:

$('#container')
  .append(
    $('<div></div>').addClass("row")
    .append(
      $('<select></select>').prop({
        id: "SelColid0",
        name: "SelColid0"
      })
    )
    .append(
      $('<select></select>').prop({
        id: "nameid0",
        name: "nameid0"
      })
    )
    .append(
      $('<button></button>').prop({
        id: "clearid0",
        innerHTML: '<i class="far fa-trash-alt"></i>',
        title: 'Clear Filter'
      })
    )
  )

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" integrity="sha512-Fo3rlrZj/k7ujTnHg4CGR2D7kSs0v4LLanw2qksYuRlEzO+tcaEPQogQ0KaoGN26/zrn20ImR1DfuLWnOo7aBA==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<div id="container" class="row"></div>

So instead of use document.createElement use directly $('whatyouneed')

If instead you wanted to use only pure JS:

const container = document.querySelector('#container');
const div = document.createElement('div');
div.classList.add('row');
let select1 = document.createElement('select');
select1.id = 'SelColid0';
select1.name = 'SelColid0';
div.append(select1);
let select2 = document.createElement('select');
select2.id = 'nameid0';
select2.name = 'nameid0';
div.append(select2);
let button = document.createElement('button');
button.id = 'clearid0';
button.innerHTML = '<i class="far fa-trash-alt"></i>';
button.title = 'Clear Filter';
div.append(button);
container.append(div);

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" integrity="sha512-Fo3rlrZj/k7ujTnHg4CGR2D7kSs0v4LLanw2qksYuRlEzO+tcaEPQogQ0KaoGN26/zrn20ImR1DfuLWnOo7aBA==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>

<div id="container" class="row"></div>


问:
HTML Email table borders in iPhone and iPad only
I'm making an HTML email and when viewed in iPhone or iPad thin borders appear around cells that contain just HTML content (cells that aren't populated with an image). Any idea how I can get rid of these borders?</p>

答:
I have just come across the same issue and I found a fix but using css - if you have a background color within your email which I assume you do since you are seeing the borders you need to add a extra containing table and set the background color to the "body" color then the inner table will be your content background color

Hope this helps :-)


问:
Is display property (e.g. flex or block) needed when element length and width have been set beforehand?
Since setting the length and width size have permanently set the element size, adding display:flex or display:block is not needed, isn't it?

答:
Depends what you mean actually.

The display property is usually affecting the children elements.
When you use display, it modifies the behavior of the children elements and sometimes their width (e.g. display: flex will make the width of the children 100%). But it's overwritten if you set a specific width.

More infos on the display property here : https://developer.mozilla.org/en-US/docs/Web/CSS/display


问:
Customize Vaadin Details Expand Icon by overriding default css applied on it
I want expand/ unexpand feature and I use Vaadin Details for it.

```<code>Div contentDiv = new Div();

Label label = new Label("Expand");

Details details = new Details(label, contentDiv);
</code>```

What it gives is following output:

But, what I want is the expand icon in right side. So for this I use ThemeVariants like this:

```<code>details.addThemeVariants(DetailsVariant.REVERSE);
</code>```

What it gives is the following output:

There is huge gap between the text and Icon.

This is because of the below default css applied on it.

```<code>:host([theme~="reverse"]) [part="summary"] {
    justify-content: space-between;
}
</code>```

So, Now I need to override this css. And what I have done is added below css code in my css file and added themeFor="summary" in import. But it did not work.

```<code>:host([theme~="reverse"]) [part="summary"] {
            justify-content: normal;
        }
</code>```

Expected Output:

So, is there any other way to do this in Vaadin? Or how can I override the default css of ThemeVariants.

Note: I am using Vaadin 14.

答:
Use themeFor="vaadin-details" instead of themeFor="summary" and it should work.

Also, use justify-content: start;. There’s no normal value for that property: https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content

Body:
I want expand/ unexpand feature and I use Vaadin Details for it.

Div contentDiv = new Div();

Label label = new Label("Expand");

Details details = new Details(label, contentDiv);

What it gives is following output:

But, what I want is the expand icon in right side. So for this I use ThemeVariants like this:

details.addThemeVariants(DetailsVariant.REVERSE);

What it gives is the following output:

There is huge gap between the text and Icon.

This is because of the below default css applied on it.

:host([theme~="reverse"]) [part="summary"] {
    justify-content: space-between;
}

So, Now I need to override this css. And what I have done is added below css code in my css file and added themeFor="summary" in import. But it did not work.

:host([theme~="reverse"]) [part="summary"] {
            justify-content: normal;
        }

Expected Output:

So, is there any other way to do this in Vaadin? Or how can I override the default css of ThemeVariants.

Note: I am using Vaadin 14.


问:
How to make flutter web size like app size
I am developing a flutter app and try to run it on web too. How do you make the size of a web app like a phone app? I saw some web app has the fixed size of phone app like following;https://i.stack.imgur.com/2J36E.jpg</p>

答:
I developed a flutter package to handle this for you: https://pub.dev/packages/center_the_widgets

You can use it just like this:

```<code> return CenterTheWidgets(
      child: Scaffold(
        body: const Text('Hi!'),
      ),
    );
</code>```

Body:
I developed a flutter package to handle this for you: https://pub.dev/packages/center_the_widgets

You can use it just like this:

 return CenterTheWidgets(
      child: Scaffold(
        body: const Text('Hi!'),
      ),
    );


问:
Load new pages via Ajax without refreshing the whole nav bar Django
I'm new to Django and I'm building my own website. I have written a base.html page that contains the main body, CSS, js, fonts, and the navbar that all the pages of my site will have. The navbar is on another HTML file, navbar.html

Now, as soon as the CSS/js/fonts/navbar included in the base.html will be loaded on every page and won't change, is there a way with Ajax to load only the actual content of the page that change seamless without seeing the whole page refresh?

For instance, the part of the page that visually changes everytime is inside a

 tag

答:
When using JQuery, it is quite simple:

```<code><script>
   function load_page(url) {
      $.ajax({
         url: url,
         success: function (data) {
            $('#nav_id').html('');
            data.nav_items.forEach(item => {
               $('#nav_id').append($('<div>').onclick(load_page(item.url)).text(item.title));
            }
         },
         error: function () {
            alert('Could not load data');
         }
      });
   }
</script>
</code>```

And in your url you can define this as /nav/str:slug/ which leads to a view like this:

```<code>def nav_ajax(request, slug):
   if slug == 'a':
       return JsonResponse({
          'navitem1': {
              'title': 'A',
              'url': reverse('your_nav_url_name', kwargs={'slug':'a'}),
       },
       # other menu items
       )
   else:
      return JsonResponse({}) # default menu items
</code>```

Body:
When using JQuery, it is quite simple:

<script>
   function load_page(url) {
      $.ajax({
         url: url,
         success: function (data) {
            $('#nav_id').html('');
            data.nav_items.forEach(item => {
               $('#nav_id').append($('<div>').onclick(load_page(item.url)).text(item.title));
            }
         },
         error: function () {
            alert('Could not load data');
         }
      });
   }
</script>

And in your url you can define this as /nav/str:slug/ which leads to a view like this:

def nav_ajax(request, slug):
   if slug == 'a':
       return JsonResponse({
          'navitem1': {
              'title': 'A',
              'url': reverse('your_nav_url_name', kwargs={'slug':'a'}),
       },
       # other menu items
       )
   else:
      return JsonResponse({}) # default menu items


问:
Embed a Powerpoint in a Web Page
Is there any way to embed a PowerPoint slide show in an HTML page using just the standard tags etc? I tried using a iframe, but that just results in the PowerPoint being downloaded.

```<code><iframe src="Chapter1.pptx">Your browser does not support.</iframe>
</code>```

I am looking for a way to show the slide show using only standard stuff. I realize I could use google docs or flash or something, but I'd rather have a simple implementation.

Does the web just not know how to process a PowerPoint presentation?

答:
I have decided to take a hack route and upload the powerpoint onto YouTube and then just include the youtube video in the iframe.

```<code><iframe height="375" width="600" src="http://www.youtube.com/embed/assignedId"></iframe>
</code>```

I know, it's cheap, but it's also easy.

EDIT

I eventually checked my page as XHTML Strict, which does not support the  tag. So I used the object tag instead.

```<code><object data="http://www.youtube.com/embed/assignedId">
</code>```

Title: Embed a Powerpoint in a Web Page

Body:
Is there any way to embed a PowerPoint slide show in an HTML page using just the standard tags etc? I tried using a iframe, but that just results in the PowerPoint being downloaded.

Your browser does not support.

I am looking for a way to show the slide show using only standard stuff. I realize I could use google docs or flash or something, but I'd rather have a simple implementation.

Does the web just not know how to process a PowerPoint presentation?

Body:
I have decided to take a hack route and upload the powerpoint onto YouTube and then just include the youtube video in the iframe.

<iframe height="375" width="600" src="http://www.youtube.com/embed/assignedId"></iframe>

I know, it's cheap, but it's also easy.

EDIT

I eventually checked my page as XHTML Strict, which does not support the <iframe> tag. So I used the object tag instead.

<object data="http://www.youtube.com/embed/assignedId">


问:
Replace same occurrence of word with different words using sed
I want to replace 2 same words in file(app.properties) with 2 different words using sed command.
Example:

```<code>mysql.host=<<CHANGE_ME>>
mysql.username=testuser
mysql.port=3306
mysql.db.password=<<CHANGE_ME>>
</code>```

required output will be

```<code>mysql.host=localhost
mysql.username=testuser
mysql.port=3306
mysql.db.password=password123
</code>```

I tried below command:

sed -e "s/<<CHANGE_ME>>/localhost/1" -e "s/<<CHANGE_ME>>/password123/2" app.properties > /home/centos/SCRIPT/io.properties_new

However I am getting localhost at both the places.

答:
This may be possible but I don't know if this is really readable for everyone.
Something like this might suite you :

sed -e '0,/<<CHANGE_ME>>/{s/<<CHANGE_ME>>/localhost/}' -e '1,/<<CHANGE_ME>>/{s/<<CHANGE_ME>>/password123/}' app.properties > /home/centos/SCRIPT/io.properties_new
```

If you have any idea to improve this, don't hesitate. I would really like to learn the best way to do this too :D

Body:
I want to replace 2 same words in file(app.properties) with 2 different words using sed command.
Example:

mysql.host=<<CHANGE_ME>>
mysql.username=testuser
mysql.port=3306
mysql.db.password=<<CHANGE_ME>>

required output will be

mysql.host=localhost
mysql.username=testuser
mysql.port=3306
mysql.db.password=password123

I tried below command:

sed -e "s/<<CHANGE_ME>>/localhost/1" -e "s/<<CHANGE_ME>>/password123/2" app.properties > /home/centos/SCRIPT/io.properties_new

However I am getting localhost at both the places.

Body:
This may be possible but I don't know if this is really readable for everyone.
Something like this might suite you :

sed -e '0,/<<CHANGE_ME>>/{s/<<CHANGE_ME>>/localhost/}' -e '1,/<<CHANGE_ME>>/{s/<<CHANGE_ME>>/password123/}' app.properties > /home/centos/SCRIPT/io.properties_new

If you have any idea to improve this, don't hesitate. I would really like to learn the best way to do this too :D


问:
How to prevent build for new branch creation in azure devops yaml
In Azure DevOps, created pipeline using Yaml file and mentioned "develop" under Triggers section. It is triggering for new commits in develop branch but also triggering for new branch creation based on "develop" branch which is not happening when I create a static pipeline. How can I prevent build for new branch. Any help here?</p>

答:
I think you should use the include / exclude filters like below :

# this is being defined in app-ci pipeline
resources:
  pipelines:
  - pipeline: securitylib
    source: security-lib-ci
    trigger:
      branches:
        include:
        - releases/*
        exclude:
        - releases/old*
```

Just check this page and you should find your answer : https://learn.microsoft.com/en-us/azure/devops/pipelines/process/pipeline-triggers?view=azure-devops

Regards

Body:
I think you should use the include / exclude filters like below :

# this is being defined in app-ci pipeline
resources:
  pipelines:
  - pipeline: securitylib
    source: security-lib-ci
    trigger:
      branches:
        include:
        - releases/*
        exclude:
        - releases/old*

Just check this page and you should find your answer : https://learn.microsoft.com/en-us/azure/devops/pipelines/process/pipeline-triggers?view=azure-devops

Regards


问:
SLF4J: Class path contains multiple SLF4J bindings during WSO2 IS startup
One of my WSO2 IS (Identity Server) went poof due to physical host error, and when I want to bring back up the IS service, it just hangs and won't start up right after these warning message:

SLF4J: Class path contains multiple SLF4J bindings.

SLF4J: Found binding in [bundleresource://539.fwk120694604:1/org/slf4j/impl/StaticLoggerBinder.class]

SLF4J: Found binding in [jar:file:/usr/lib64/wso2/wso2is/5.6.0/repository/deployment/server/webapps/api%23identity%23entitlement/WEB-INF/lib/slf4j-simple-1.6.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]

Aside of IS process hanging, there is no logs generated as well, so as per the warning messages said, there are conflicting logging classes for WSO2 IS, but I can't find this class whereabout:

bundleresource://539.fwk120694604:1/org/slf4j/impl/StaticLoggerBinder.class

My current WSO2 IS version is 5.6.0 and due to some restriction I can't upgrade the version and I don't think versioning is the issue here.

I had search all over the internet but mostly involve edit pom / maven kinda stuffs but WSO2 IS is supposed to be ready product right? Well, thus until now I still can't find any solution.

Can any kind soul help me with this issue?

Thank you.

答:
This is thrown as a warn in WSO2IS

```<code>SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [bundleresource://540.fwk1316864772:1/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/home/maneesha/WSO2/Stackoverflow/wso2is-5.6.0/wso2is-5.6.0/repository/deployment/server/webapps/api%23identity%23entitlement/WEB-INF/lib/slf4j-simple-1.6.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
</code>```

This happens because there is an SLF4J jar file in

<IS-HOME>/repository/components/plugins/slf4j.log4j12_1.6.1.jar

<IS-HOME>/repository/deployment/server/webapps/api#identity#entitlement/WEB-INF/lib/slf4j-simple-1.6.1.jar

both contain the StaticLoggerBinder.class this could have been avoided using dependency management while building the api#identity#entitlement.war file.

https://github.com/wso2/carbon-identity-framework/blob/ed3e0a150adb8363f2bbd7f91a249b66c069a992/components/entitlement/org.wso2.carbon.identity.entitlement.endpoint/pom.xml#L85

As you can see there is no scope provided, can use the below dependency management to make the SLF4J lib not to bundled into  api#identity#entitlement.war file

```<code><dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <scope>provided</scope>
</dependency>
</code>```

Body:
This is thrown as a warn in WSO2IS

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [bundleresource://540.fwk1316864772:1/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/home/maneesha/WSO2/Stackoverflow/wso2is-5.6.0/wso2is-5.6.0/repository/deployment/server/webapps/api%23identity%23entitlement/WEB-INF/lib/slf4j-simple-1.6.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]

This happens because there is an SLF4J jar file in

<IS-HOME>/repository/components/plugins/slf4j.log4j12_1.6.1.jar

<IS-HOME>/repository/deployment/server/webapps/api#identity#entitlement/WEB-INF/lib/slf4j-simple-1.6.1.jar

both contain the StaticLoggerBinder.class this could have been avoided using dependency management while building the api#identity#entitlement.war file.

https://github.com/wso2/carbon-identity-framework/blob/ed3e0a150adb8363f2bbd7f91a249b66c069a992/components/entitlement/org.wso2.carbon.identity.entitlement.endpoint/pom.xml#L85

As you can see there is no scope provided, can use the below dependency management to make the SLF4J lib not to bundled into  api#identity#entitlement.war file

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <scope>provided</scope>
</dependency>


问:
Redux reducer design for large state within a single module
I have come across two kinds of reducer design for handling a large state within a single module.
The first approach is to have all the variables inside a single large state and have one reducer function.

```<code>const initialState = {
   results: [],
   pagination: {},
   filters: [],
   appliedFilters = [],
}

const reducer = (st = { ...initialState }, action) => {
  const state = st;
  switch (action.type) {
     case 'SEARCH':{
         return {
           ...state,
           results: action.results,
           pagination: action.pagination,
           filters: action.filters,
           appliedFilters: action.appliedFilters
     },
     case 'APPLY_FILTER':{
         return {
           ...state,
           results: action.results,
           pagination: action.pagination,
           filters: action.filters,
           appliedFilters: action.appliedFilters
     },
     case 'PAGINATE':{
         return {
           ...state,
           results: action.results,
           pagination: action.pagination,
     }
}
</code>```

The second approach is to have multiple reducers for the sub items in the data.

```<code>export function applications(state = [], { type, results}) {
  switch (type) {
    case SEARCH:
      return results;
   case INIT_RESULTS:
      return [];
    default:
      return state;
  }
}

export function pagination(state = null, { type, paginationData }) {
  switch (type) {
    case SEARCH:
      return paginationData;
    default:
      return state;
  }
}

export function filters(state = [], { type, filterData }) {
  switch (type) {
    case SEARCH:
      return filterData;
    case UPDATE_FILTERS:
      return filterData;
    default:
      return state;
  }
}
</code>```

I think both have their own pros and cons. Considering scalability and modularization which one is a better pick?

答:
Generally, both of these are very far off our official recommendations.

you should have a "slice" reducer for each sub-state (that rules out your first option

you should not treat reducers as "setting a value", but move the whole "calculating how to get the value" into the reducer and handle your action as just "describing an event that happened"

you should be using the official Redux Toolkit which we are recommending & teaching as the default way of writing Redux sinde 2019. Seriously, look at it. It is about 1/4 of the code. No more switch..case reducers or ACTION_TYPES.

Please give the Redux Style Guide a read and to learn modern Redux with Redux Toolkit, please follow the official Redux Tutorial

Body:
I have come across two kinds of reducer design for handling a large state within a single module.
The first approach is to have all the variables inside a single large state and have one reducer function.

const initialState = {
   results: [],
   pagination: {},
   filters: [],
   appliedFilters = [],
}

const reducer = (st = { ...initialState }, action) => {
  const state = st;
  switch (action.type) {
     case 'SEARCH':{
         return {
           ...state,
           results: action.results,
           pagination: action.pagination,
           filters: action.filters,
           appliedFilters: action.appliedFilters
     },
     case 'APPLY_FILTER':{
         return {
           ...state,
           results: action.results,
           pagination: action.pagination,
           filters: action.filters,
           appliedFilters: action.appliedFilters
     },
     case 'PAGINATE':{
         return {
           ...state,
           results: action.results,
           pagination: action.pagination,
     }
}

The second approach is to have multiple reducers for the sub items in the data.

export function applications(state = [], { type, results}) {
  switch (type) {
    case SEARCH:
      return results;
   case INIT_RESULTS:
      return [];
    default:
      return state;
  }
}

export function pagination(state = null, { type, paginationData }) {
  switch (type) {
    case SEARCH:
      return paginationData;
    default:
      return state;
  }
}

export function filters(state = [], { type, filterData }) {
  switch (type) {
    case SEARCH:
      return filterData;
    case UPDATE_FILTERS:
      return filterData;
    default:
      return state;
  }
}

I think both have their own pros and cons. Considering scalability and modularization which one is a better pick?


问:
How do I add an svg icon to Material ui helper text generated by Formik and Yup
In my React form I am using Formik, Yup and Material ui form and textfield:

```<code>import { TextField } from '@material-ui/core';
</code>```

for my E-mail form.

When I blur out the field it's generating the following HTML:

```<code><p class="MuiFormHelperText-root MuiFormHelperText-contained Mui-error">This field is required.</p>
</code>```

How do I add an svg icon to this helper text?

For example a React component <HelperText icon={MyIcon} />, is that possible?

答:
You can add the svg with css class from the global styles.css file, it is not a best practice but it's a nice workaround if there is no other solution for this situation.
Similarly easy to using SVG as an img, you can use it in CSS as a background-image.
for example:

```<code>.MuiFormHelperText-root MuiFormHelperText-contained Mui-error {
  display: block;
  text-indent: -9999px;
  width: 100px;
  height: 82px;
  background: url(example.svg);
  background-size: 100px 82px;
}
</code>```

Notice we set the background-size to the size of the logo element. We have to do that otherwise we’ll just see a bit of the upper left of our much larger original SVG image. These numbers are aspect-ratio aware of the original size. But you could use a background-size keywords like contain if you want to make sure the image will fit and can’t know the parent image will be of the exact right size.

Body:
In my React form I am using Formik, Yup and Material ui form and textfield:

import { TextField } from '@material-ui/core';

for my E-mail form.

When I blur out the field it's generating the following HTML:

This field is required.

How do I add an svg icon to this helper text?

For example a React component <HelperText icon={MyIcon} />, is that possible?

Body:
You can add the svg with css class from the global styles.css file, it is not a best practice but it's a nice workaround if there is no other solution for this situation.
Similarly easy to using SVG as an img, you can use it in CSS as a background-image.
for example:

.MuiFormHelperText-root MuiFormHelperText-contained Mui-error {
  display: block;
  text-indent: -9999px;
  width: 100px;
  height: 82px;
  background: url(example.svg);
  background-size: 100px 82px;
}

Notice we set the background-size to the size of the logo element. We have to do that otherwise we’ll just see a bit of the upper left of our much larger original SVG image. These numbers are aspect-ratio aware of the original size. But you could use a background-size keywords like contain if you want to make sure the image will fit and can’t know the parent image will be of the exact right size.


问:
Is there a kdevelop version that i can install on windows?
is there any other than using Cygwin? thanks!</p>

答:
KDE 4 supports Windows, and you can check the install methods from this and here.

Note that you will have to use either MinGW or MSVC as the compiler, though.


问:
How can I move an element inside a flex div to the right?
i'm trying to move these bars to the right next to the logout button.

This is the current style.

.p-menubar-button {
    display: none;
    cursor: pointer;
    align-items: center;
    justify-content: center;
}
```

I have tried to align-content: flex-end but it doesn't move it.

This is what I'm trying to achieve

答:
this might work , try adding :

flex:1;

Body:
i'm trying to move these bars to the right next to the logout button.

This is the current style.

.p-menubar-button {
    display: none;
    cursor: pointer;
    align-items: center;
    justify-content: center;
}

I have tried to align-content: flex-end but it doesn't move it.

This is what I'm trying to achieve

Body:
this might work , try adding :

flex:1;


问:
Azure Key vault Certificate based Authentication - Production Deployment

Using a self-signed certificate is only recommended for development, not production.

What certificate should a team buy when Application moves to Production - TIA

答:
Ideally, certificates are bought from the certificate authority for production scenarios.

a certificate authority or certification authority (CA) is
an entity that issues digital
certificates. A digital certificate certifies the
ownership of a public key by the named subject of the certificate.
This allows others (relying parties) to rely upon signatures or on
assertions made about the private key that corresponds to the
certified public key. A CA acts as a trusted third party—trusted both
by the subject (owner) of the certificate and by the party relying
upon the certificate. The format of these certificates is specified by
the X.509 or
EMV standard.

Reference: https://thecodeblogger.com/2020/06/20/service-principal-and-certificate-with-azure-key-vault/


问:
Is there any way to provide an alternative layout in a WPF application?
I'm developping an application that will be used in combination with Microsoft Word. I anticipate that the user will resize the my application's window and Microsft Word's window so they don't overlap. When they do so they have the choice to put my application above (or bellow) Word or to put it in the right (or left) of Word.

In one case, my application's window will be much larger than high. In the other case, the window will be really narrow.

Is there any way to provide two layout for my window and switch from one to the other at runtime?

Thanks

答:
Try having a look at this blog post...it might fit your requirements
http://learnwpf.com/post/2011/08/09/Changing-the-DataTemplate-based-on-the-Available-Space-e28093-SizeBasedTemplateSelector.aspx</p>


问:
C string capitalize problem. I encounter bus error
I am making capitalized function. But when execute this code, the bus error occur. Is there anyone can debug this? I really need your help!! please help me . I am computer programming novice without c knowledge.</p>
```<code>#include <stdio.h>
void    up(char *c)
{
    if((*c < ‘z’) && (*c > ‘a’))
    {
        *c -= 32;
    }
}
char    *ft_strcapitalize(char *str)
{
    int i;
    i=0;
    while (str[i])
    {
            up(&str[i]);
        i++;
    }
    return str;
}
int main()
{
    char *str = “salut, comment tu vas ? 42mots quarante-deux cinquante”;
    ft_strcapitalize(str);
    printf(“%s”, str);
}
</code>```

答:
This solution should work for you.

#include <stdio.h>

void up(char *c)
{
    if (!c)
        return;
    if((*c <= 'z') && (*c >= 'a'))
        *c -= 32;
}

char *ft_strcapitalize(char *str)
{
    int i;

    for (i = 0; str[i]; i++)
        up(&str[i]);
    return str;
}

int main()
{
    char str[] = "salut, comment tu vas ? 42mots quarante-deux cinquante";

    ft_strcapitalize(str);
    printf("%s\n", str);
    return 0;
}
```

Body:
I am making capitalized function. But when execute this code, the bus error occur. Is there anyone can debug this? I really need your help!! please help me . I am computer programming novice without c knowledge.

#include <stdio.h>
void    up(char *c)
{
    if((*c < ‘z’) && (*c > ‘a’))
    {
        *c -= 32;
    }
}
char    *ft_strcapitalize(char *str)
{
    int i;
    i=0;
    while (str[i])
    {
            up(&str[i]);
        i++;
    }
    return str;
}
int main()
{
    char *str = “salut, comment tu vas ? 42mots quarante-deux cinquante”;
    ft_strcapitalize(str);
    printf(“%s”, str);
}