问:
"Sign in with Google temporarily disabled for this app" - but we are under the cap
An internal script I use together with my research team uses the Drive API to automate file download from Drive. Some accounts, arbitrarily as far as I could tell, get the "temporarily disabled" message instead of the regular authorization screen.

The behavior is per account - some accounts always get the "temporarily disabled" screen, while the rest always get the desired auth screen. Switching accounts sometimes helps in case one's second account is in the "good group" that gets the auth screen.

We use @gmail accounts (not gsuite). The app uses the https://www.googleapis.com/auth/drive.readonly scope. The app has not been verified and I am aware of the cap when using sensitive scopes. It seems from the dashboard that we are below the user cap. Looking at OAuth consent screen > OAuth rate limits > Your user cap I see "5 users / 100 user cap".

Can someone explain this behavior?

Am I looking at the right thing on the dashboard?

Can I use a less sensitive scope that will not require verification? We only need to download specific files/folders.

答: If an app or service shows the Sign in with Google temporarily disabled for this app message it means that Google paralyzed the app/service for security reasons. The only thing that you can do is go through the verification process.


来源: stackexchange

问:
POP3 Authentication with OAuth gives "Err Protocol error. Connection is closed"
My company needs to upgrade an application to integrate two-legged OAuth 2.0 for POP3. I'm testing with an outlook online account and trying to authenticate on outlook.office365.com (I've also tried pop3.live.com).

I registered for an Exchange Online trial using my test outlook account.

I've registered my app on Azure and have enabled API Application Permissions for MS Graph (Mail.ReadWrite, Mail.Send) and Exchange (full_access_as_app). The same outlook account I used for the Exchange registration is the Global Admin of the Azure tenant.

I'm able to request a valid OAuth token from both the Graph and Exchange endpoints. However, when I use the token and try to log into the POP server, I get the following error:

```<code><PopCmdSent>AUTH XOAUTH2 [token]</PopCmdSent>
<PopCmdResp>-ERR Protocol error. Connection is closed. 10</PopCmdResp>
</code>```

Followed by:

```<code><error>POP3 authentication failed</error>
</code>```

I'm not sure what this error means. Does my mail component need to be set up to use a different protocol (not sure if this is possible)? Could this be an issue with the way my application is registered/authenticated or with the Exchange security settings?

The login works fine if I use Basic Auth instead of OAuth.

How can I troubleshoot this?

Edit

I recently stumbled across this Microsoft article that references the same error, but it's related to Exchange Server 2007. The article says the solution is to increase the "MaxCommandSize" setting on the Exchange server from the default 40kb.

This is literally the only other place I've seen this error referenced online:

https://support.microsoft.com/en-ca/help/945552/error-message-when-you-try-to-connect-to-a-pop3-mailbox-on-exchange-se

I wonder if this is relevant for Exchange Online/Outlook? I'm unable to find a similar setting on my Exchange Online trial or Outlook mail settings

Edit 2

I had an email exchange with a developer of the mail component I'm using (Chilkat Mailman). He has apparently been stuck on the same problem for a few months. He says the correct protocols for XOAUTH2 are implemented in the component and should work the same for any mail server.

However, he's also having difficulty linking the Azure app registration to a specific O365 account and getting the correct scope/permissions to authenticate the account.

It's good to hear that I'm not the only one struggling with this and that there isn't an obvious piece I'm missing. But also pretty concerning that the developer of a popular mail component is having trouble replicating what used to be an incredibly simple process.

Article he wrote on his current understanding (not sure if this is relevant):

https://cknotes.com/o365-imap-authentication-oauth-mfa-wtf/

答:
POP3 Auth2.0 for office365 was rolled over only few days ago.

Please see "Announcing OAuth Support for POP in Exchange Online " for more information.

ContentLicense: CC BY-SA 4.0

Body:
My company needs to upgrade an application to integrate two-legged OAuth 2.0 for POP3. I'm testing with an outlook online account and trying to authenticate on outlook.office365.com (I've also tried pop3.live.com).

I registered for an Exchange Online trial using my test outlook account.

I've registered my app on Azure and have enabled API Application Permissions for MS Graph (Mail.ReadWrite, Mail.Send) and Exchange (full_access_as_app). The same outlook account I used for the Exchange registration is the Global Admin of the Azure tenant.

I'm able to request a valid OAuth token from both the Graph and Exchange endpoints. However, when I use the token and try to log into the POP server, I get the following error:

<PopCmdSent>AUTH XOAUTH2 [token]</PopCmdSent>
<PopCmdResp>-ERR Protocol error. Connection is closed. 10</PopCmdResp>

Followed by:

<error>POP3 authentication failed</error>

I'm not sure what this error means. Does my mail component need to be set up to use a different protocol (not sure if this is possible)? Could this be an issue with the way my application is registered/authenticated or with the Exchange security settings?

The login works fine if I use Basic Auth instead of OAuth.

How can I troubleshoot this?

Edit

I recently stumbled across this Microsoft article that references the same error, but it's related to Exchange Server 2007. The article says the solution is to increase the "MaxCommandSize" setting on the Exchange server from the default 40kb.

This is literally the only other place I've seen this error referenced online:

https://support.microsoft.com/en-ca/help/945552/error-message-when-you-try-to-connect-to-a-pop3-mailbox-on-exchange-se

I wonder if this is relevant for Exchange Online/Outlook? I'm unable to find a similar setting on my Exchange Online trial or Outlook mail settings

Edit 2

I had an email exchange with a developer of the mail component I'm using (Chilkat Mailman). He has apparently been stuck on the same problem for a few months. He says the correct protocols for XOAUTH2 are implemented in the component and should work the same for any mail server.

However, he's also having difficulty linking the Azure app registration to a specific O365 account and getting the correct scope/permissions to authenticate the account.

It's good to hear that I'm not the only one struggling with this and that there isn't an obvious piece I'm missing. But also pretty concerning that the developer of a popular mail component is having trouble replicating what used to be an incredibly simple process.

Article he wrote on his current understanding (not sure if this is relevant):

https://cknotes.com/o365-imap-authentication-oauth-mfa-wtf/


问:
how do I register an invisible window class in a Win32 console application?
I am trying to register an invisible window in a Win32 console application. My goal is to listen for Raw Input in the WindowProc to (1) display it on the console, and (2) perform additional computation e.g. sending information over a Web socket. I followed this CodeProject article, but my WNDCLASSEX registration seems to fail.

Here is the code that I have:

approach 1 -- registration does not seem to work

My main function

WNDCLASSEX wndclass;
wndclass.cbSize = sizeof(WNDCLASSEX);
wndclass.lpfnWndProc = NVTouch_WindowProc;
wndclass.hInstance = GetModuleHandle(NULL);
wndclass.lpszClassName = L"myclass";
bool isClassRegistered = false;
isClassRegistered =  RegisterClassEx(&wndclass);
if (isClassRegistered) //1
{
    HWND window = CreateWindow(wndclass.lpszClassName, NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, GetModuleHandle(0), NULL);
    if (window)
    {
        ShowWindow(window, SW_SHOWDEFAULT);
        MSG msg;
        while (GetMessage(&msg, 0, 0, 0))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }
}
```

<h3>My WindowProc function:</h3>

```static LRESULT CALLBACK NVTouch_WindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    std::cout << "window Proc";
    bool registrationStatus = false;
    switch (message)
    {
    case WM_CREATE:
        registrationStatus  = registerTouchpadForInput();
        break;
    case WM_DESTROY:
        std::cout << "destroying application.";
        PostQuitMessage(0);
        break;
    case WM_INPUT:
        std::cout << "input!";
        break;
    default:
        std::cout << "default.";
        return DefWindowProc(hwnd, message, wParam, lParam);
    }
    return 0;
}
```

<p>When I put breakpoints in Visual Studio 2019, I notice my code jumps from <code>//1</code> to <code>//2</code> with the registration status being <code>false</code>.</p>

<p>I had a similar implementation based on this article where registration was successful, but I wasn't able to listen for the <code>WM_INPUT</code> messages.</p>

<h2>approach 2 -- window creation works, but WM_INPUT messages are not read</h2>

```int main()
{
    WNDCLASSEX wndclass = {
        sizeof(WNDCLASSEX),
        CS_DBLCLKS,
        NVTouch_WindowProc,
        0,
        0,
        GetModuleHandle(0),
        LoadIcon(0,IDI_APPLICATION),
        LoadCursor(0,IDC_ARROW),
        HBRUSH(COLOR_WINDOW + 1),
        0,
        L"myclass",
        LoadIcon(0,IDI_APPLICATION)
    };
    bool isClassRegistered = false;
    isClassRegistered =  RegisterClassEx(&wndclass);
    if (isClassRegistered)
    {
        std::cout << "window class registered!";
        HWND window = CreateWindowEx(0, L"myclass", L"title", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, GetModuleHandle(0), 0);
        if (window)
        {
            ShowWindow(window, SW_SHOWDEFAULT);
            MSG msg;
            while (GetMessage(&msg, 0, 0, 0))
            {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
        }
    }
}
```

I want to ideally register the class and display Raw Input on the console (approach 1), but being able to do that modifying approach 2 code would also work.

Why is my registration failing in approach 1? Why am I not able to listen for WM_INPUT messages in approach 2?

答:
In approach 1:

You need to initialize wndclass:

```<code>WNDCLASSEX wndclass = { 0 };
</code>```

Otherwise, the uninitialized part defaults to random values(Undefined behavior, usually like 0xcccccccc), and RegisterClassEx will failed with error code: 87.

In approach 2:

You initialized all the members in wndclass, so the RegisterClassEx succeed.
I cannot reproduce the issue with approach 2, The problem may be in the registerTouchpadForInput.

Noticed that this function has no parameters, but RegisterRawInputDevices need to set RAWINPUTDEVICE.hwndTarget, maybe you have not set the target window, if you set to NULL, according to the document, you must focus your keyboard on your window To receive the message.

In addition, in approach 2, the program will create a visible window. For generating an invisible window, create a Message-Only Windows as in approach 1.

sample:

```<code>#include <windows.h>
#include <iostream>

using namespace std;
BOOL registerTouchpadForInput(HWND hWnd)
{
    RAWINPUTDEVICE rid;
    rid.dwFlags = RIDEV_NOLEGACY | RIDEV_INPUTSINK;
    rid.usUsagePage = 1;                            // raw keyboard data only
    rid.usUsage = 6;
    rid.hwndTarget = hWnd;
    return RegisterRawInputDevices(&rid, 1, sizeof(rid));
}
static LRESULT CALLBACK NVTouch_WindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    std::cout << "window Proc";
    BOOL  registrationStatus = false;
    switch (message)
    {
    case WM_CREATE:
        registrationStatus = registerTouchpadForInput(hwnd);
        break;
    case WM_DESTROY:
        std::cout << "destroying application.";
        PostQuitMessage(0);
        break;
    case WM_INPUT:
        std::cout << "input!";
        return DefWindowProc(hwnd, message, wParam, lParam);
    default:
        std::cout << "default.";
        return DefWindowProc(hwnd, message, wParam, lParam);
    }
    return 0;
}

int main()
{
    WNDCLASSEX wndclass = {
        sizeof(WNDCLASSEX),
        CS_DBLCLKS,
        NVTouch_WindowProc,
        0,
        0,
        GetModuleHandle(0),
        LoadIcon(0,IDI_APPLICATION),
        LoadCursor(0,IDC_ARROW),
        HBRUSH(COLOR_WINDOW + 1),
        0,
        L"myclass",
        LoadIcon(0,IDI_APPLICATION)
    };
    bool isClassRegistered = false;
    isClassRegistered = RegisterClassEx(&wndclass);
    if (isClassRegistered)
    {
        std::cout << "window class registered!";
        //HWND window = CreateWindowEx(0, L"myclass", L"title", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, GetModuleHandle(0), 0);
        HWND window = CreateWindow(wndclass.lpszClassName, NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, GetModuleHandle(0), NULL);
        if (window)
        {
            ShowWindow(window, SW_SHOWDEFAULT);
            MSG msg;
            while (GetMessage(&msg, 0, 0, 0))
            {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
        }
    }
}
</code>```

Body:
I am trying to register an invisible window in a Win32 console application. My goal is to listen for Raw Input in the WindowProc to (1) display it on the console, and (2) perform additional computation e.g. sending information over a Web socket. I followed this CodeProject article, but my WNDCLASSEX registration seems to fail.

Here is the code that I have:

approach 1 -- registration does not seem to work

My main function

WNDCLASSEX wndclass;
wndclass.cbSize = sizeof(WNDCLASSEX);
wndclass.lpfnWndProc = NVTouch_WindowProc;
wndclass.hInstance = GetModuleHandle(NULL);
wndclass.lpszClassName = L"myclass";
bool isClassRegistered = false;
isClassRegistered =  RegisterClassEx(&wndclass);
if (isClassRegistered) //1
{
    HWND window = CreateWindow(wndclass.lpszClassName, NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, GetModuleHandle(0), NULL);
    if (window)
    {
        ShowWindow(window, SW_SHOWDEFAULT);
        MSG msg;
        while (GetMessage(&msg, 0, 0, 0))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }
}

My WindowProc function:

static LRESULT CALLBACK NVTouch_WindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    std::cout << "window Proc";
    bool registrationStatus = false;
    switch (message)
    {
    case WM_CREATE:
        registrationStatus  = registerTouchpadForInput();
        break;
    case WM_DESTROY:
        std::cout << "destroying application.";
        PostQuitMessage(0);
        break;
    case WM_INPUT:
        std::cout << "input!";
        break;
    default:
        std::cout << "default.";
        return DefWindowProc(hwnd, message, wParam, lParam);
    }
    return 0;
}

When I put breakpoints in Visual Studio 2019, I notice my code jumps from //1 to //2 with the registration status being false.

I had a similar implementation based on this article where registration was successful, but I wasn't able to listen for the WM_INPUT messages.

approach 2 -- window creation works, but WM_INPUT messages are not read

int main()
{
    WNDCLASSEX wndclass = {
        sizeof(WNDCLASSEX),
        CS_DBLCLKS,
        NVTouch_WindowProc,
        0,
        0,
        GetModuleHandle(0),
        LoadIcon(0,IDI_APPLICATION),
        LoadCursor(0,IDC_ARROW),
        HBRUSH(COLOR_WINDOW + 1),
        0,
        L"myclass",
        LoadIcon(0,IDI_APPLICATION)
    };
    bool isClassRegistered = false;
    isClassRegistered =  RegisterClassEx(&wndclass);
    if (isClassRegistered)
    {
        std::cout << "window class registered!";
        HWND window = CreateWindowEx(0, L"myclass", L"title", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, GetModuleHandle(0), 0);
        if (window)
        {
            ShowWindow(window, SW_SHOWDEFAULT);
            MSG msg;
            while (GetMessage(&msg, 0, 0, 0))
            {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
        }
    }
}

I want to ideally register the class and display Raw Input on the console (approach 1), but being able to do that modifying approach 2 code would also work.

Why is my registration failing in approach 1? Why am I not able to listen for WM_INPUT messages in approach 2?

Body:
In approach 1:

You need to initialize wndclass:

WNDCLASSEX wndclass = { 0 };

Otherwise, the uninitialized part defaults to random values(Undefined behavior, usually like 0xcccccccc), and RegisterClassEx will failed with error code: 87.

In approach 2:

You initialized all the members in wndclass, so the RegisterClassEx succeed.
I cannot reproduce the issue with approach 2, The problem may be in the registerTouchpadForInput.

Noticed that this function has no parameters, but RegisterRawInputDevices need to set RAWINPUTDEVICE.hwndTarget, maybe you have not set the target window, if you set to NULL, according to the document, you must focus your keyboard on your window To receive the message.

In addition, in approach 2, the program will create a visible window. For generating an invisible window, create a Message-Only Windows as in approach 1.

sample:

#include <windows.h>
#include <iostream>

using namespace std;
BOOL registerTouchpadForInput(HWND hWnd)
{
    RAWINPUTDEVICE rid;
    rid.dwFlags = RIDEV_NOLEGACY | RIDEV_INPUTSINK;
    rid.usUsagePage = 1;                            // raw keyboard data only
    rid.usUsage = 6;
    rid.hwndTarget = hWnd;
    return RegisterRawInputDevices(&rid, 1, sizeof(rid));
}
static LRESULT CALLBACK NVTouch_WindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    std::cout << "window Proc";
    BOOL  registrationStatus = false;
    switch (message)
    {
    case WM_CREATE:
        registrationStatus = registerTouchpadForInput(hwnd);
        break;
    case WM_DESTROY:
        std::cout << "destroying application.";
        PostQuitMessage(0);
        break;
    case WM_INPUT:
        std::cout << "input!";
        return DefWindowProc(hwnd, message, wParam, lParam);
    default:
        std::cout << "default.";
        return DefWindowProc(hwnd, message, wParam, lParam);
    }
    return 0;
}

int main()
{
    WNDCLASSEX wndclass = {
        sizeof(WNDCLASSEX),
        CS_DBLCLKS,
        NVTouch_WindowProc,
        0,
        0,
        GetModuleHandle(0),
        LoadIcon(0,IDI_APPLICATION),
        LoadCursor(0,IDC_ARROW),
        HBRUSH(COLOR_WINDOW + 1),
        0,
        L"myclass",
        LoadIcon(0,IDI_APPLICATION)
    };
    bool isClassRegistered = false;
    isClassRegistered = RegisterClassEx(&wndclass);
    if (isClassRegistered)
    {
        std::cout << "window class registered!";
        //HWND window = CreateWindowEx(0, L"myclass", L"title", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, GetModuleHandle(0), 0);
        HWND window = CreateWindow(wndclass.lpszClassName, NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, GetModuleHandle(0), NULL);
        if (window)
        {
            ShowWindow(window, SW_SHOWDEFAULT);
            MSG msg;
            while (GetMessage(&msg, 0, 0, 0))
            {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
        }
    }
}


问:
When will it be impossible to support Visual Basic 6.0 applications?
In the last 3-5 years I have been renewing an insurance application and a commmercial integration toolkit based on Visual Basic 6.0.

According to Microsoft's "It just works policy" the IDE is no longer supported after april 8th 2008.

It still works to develop and deploy Visual Basic 6.0 applications.

When will it be impossible to support Visual Basic 6.0 applications, or will they live forever like Cobol applications do?

Update: Microsoft statement march 2010: The Visual Basic team is committed to “It Just Works” compatibility for Visual Basic 6.0 applications on Windows Vista, Windows Server 2008 including R2, and Windows 7.

Update may 2011:

Happy 20th Birthday Visual Basic!

答:
I have to say this is something you cannot accuse the much (and justly!) maligned COBOL for.

COBOL is continuously supported with frequent new releases from IBM, UNISYS, MicroFocus on several platforms which support things like the latest hardware, 64bit addressing,  built in support for XML etc.. There is even a Linux version (OpenCobol) which is progressing nicely.

Furthermore the language itself is continuously developing (if you can call making the same old mistakes with new reserved words developing :-} ) and the latest langauge specification is fully OO look here if you don't believe me!

So COBOL is not yet dead merely archaic. Whereas I think VB 6.0 really is dead and just bit late for its own funeral.

OwnerDisplayName: Keb

ContentLicense: CC BY-SA 3.0


问:
How to position cursor in input field after icon
I have an input field that has a search icon positioned inside of it using the background property and every time I type in it the cursor sticks in the beginning like shown in the picture:

https://imgur.com/ocJRux8

How can I position the cursor after the search icon? I tried setting the padding-left and the text-indent but that also moves the placeholder which is not desirable.

Here is my input field:

```<code>import React, { Component } from "react";
import Spinner from '../../components/Spinner/Spinner.jsx';
import { Link } from 'react-router-dom';

import axios from "axios";

class Search extends Component {

    state = {
        searchResults: [],
        isLoading: false
    }

    getSearchQuery = (event) => {
        const SEARCH_RESULTS_ENDPOINT = process.env.REACT_APP_SEARCH_ENDPOINT;

        const queryString = document.querySelector(
            ".search-input"
        ).value;
        if (event.keyCode === 13) {
            this.setState({ ...this.state, isLoading: true });
            axios.post(SEARCH_RESULTS_ENDPOINT, {
                queryString: queryString,

            }).then(response => {
                this.setState({ ...this.state, searchResults: response.data });
                this.setState({ ...this.state, isLoading: false });
            });
        }
    };

    render() {
        if (this.state.isLoading) {
            return <Spinner />
        }
        return (

            <div>
                <input
                    type="text"
                    placeholder="Search"
                    className="search-input"
                    onKeyDown={(e) => this.getSearchQuery(e)}

                />
                <div>
                    {this.state.searchResults.map(result => (
                        <div key={result._id} >
                            <img src={result.picture} alt="avatar" />
                            <div >
                                <div>
                                    <h2>{result.title}</h2>
                                    <p>{result.date}</p>
                                    <p>{result.postContent}</p>
                                    <Link to={`/post/${result._id}`} className="read-more-btn">
                                        <button className="read-more-btn">Read more</button>
                                    </Link>
                                </div>
                            </div>
                        </div>
                    ))}

                </div>
            </div>
        );
    }
}

export default Search;
</code>```

and here is my CSS:

```<code>.search-input {
    background: url(../../assets/images/search-icon.png) no-repeat scroll 12px 12px;
    background-size: 20px 20px;
    margin: auto;
    display: block;
    width: 500px;
    margin-top: 30px;
    height: 40px;
    border: solid 1px #AAAAAA;
    // text-indent: 30px;
}

.search-icon {
  height: 20px;
  width: 20px;
}

.no-results-found {
 text-align: center;
 margin-top: 50px;
}

.search-input::-webkit-input-placeholder { /* Chrome/Opera/Safari */
    padding-left:35px;
}

input:focus{
  outline: none;
}

  ::-moz-placeholder { /* Firefox 19+ */
    padding-left:20px;
}
  :-ms-input-placeholder { /* IE 10+ */
    padding-left:20px;
}
  :-moz-placeholder { /* Firefox 18- */
    padding-left:20px;
}
</code>```

答:
Add some padding to search input as it will pad that much area.

```<code>.search-input {
    background: url(../../assets/images/search-icon.png) no-repeat scroll 12px 12px;
    background-size: 20px 20px;
    margin: auto;
    display: block;
    width: 500px;
    margin-top: 30px;
    height: 40px;
    border: solid 1px #AAAAAA;
    padding-left: 20px;
}

</code>```

Body:
I have an input field that has a search icon positioned inside of it using the background property and every time I type in it the cursor sticks in the beginning like shown in the picture:

https://imgur.com/ocJRux8

How can I position the cursor after the search icon? I tried setting the padding-left and the text-indent but that also moves the placeholder which is not desirable.

Here is my input field:

import React, { Component } from "react";
import Spinner from '../../components/Spinner/Spinner.jsx';
import { Link } from 'react-router-dom';

import axios from "axios";

class Search extends Component {

    state = {
        searchResults: [],
        isLoading: false
    }

    getSearchQuery = (event) => {
        const SEARCH_RESULTS_ENDPOINT = process.env.REACT_APP_SEARCH_ENDPOINT;

        const queryString = document.querySelector(
            ".search-input"
        ).value;
        if (event.keyCode === 13) {
            this.setState({ ...this.state, isLoading: true });
            axios.post(SEARCH_RESULTS_ENDPOINT, {
                queryString: queryString,

            }).then(response => {
                this.setState({ ...this.state, searchResults: response.data });
                this.setState({ ...this.state, isLoading: false });
            });
        }
    };

    render() {
        if (this.state.isLoading) {
            return <Spinner />
        }
        return (

                <input
                    type="text"
                    placeholder="Search"
                    className="search-input"
                    onKeyDown={(e) => this.getSearchQuery(e)}

                />

                    {this.state.searchResults.map(result => (

{result.title}

{result.date}

{result.postContent}

                                    <Link to={`/post/${result._id}`} className="read-more-btn">
                                        <button className="read-more-btn">Read more</button>
                                    </Link>

                    ))}

        );
    }
}

export default Search;

and here is my CSS:

.search-input {
    background: url(../../assets/images/search-icon.png) no-repeat scroll 12px 12px;
    background-size: 20px 20px;
    margin: auto;
    display: block;
    width: 500px;
    margin-top: 30px;
    height: 40px;
    border: solid 1px #AAAAAA;
    // text-indent: 30px;
}

.search-icon {
  height: 20px;
  width: 20px;
}

.no-results-found {
 text-align: center;
 margin-top: 50px;
}

.search-input::-webkit-input-placeholder { /* Chrome/Opera/Safari */
    padding-left:35px;
}

input:focus{
  outline: none;
}

  ::-moz-placeholder { /* Firefox 19+ */
    padding-left:20px;
}
  :-ms-input-placeholder { /* IE 10+ */
    padding-left:20px;
}
  :-moz-placeholder { /* Firefox 18- */
    padding-left:20px;
}

Body:
Add some padding to search input as it will pad that much area.

.search-input {
    background: url(../../assets/images/search-icon.png) no-repeat scroll 12px 12px;
    background-size: 20px 20px;
    margin: auto;
    display: block;
    width: 500px;
    margin-top: 30px;
    height: 40px;
    border: solid 1px #AAAAAA;
    padding-left: 20px;
}


问:
Angular resolver observable completes too early
I am passing a subject as an observable from a service to a resolver. The service may complete the observable when an http request completes or when it finds that the data it needs is cached. In the second case, where the data is cached it looks like the observable completes too early because the route transition does not happen. if i put the requestSubject.complete() inside a setTimeout with some timeout it works but otherwise it doesnt.</p>

```<code>//resolve function from resolver
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
  const id = +route.paramMap.get('id');
  const language = route.queryParamMap.get('language');
  const request = this.service.get(id, language);
  request.pipe(share()).subscribe(
    () => {},
    () => { this.router.navigateByUrl(AppRoutingConfig.search); });
  return request;
}

//the service get function
get(id: number, language: string): Observable<any> {
  const requestSubject = new Subject();
  if (!isDataCached(id)) {
    const url = `some url`;
    const sub = this.http.get(url).subscribe((item: any) => {
      requestSubject.next(1);
    }, () => {
        requestSubject.error(0);
    }, () => {
      requestSubject.complete();
    });
  } else {
    requestSubject.complete();
  }
  return requestSubject.asObservable();
}
</code>```

答:
In your case instead of Subject you need to use ReplaySubject, it remembers the last value and will emit it once someone subscribes.

Nevertheless I would change the get() to use a caching state for the stream.

//resolve function from resolver
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
  const id = +route.paramMap.get('id');
  const language = route.queryParamMap.get('language');
  return this.service.get(id, language).pipe(
    catchError(() => {
      this.router.navigateByUrl(AppRoutingConfig.search);
      return EMPTY; // to suppress the stream
    }),
  );
}

//the service get function
private readonly cache = new Map(); // our cache for urls

get(id: number, language: string): Observable<any> {
  const url = `some url`;

  // if we had the id - we return its observable.
  if (this.cache.has(id)) {
    return cache.get(id);
  }

  // otherwise we create a replay subject.
  const status$ = new ReplaySubject(1);
  this.cache.set(id, status$);

  this.http.get(url).subscribe(
    () => status$.next(),
    e => status$.error(e),
    () => requestSubject.complete(),
  );

  return status$.asObservable();
}
```

Body:
I am passing a subject as an observable from a service to a resolver. The service may complete the observable when an http request completes or when it finds that the data it needs is cached. In the second case, where the data is cached it looks like the observable completes too early because the route transition does not happen. if i put the requestSubject.complete() inside a setTimeout with some timeout it works but otherwise it doesnt.

//resolve function from resolver
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
  const id = +route.paramMap.get('id');
  const language = route.queryParamMap.get('language');
  const request = this.service.get(id, language);
  request.pipe(share()).subscribe(
    () => {},
    () => { this.router.navigateByUrl(AppRoutingConfig.search); });
  return request;
}

//the service get function
get(id: number, language: string): Observable<any> {
  const requestSubject = new Subject();
  if (!isDataCached(id)) {
    const url = `some url`;
    const sub = this.http.get(url).subscribe((item: any) => {
      requestSubject.next(1);
    }, () => {
        requestSubject.error(0);
    }, () => {
      requestSubject.complete();
    });
  } else {
    requestSubject.complete();
  }
  return requestSubject.asObservable();
}


问:
Custom JComponent (A Line) Doesn't Show Up On JPanel
It shows the line without jpanel on jframe, but it doesn't when I add it to jpanel. I've tried setting the layout manager of jpanel to null but no result. I want to use JComponents for drawing lines because I want them clickable.

Main.java file:

```<code>import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;

class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
    frame.setSize(500, 500);

    //Parent Panel
    JPanel panel = new JPanel();
    panel.setBackground(Color.YELLOW);
    panel.setLayout(null);

    //Add Line To Panel
    Line line = new Line(new Point2D.Double(20,20), new Point2D.Double(180,180));

    panel.add(line);
    panel.repaint();

    frame.add(panel);
    frame.setVisible(true);
  }
}

class Line extends JComponent {

   private final Point2D start, end;

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(Color.BLUE);
        g2.setStroke(new BasicStroke(2.0F));
        g2.draw(new Line2D.Double(start,end));
    }

    public Line( Point2D start, Point2D end){
        this.start = start;
        this.end = end;
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                System.out.println("mouse clicked");
            }
        });
    }
}
</code>```

答:
Add custom size in Line constructor.

public Line( Point2D start, Point2D end){ ...

this.setSize(200, 200); }

Updated to fit also with painted Graph

Advice to change from JComponent to JPanel in order to see background

```<code>import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
    frame.setSize(500, 500);

    //Parent Panel
    JPanel panel = new JPanel();
    panel.setSize(300,300);
    frame.add(panel);
    panel.setBackground(Color.YELLOW);
    panel.setLayout(null);

    //Add Line To Panel
    Line line = new Line(new Point2D.Double(20,20), new Point2D.Double(180,180));
    panel.add(line);

    frame.setVisible(true);
  }
}

class Line extends JPanel {

   private final Point2D start, end;

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setBackground(Color.RED);
        g2.setColor(Color.BLUE);
        g2.setStroke(new BasicStroke(2.0F));
        g2.draw(new Line2D.Double(start,end));
        Rectangle r = g2.getClipBounds();
        System.out.println(r.x+":"+r.y);
    }

    public Line( Point2D start, Point2D end){

        this.start = start;
        this.end = end;
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                System.out.println("mouse clicked at "+e.getX()+":"+e.getY());

            }
        });
        int max_x = (int) Math.max(start.getX(), end.getX());
        int max_y = (int) Math.max(start.getY(), end.getY());
        System.out.println("max x="+max_y+",y="+max_y);
        setSize(max_x,max_y);
        setVisible(true);
        setBackground(Color.GREEN);
    }
}
</code>```

Note: Only inside_green clicks allowed !

Body:
It shows the line without jpanel on jframe, but it doesn't when I add it to jpanel. I've tried setting the layout manager of jpanel to null but no result. I want to use JComponents for drawing lines because I want them clickable.

Main.java file:

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;

class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
    frame.setSize(500, 500);

    //Parent Panel
    JPanel panel = new JPanel();
    panel.setBackground(Color.YELLOW);
    panel.setLayout(null);

    //Add Line To Panel
    Line line = new Line(new Point2D.Double(20,20), new Point2D.Double(180,180));

    panel.add(line);
    panel.repaint();

    frame.add(panel);
    frame.setVisible(true);
  }
}

class Line extends JComponent {

   private final Point2D start, end;

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(Color.BLUE);
        g2.setStroke(new BasicStroke(2.0F));
        g2.draw(new Line2D.Double(start,end));
    }

    public Line( Point2D start, Point2D end){
        this.start = start;
        this.end = end;
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                System.out.println("mouse clicked");
            }
        });
    }
}

Body:
Add custom size in Line constructor.

public Line( Point2D start, Point2D end){ ...

this.setSize(200, 200); }

Updated to fit also with painted Graph

Advice to change from JComponent to JPanel in order to see background

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
    frame.setSize(500, 500);

    //Parent Panel
    JPanel panel = new JPanel();
    panel.setSize(300,300);
    frame.add(panel);
    panel.setBackground(Color.YELLOW);
    panel.setLayout(null);

    //Add Line To Panel
    Line line = new Line(new Point2D.Double(20,20), new Point2D.Double(180,180));
    panel.add(line);

    frame.setVisible(true);
  }
}

class Line extends JPanel {

   private final Point2D start, end;

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setBackground(Color.RED);
        g2.setColor(Color.BLUE);
        g2.setStroke(new BasicStroke(2.0F));
        g2.draw(new Line2D.Double(start,end));
        Rectangle r = g2.getClipBounds();
        System.out.println(r.x+":"+r.y);
    }

    public Line( Point2D start, Point2D end){

        this.start = start;
        this.end = end;
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                System.out.println("mouse clicked at "+e.getX()+":"+e.getY());

            }
        });
        int max_x = (int) Math.max(start.getX(), end.getX());
        int max_y = (int) Math.max(start.getY(), end.getY());
        System.out.println("max x="+max_y+",y="+max_y);
        setSize(max_x,max_y);
        setVisible(true);
        setBackground(Color.GREEN);
    }
}

Note: Only inside_green clicks allowed !


问:
Bitcoin SegWit Wallet Address Calculation
Sorry if this is a bit misleading, but I was actually doing this with Litecoin as opposed to Bitcoin, but the algorithm is exactly the same and I'm pretty sure that the answer will be too.  In fact, am almost certain when I look, there's going to be the same problem with Bitcoin too.  I'm having difficulty generating the correct SegWit address for a given public key as below:

Litecoin address generation (which is the same as Bitcoin)

I take a compressed public key:
03861b83752e0c47cac36fc5980ae8956f41f6d9792a51f68a6bd5f66cc7364b48

SHA256 on the public key.

RipeMD160 the result from 2.

Add a prefix byte, in my case, 0x3a which is the LTC_TESTNET

Double SHA256 result of 4 and add the first four bytes of this result to the end of the RipeMD160.

Finally, Base58 encode.

All seems dandy, right?  Out pops the SegWit address:  QhQxSZvVDWr3JvoKsYVC6BBW3DqkGhesrF

However, I'm pretty sure this address isn't right.  When I import the private key into Electrum-LTC as a (p2wpkh-p2sh:) the address it generates for this private key is:  QYyWqgyWSm1AJWph32GnyY7eamG1wUDruk

Now I believe that Electrum-LTC is right and there's something that I'm missing when generating a SegWit address and there's more to address generation than just changing the network prefix.
My Public Key Hash is:

e444ac77800cdf904b928fc4642ab6fb6d4d696c

and Electrum-LTC's Public Key Hash is:

87b3e5bf5b2a1381e6549020d245e45b9ac76c82

Since the values are so VERY different, it suggests that the initial SHA256 is not hashing just the public key alone and that I'm missing something.  I'm about out of ideas and am hoping someone has the answer and about the only thing I can find in the source, in the chainparams.cpp was this:

```<code>base58Prefixes[EXT_PUBLIC_KEY] = {0x04, 0x88, 0xB2, 0x1E};
</code>```

Anyone know what I might be doing wrong?

Update - Someone asked for the code - so here it is

```<code>#include <openssl/sha.h>
#include <openssl/ripemd.h>
#include <cstdint>
#include <iostream>
#include <vector>

std::string base58Encode(const std::vector<uint8_t>& data)
{
    const uint8_t mapping[] = {
      '1', '2', '3', '4', '5', '6', '7', '8',
      '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
      'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q',
      'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
      'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
      'h', 'i', 'j', 'k', 'm', 'n', 'o', 'p',
      'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
      'y', 'z' };

    std::vector<uint8_t> digits((data.size() * 137) / 100);
    size_t digitslen = 1;
    for (size_t i = 0; i < data.size(); i++)
    {
        uint32_t carry = static_cast<uint32_t>(data[i]);
        for (size_t j = 0; j < digitslen; j++)
        {
            carry = carry + static_cast<uint32_t>(digits[j] << 8);
            digits[j] = static_cast<uint8_t>(carry % 58);
            carry /= 58;
        }
        for (; carry; carry /= 58)
            digits[digitslen++] = static_cast<uint8_t>(carry % 58);
    }
    std::string result;
    for (size_t i = 0; i < data.size() && !data[i]; i++)
        result.push_back(mapping[0]);
    for (size_t i = 0; i < digitslen; i++)
        result.push_back(mapping[digits[digitslen - 1 - i]]);
    return result;
}

std::vector<uint8_t> SHA256_Hash(const std::vector<uint8_t>& data)
{
    std::vector<uint8_t> SHA256_Digest(SHA256_DIGEST_LENGTH);
    SHA256_CTX ctx;
    SHA256_Init(&ctx);
    SHA256_Update(&ctx, data.data(), data.size());
    SHA256_Final(SHA256_Digest.data(), &ctx);
    return SHA256_Digest;
}

std::vector<uint8_t> RipeMD160_Hash(const std::vector<uint8_t>& data)
{
    std::vector<uint8_t> RipeMD160_Digest(RIPEMD160_DIGEST_LENGTH);
    RIPEMD160_CTX ctx;
    RIPEMD160_Init(&ctx);
    RIPEMD160_Update(&ctx, data.data(), data.size());
    RIPEMD160_Final(RipeMD160_Digest.data(), &ctx);
    return RipeMD160_Digest;
}

std::string getWalletAddress(const std::vector<uint8_t>& public_key, uint8_t id)
{
    std::vector<uint8_t> addr_hash = SHA256_Hash(key);
    std::vector<uint8_t> addr_ripe = RipeMD160_Hash(addr_hash);
    addr_ripe.insert(addr_ripe.begin(), id);
    addr_hash = SHA256_Hash(SHA256_Hash(addr_ripe));
    addr_ripe.insert(addr_ripe.end(), addr_hash.begin(), addr_hash.begin() + sizeof(uint32_t));
    return base58Encode(addr_ripe);
}

int main(int argc, char** argv)
{
    const uint8_t LTC_TESTNET = 0x3a;

    std::vector<uint8_t> public_key{
        0x03, 0x86, 0x1b, 0x83, 0x75, 0x2e, 0x0c, 0x47, 0xca, 0xc3, 0x6f, 0xc5, 0x98, 0x0a, 0xe8, 0x95,
        0x6f, 0x41, 0xf6, 0xd9, 0x79, 0x2a, 0x51, 0xf6, 0x8a, 0x6b, 0xd5, 0xf6, 0x6c, 0xc7, 0x36, 0x4b, 0x48};

    std::cout << "Wallet Address: " << getWalletAddress(public_key, LTC_TESTNET) << std::endl;
    // The above ouputs:  QhQxSZvVDWr3JvoKsYVC6BBW3DqkGhesrF
    // But it should be:  QYyWqgyWSm1AJWph32GnyY7eamG1wUDruk
    return 0;
}
</code>```

答:
Have finally figured this one out...  When calculating a p2wpkh-p2sh address, it's not just the prefix of the address that is different.  In actual fact, I found the answer to the above problem here:  https://bitcoin.stackexchange.com/questions/72775/is-it-possible-to-convert-an-address-from-p2pkh-to-p2sh  (although it is quite cryptic in how it is explained).

The above code in my question will work quite happily for p2pkh address generation for Bitcoin/Litecoin etc, but when generating a Q (for Litecoin), 2 (for Bitcoin), it won't work because it's not just the public key that is hashed.  It's actually a script, of 0x00 (DUP_0) and then a length of the public key hash (0x14).

So, to fix the above code, if the address generation code is changed to:

```<code>std::string getWalletAddress(const std::vector<uint8_t>& public_key, uint8_t id, bool is_p2sh)
{
    std::vector<uint8_t> addr_hash = SHA256_Hash(key);
    std::vector<uint8_t> addr_ripe = RipeMD160_Hash(addr_hash);
    if (is_p2sh)
    {
        addr_ripe.insert(addr_ripe.begin(), { 0x00, static_cast<uint8_t>(addr_ripe.size()) });
        addr_hash = SHA256_Hash(addr_ripe);
        addr_ripe = RipeMD160_Hash(addr_ripe);
    }
    addr_ripe.insert(addr_ripe.begin(), id);
    addr_hash = SHA256_Hash(SHA256_Hash(addr_ripe));
    addr_ripe.insert(addr_ripe.end(), addr_hash.begin(), addr_hash.begin() + sizeof(uint32_t));
    return base58Encode(addr_ripe);
}

// This will now work for both p2pkh addresses and p2wpkh-p2sh addresses

getWalletAddress(public_key, LTC_TESTNET, true);  // Produces: QYyWqgyWSm1AJWph32GnyY7eamG1wUDruk
</code>```

Body:
Sorry if this is a bit misleading, but I was actually doing this with Litecoin as opposed to Bitcoin, but the algorithm is exactly the same and I'm pretty sure that the answer will be too.  In fact, am almost certain when I look, there's going to be the same problem with Bitcoin too.  I'm having difficulty generating the correct SegWit address for a given public key as below:

Litecoin address generation (which is the same as Bitcoin)

I take a compressed public key:
03861b83752e0c47cac36fc5980ae8956f41f6d9792a51f68a6bd5f66cc7364b48

SHA256 on the public key.

RipeMD160 the result from 2.

Add a prefix byte, in my case, 0x3a which is the LTC_TESTNET

Double SHA256 result of 4 and add the first four bytes of this result to the end of the RipeMD160.

Finally, Base58 encode.

All seems dandy, right?  Out pops the SegWit address:  QhQxSZvVDWr3JvoKsYVC6BBW3DqkGhesrF

However, I'm pretty sure this address isn't right.  When I import the private key into Electrum-LTC as a (p2wpkh-p2sh:) the address it generates for this private key is:  QYyWqgyWSm1AJWph32GnyY7eamG1wUDruk

Now I believe that Electrum-LTC is right and there's something that I'm missing when generating a SegWit address and there's more to address generation than just changing the network prefix.
My Public Key Hash is:

e444ac77800cdf904b928fc4642ab6fb6d4d696c

and Electrum-LTC's Public Key Hash is:

87b3e5bf5b2a1381e6549020d245e45b9ac76c82

Since the values are so VERY different, it suggests that the initial SHA256 is not hashing just the public key alone and that I'm missing something.  I'm about out of ideas and am hoping someone has the answer and about the only thing I can find in the source, in the chainparams.cpp was this:

base58Prefixes[EXT_PUBLIC_KEY] = {0x04, 0x88, 0xB2, 0x1E};

Anyone know what I might be doing wrong?

Update - Someone asked for the code - so here it is

#include <openssl/sha.h>
#include <openssl/ripemd.h>
#include <cstdint>
#include <iostream>
#include <vector>

std::string base58Encode(const std::vector<uint8_t>& data)
{
    const uint8_t mapping[] = {
      '1', '2', '3', '4', '5', '6', '7', '8',
      '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
      'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q',
      'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
      'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
      'h', 'i', 'j', 'k', 'm', 'n', 'o', 'p',
      'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
      'y', 'z' };

    std::vector<uint8_t> digits((data.size() * 137) / 100);
    size_t digitslen = 1;
    for (size_t i = 0; i < data.size(); i++)
    {
        uint32_t carry = static_cast<uint32_t>(data[i]);
        for (size_t j = 0; j < digitslen; j++)
        {
            carry = carry + static_cast<uint32_t>(digits[j] << 8);
            digits[j] = static_cast<uint8_t>(carry % 58);
            carry /= 58;
        }
        for (; carry; carry /= 58)
            digits[digitslen++] = static_cast<uint8_t>(carry % 58);
    }
    std::string result;
    for (size_t i = 0; i < data.size() && !data[i]; i++)
        result.push_back(mapping[0]);
    for (size_t i = 0; i < digitslen; i++)
        result.push_back(mapping[digits[digitslen - 1 - i]]);
    return result;
}

std::vector<uint8_t> SHA256_Hash(const std::vector<uint8_t>& data)
{
    std::vector<uint8_t> SHA256_Digest(SHA256_DIGEST_LENGTH);
    SHA256_CTX ctx;
    SHA256_Init(&ctx);
    SHA256_Update(&ctx, data.data(), data.size());
    SHA256_Final(SHA256_Digest.data(), &ctx);
    return SHA256_Digest;
}

std::vector<uint8_t> RipeMD160_Hash(const std::vector<uint8_t>& data)
{
    std::vector<uint8_t> RipeMD160_Digest(RIPEMD160_DIGEST_LENGTH);
    RIPEMD160_CTX ctx;
    RIPEMD160_Init(&ctx);
    RIPEMD160_Update(&ctx, data.data(), data.size());
    RIPEMD160_Final(RipeMD160_Digest.data(), &ctx);
    return RipeMD160_Digest;
}

std::string getWalletAddress(const std::vector<uint8_t>& public_key, uint8_t id)
{
    std::vector<uint8_t> addr_hash = SHA256_Hash(key);
    std::vector<uint8_t> addr_ripe = RipeMD160_Hash(addr_hash);
    addr_ripe.insert(addr_ripe.begin(), id);
    addr_hash = SHA256_Hash(SHA256_Hash(addr_ripe));
    addr_ripe.insert(addr_ripe.end(), addr_hash.begin(), addr_hash.begin() + sizeof(uint32_t));
    return base58Encode(addr_ripe);
}

int main(int argc, char** argv)
{
    const uint8_t LTC_TESTNET = 0x3a;

    std::vector<uint8_t> public_key{
        0x03, 0x86, 0x1b, 0x83, 0x75, 0x2e, 0x0c, 0x47, 0xca, 0xc3, 0x6f, 0xc5, 0x98, 0x0a, 0xe8, 0x95,
        0x6f, 0x41, 0xf6, 0xd9, 0x79, 0x2a, 0x51, 0xf6, 0x8a, 0x6b, 0xd5, 0xf6, 0x6c, 0xc7, 0x36, 0x4b, 0x48};

    std::cout << "Wallet Address: " << getWalletAddress(public_key, LTC_TESTNET) << std::endl;
    // The above ouputs:  QhQxSZvVDWr3JvoKsYVC6BBW3DqkGhesrF
    // But it should be:  QYyWqgyWSm1AJWph32GnyY7eamG1wUDruk
    return 0;
}

Body:
Have finally figured this one out...  When calculating a p2wpkh-p2sh address, it's not just the prefix of the address that is different.  In actual fact, I found the answer to the above problem here:  https://bitcoin.stackexchange.com/questions/72775/is-it-possible-to-convert-an-address-from-p2pkh-to-p2sh  (although it is quite cryptic in how it is explained).

The above code in my question will work quite happily for p2pkh address generation for Bitcoin/Litecoin etc, but when generating a Q (for Litecoin), 2 (for Bitcoin), it won't work because it's not just the public key that is hashed.  It's actually a script, of 0x00 (DUP_0) and then a length of the public key hash (0x14).

So, to fix the above code, if the address generation code is changed to:

std::string getWalletAddress(const std::vector<uint8_t>& public_key, uint8_t id, bool is_p2sh)
{
    std::vector<uint8_t> addr_hash = SHA256_Hash(key);
    std::vector<uint8_t> addr_ripe = RipeMD160_Hash(addr_hash);
    if (is_p2sh)
    {
        addr_ripe.insert(addr_ripe.begin(), { 0x00, static_cast<uint8_t>(addr_ripe.size()) });
        addr_hash = SHA256_Hash(addr_ripe);
        addr_ripe = RipeMD160_Hash(addr_ripe);
    }
    addr_ripe.insert(addr_ripe.begin(), id);
    addr_hash = SHA256_Hash(SHA256_Hash(addr_ripe));
    addr_ripe.insert(addr_ripe.end(), addr_hash.begin(), addr_hash.begin() + sizeof(uint32_t));
    return base58Encode(addr_ripe);
}

// This will now work for both p2pkh addresses and p2wpkh-p2sh addresses

getWalletAddress(public_key, LTC_TESTNET, true);  // Produces: QYyWqgyWSm1AJWph32GnyY7eamG1wUDruk


问:
How to debug ingress-controller connections with a single IP by ConfigMap
We are trying to edit our ingress-nginx.yml to make ingress-controllers pods debug traffic coming from a specific source IP.
Our setup is:

Kubernetes v1.13

Ingress-Controller v0.24.1

From NGINX and Kubernetes DOCs it appears there is no very easy way to debug traffic from a single ip (you cannot edit the nginx config directly). So, we would like to add the debug_connection directive to appear like this:

```<code>error_log /path/to/log;
...
events {
    debug_connection 192.168.1.1;
}
</code>```

The correct way to do it shall be through CustomAnnotations in a ConfigMap + a new ingress to enable the CustomAnnotation, so we tried this:

```<code>kind: ConfigMap
apiVersion: v1
metadata:
  name: nginx-configuration
  namespace: ingress-nginx
  labels:
    app: ingress-nginx
data:
ingress-template: |
    #Creating the custom annotation to make debug_connection on/off
    {if index $.Ingress.Annotations "custom.nginx.org/debug_connection"}
    {$ip := index $.Ingress.Annotations "custom.nginx.org/ip"}
    {end}

    {range $events := .Events}
    events {
      # handling custom.nginx.org/debug_connection
      {if index $.Ingress.Annotations "custom.nginx.org/debug_connection"}
      {end}
</code>```

And:

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: debugenabler
  annotations:
    kubernetes.io/ingress.class: "nginx"
    custom.nginx.org/debug_connection: "on"
    custom.nginx.org/ip: "192.168.1.1"
spec:
  rules:
  - host: "ourhostname"
    http:
      paths:
      - path: /tea
        backend:
          serviceName: tea-svc
          servicePort: 80
      - path: /coffee
        backend:
          serviceName: coffee-svc
          servicePort: 80
</code>```

We applied ingress-nginx.yml with no errors. We see new lines in the nginx conf:

```<code>location /coffee {

            set $namespace      "test";
            set $ingress_name   "debugenabler";
            set $service_name   "coffee-svc";
            set $service_port   "80";
            set $location_path  "/coffee";

            rewrite_by_lua_block {
                lua_ingress.rewrite({
                    force_ssl_redirect = true,
                    use_port_in_redirects = false,
                })
                balancer.rewrite()
</code>```

But still nothing as regard the debug_connection in the events block:

```<code>events {
    multi_accept        on;
    worker_connections  16384;
    use                 epoll;
}
</code>```

How to insert debug_connection in the events context ?

答:
For those who may face similar challenges, I actually managed to do it by:

Creating a ConfigMap with a new ingress-controller template file (nginx.tmpl) containing the debug_connection line (double check your ingress-controller version here, the file changes dramatically)

Creating a Volume which links at the Configmap (specifying Volume and Volumemount)

Creating a InitContainer which copy the content of the volume inside the /etc/nginx/template (this was needed to overcome probably permission-related issues) before the container start.

For point 2 and 3 you can add the relevant code at the end of a deployment or a pod code, I share an example:

```<code>     volumes:
        - name: nginxconf2
          configMap:
            name: nginxconf2
            items:
            - key: nginx.tmpl
              path: nginx.tmpl
      initContainers:
      - name: copy-configs
        image: {{ kubernetes.ingress_nginx.image }}
        volumeMounts:
        - mountPath: /nginx
          name: nginxconf2
        command: ['sh', '-c', 'cp -R /nginx/ /etc/nginx/template/']
</code>```

Body:
We are trying to edit our ingress-nginx.yml to make ingress-controllers pods debug traffic coming from a specific source IP.
Our setup is:

Kubernetes v1.13

Ingress-Controller v0.24.1

From NGINX and Kubernetes DOCs it appears there is no very easy way to debug traffic from a single ip (you cannot edit the nginx config directly). So, we would like to add the debug_connection directive to appear like this:

error_log /path/to/log;
...
events {
    debug_connection 192.168.1.1;
}

The correct way to do it shall be through CustomAnnotations in a ConfigMap + a new ingress to enable the CustomAnnotation, so we tried this:

kind: ConfigMap
apiVersion: v1
metadata:
  name: nginx-configuration
  namespace: ingress-nginx
  labels:
    app: ingress-nginx
data:
ingress-template: |
    #Creating the custom annotation to make debug_connection on/off
    {if index $.Ingress.Annotations "custom.nginx.org/debug_connection"}
    {$ip := index $.Ingress.Annotations "custom.nginx.org/ip"}
    {end}

    {range $events := .Events}
    events {
      # handling custom.nginx.org/debug_connection
      {if index $.Ingress.Annotations "custom.nginx.org/debug_connection"}
      {end}

And:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: debugenabler
  annotations:
    kubernetes.io/ingress.class: "nginx"
    custom.nginx.org/debug_connection: "on"
    custom.nginx.org/ip: "192.168.1.1"
spec:
  rules:
  - host: "ourhostname"
    http:
      paths:
      - path: /tea
        backend:
          serviceName: tea-svc
          servicePort: 80
      - path: /coffee
        backend:
          serviceName: coffee-svc
          servicePort: 80

We applied ingress-nginx.yml with no errors. We see new lines in the nginx conf:

location /coffee {

            set $namespace      "test";
            set $ingress_name   "debugenabler";
            set $service_name   "coffee-svc";
            set $service_port   "80";
            set $location_path  "/coffee";

            rewrite_by_lua_block {
                lua_ingress.rewrite({
                    force_ssl_redirect = true,
                    use_port_in_redirects = false,
                })
                balancer.rewrite()

But still nothing as regard the debug_connection in the events block:

events {
    multi_accept        on;
    worker_connections  16384;
    use                 epoll;
}

How to insert debug_connection in the events context ?

Body:
For those who may face similar challenges, I actually managed to do it by:

Creating a ConfigMap with a new ingress-controller template file (nginx.tmpl) containing the debug_connection line (double check your ingress-controller version here, the file changes dramatically)

Creating a Volume which links at the Configmap (specifying Volume and Volumemount)

Creating a InitContainer which copy the content of the volume inside the /etc/nginx/template (this was needed to overcome probably permission-related issues) before the container start.

For point 2 and 3 you can add the relevant code at the end of a deployment or a pod code, I share an example:

     volumes:
        - name: nginxconf2
          configMap:
            name: nginxconf2
            items:
            - key: nginx.tmpl
              path: nginx.tmpl
      initContainers:
      - name: copy-configs
        image: {{ kubernetes.ingress_nginx.image }}
        volumeMounts:
        - mountPath: /nginx
          name: nginxconf2
        command: ['sh', '-c', 'cp -R /nginx/ /etc/nginx/template/']


问:
How to calculate t and p values with t-test approach in python?
I have a dataset that measures the expression levels of large numbers of genes simultaneously.

Here is some part of my data frame

Column 0 refers to gene types and other columns are patient samples. Samples in the datasets represent patients. For each patient, 7070 genes expressions (values) are measured in order to classify the patient’s disease into one of the following cases: EPD, JPA, MED, MGL, RHB.

I would like to generate subsets with top 2,4,6,8,10,12,15,20,25, and 30 top genes
with the highest absolute T-value for each class.

I try to use scipy.stats.ttest_ind for every possible pair.

```<code>def calculate_t():
t_res = []
for cls in range(np.max(classes)):
    samp = np.where(classes == cls)[0]
    for gene in range(train.shape[1]):
        for other_genes in range(gene, train.shape[1]):
            t_res.append(ttest_ind(train[samp, gene], train[samp, other_genes])[:])

return t_res
</code>```

I didn't continue because I thought it would take too long.

I would appreciate it if anyone has any ideas. Have a nice day.

答:
I'll try not to get to stats-heavy in my answer since Stack Overflow is meant to focus of the technical issues, but there are pretty large theoretical problems with carrying out multiple-tests. In short, a p-value of 0.05 is normally required for acceptance, meaning the chance of it occurring if the null hypothesis is true, is only 5%. If you carry out lots of similar tests, the chance that one of them will reject the null hypothesis becomes much more likely.

Think of it as if you where rolling a dice to get a six- there's only a one in six chance for each roll, but if you roll a hundred times, it's more or less guaranteed that lots of your rolls will be six (even though this is unlikely in a given through).

Rather than optimising your code to carry out multiple t-tests, it might be worth looking at alternative tests for significance that are designed to work across multiple comparisons.

Scipy has an ANOVA test you can use for significance across multiple comparisons, like so:

```<code>stats.f_oneway(df['sample_one'], df['sample_two'], df['sample_three'])
</code>```

Although this will just give you the F and P value of the overall test. If you want to break down into more detail, it's probably worth looking into other test such as a Tukey Test which is supported by the statsmodels module. You can find a helpful guide on carrying it out here.

Body:
I have a dataset that measures the expression levels of large numbers of genes simultaneously.

Here is some part of my data frame

Column 0 refers to gene types and other columns are patient samples. Samples in the datasets represent patients. For each patient, 7070 genes expressions (values) are measured in order to classify the patient’s disease into one of the following cases: EPD, JPA, MED, MGL, RHB.

I would like to generate subsets with top 2,4,6,8,10,12,15,20,25, and 30 top genes
with the highest absolute T-value for each class.

I try to use scipy.stats.ttest_ind for every possible pair.

def calculate_t():
t_res = []
for cls in range(np.max(classes)):
    samp = np.where(classes == cls)[0]
    for gene in range(train.shape[1]):
        for other_genes in range(gene, train.shape[1]):
            t_res.append(ttest_ind(train[samp, gene], train[samp, other_genes])[:])

return t_res

I didn't continue because I thought it would take too long.

I would appreciate it if anyone has any ideas. Have a nice day.

Body:
I'll try not to get to stats-heavy in my answer since Stack Overflow is meant to focus of the technical issues, but there are pretty large theoretical problems with carrying out multiple-tests. In short, a p-value of 0.05 is normally required for acceptance, meaning the chance of it occurring if the null hypothesis is true, is only 5%. If you carry out lots of similar tests, the chance that one of them will reject the null hypothesis becomes much more likely.

Think of it as if you where rolling a dice to get a six- there's only a one in six chance for each roll, but if you roll a hundred times, it's more or less guaranteed that lots of your rolls will be six (even though this is unlikely in a given through).

Rather than optimising your code to carry out multiple t-tests, it might be worth looking at alternative tests for significance that are designed to work across multiple comparisons.

Scipy has an ANOVA test you can use for significance across multiple comparisons, like so:

stats.f_oneway(df['sample_one'], df['sample_two'], df['sample_three'])

Although this will just give you the F and P value of the overall test. If you want to break down into more detail, it's probably worth looking into other test such as a Tukey Test which is supported by the statsmodels module. You can find a helpful guide on carrying it out here.


问:
Zoom Api - I can't update a meeting
I am trying to update a meeting using Zoom API but I can't get it to work. I'm trying to do a PATCH request using eleague oauth2 client like this:

```<code>require '../vendor/autoload.php';
require_once '../config.php';

$id = $_POST['id'];
$topic = $_POST['topic'];
$type = $_POST['type'];
$start_time = $_POST['start_time'];
$duration = $_POST['duration'];
$agenda = $_POST['agenda'];

$params = array(
        'topic' => $topic,
        'type' => $type,
        'start_time' => $start_time,
        'duration' => $duration,
        'agenda' => $agenda,
        'password' => '123456'
);

$provider = new \League\OAuth2\Client\Provider\GenericProvider([
    'clientId'                => CONEXAO_API['clientId'],
    'clientSecret'            => CONEXAO_API['clientSecret'],
    'redirectUri'             => CONEXAO_API['redirect_url'],
    'urlAuthorize'            => 'https://zoom.us/oauth/authorize',
    'urlAccessToken'          => 'https://zoom.us/oauth/token',
    'urlResourceOwnerDetails' => 'https://api.zoom.us/v2/users/me'
]);

$options['body'] = json_encode( $params );
$options['headers']['Content-Type'] = 'application/json';
$options['headers']['Accept'] = 'application/json';

$request = $provider->getAuthenticatedRequest( 'PATCH',
        'https://api.zoom.us/v2/meetings/'.$id,
        unserialize($_SESSION['token']),
        $options
);

$retorno =  $provider->getParsedResponse($request);

var_dump($retorno);
</code>```

I'm getting an empty response, and I'm not sure what is missing. Can anyone help me?

答: basically the response given by the api is blank or just meeting updated which isn't in json format. So in case you want to check whether its working go to zoom meeting panel and open the meeting which you are updating using api and run the api and check the meeting is updated in zoom meeting panel.</p>

Title: Zoom Api - I can't update a meeting

Body:
I am trying to update a meeting using Zoom API but I can't get it to work. I'm trying to do a PATCH request using eleague oauth2 client like this:

require '../vendor/autoload.php';
require_once '../config.php';

$id = $_POST['id'];
$topic = $_POST['topic'];
$type = $_POST['type'];
$start_time = $_POST['start_time'];
$duration = $_POST['duration'];
$agenda = $_POST['agenda'];

$params = array(
        'topic' => $topic,
        'type' => $type,
        'start_time' => $start_time,
        'duration' => $duration,
        'agenda' => $agenda,
        'password' => '123456'
);

$provider = new \League\OAuth2\Client\Provider\GenericProvider([
    'clientId'                => CONEXAO_API['clientId'],
    'clientSecret'            => CONEXAO_API['clientSecret'],
    'redirectUri'             => CONEXAO_API['redirect_url'],
    'urlAuthorize'            => 'https://zoom.us/oauth/authorize',
    'urlAccessToken'          => 'https://zoom.us/oauth/token',
    'urlResourceOwnerDetails' => 'https://api.zoom.us/v2/users/me'
]);

$options['body'] = json_encode( $params );
$options['headers']['Content-Type'] = 'application/json';
$options['headers']['Accept'] = 'application/json';

$request = $provider->getAuthenticatedRequest( 'PATCH',
        'https://api.zoom.us/v2/meetings/'.$id,
        unserialize($_SESSION['token']),
        $options
);

$retorno =  $provider->getParsedResponse($request);

var_dump($retorno);

I'm getting an empty response, and I'm not sure what is missing. Can anyone help me?


问:
php intellisense not working with custom file associations
I faced a weird scenario and I seek your help. I made a custom file association

```<code>"files.associations": {
"*.dws": "PHP"
}
</code>```

so my ".dws" files are mapped as PHP. but my vscode extensions such as PHP IntelliSense is not working in dws file but working fine with PHP file. I researched but not able to find a solution to this.

Thank you in advance

答:
Note that casing matters for exact identifier matching Uppercase Markdown cannot be equal to the lowercase markdown

So you have to use this:

```<code>"files.associations": {
  "*.dws": "php"                     <--- Do not use Uppercase PHP
}
</code>```

Body:
I faced a weird scenario and I seek your help. I made a custom file association

"files.associations": {
"*.dws": "PHP"
}

so my ".dws" files are mapped as PHP. but my vscode extensions such as PHP IntelliSense is not working in dws file but working fine with PHP file. I researched but not able to find a solution to this.

Thank you in advance

Body:
Note that casing matters for exact identifier matching Uppercase Markdown cannot be equal to the lowercase markdown

So you have to use this:

"files.associations": {
  "*.dws": "php"                     <--- Do not use Uppercase PHP
}


问:
React onMouseEnter is blocking onClick
I have a button that sends a prefetch request using graphQL Apollo Client when a user hovers it.

The issue is the onClick event is blocked for a few ms. Can someone please explain why seperate events are clashing like this. I can't think of any reason why my onclick event is not firing while the request is in flight as its asynchronous.

```<code><div
   role="button"
   key={shortId()}
   onMouseEnter={prefetch(value.value)}
   onClick={onToggle(id, value.value)}
   className="FilterGroup__item"
>
   {renderWidget({value, selected})}
    <span className="FilterGroup__item__count">{value.count}</span>
</div>
</code>```

The function returned by prefetch is:

```<code>    const [searchPrefetch] = useLazyQuery(searchQuery, {
        returnPartialData: true
    });

    const sendSearchPrefetch = (additionalParameters?: IAdditionalSearchParameters) => {
        searchPrefetch({
            variables: getRequestParameters(additionalParameters)
        });
    };

const handlePrefetch = useCallback(
        debounce(async (additionalFacets?: IAdditionalSearchParameters) => {
            sendSearchPrefetch(additionalFacets);
        }, SEARCH_DEBOUNCE_TIMER_MS),
        []
    );

  const prefetch = (filter: string) => (value: string) => () => {
        handlePrefetch({filters: {[filter]: value}});
    };
</code>```

答:
This is similar issue to this post. It is not good idea to bind handlers to both the click and mouseenter. So, I would suggest you to update the state instead of handling events. After we get the updated state we can call the handler. Here's a pseudo code to demonstrate that:</p>

```<code>const [prefetch, setPrefetch] = useState('')
const [toggle, setToggle] = useState({})

onMouseEnter={setPrefetch(value)}
onClick={setToggle({id,value})}

useEffect(() => { // you may use memoized effect
  if (prefetch) {
    prefetchFunc(prefetch)
  }
  if (toggle) { // you may check additional detail
    toggleFunc(toggle)
  }
}, [prefetch, toggle])
</code>```

Title: React onMouseEnter is blocking onClick

Body:
I have a button that sends a prefetch request using graphQL Apollo Client when a user hovers it.

The issue is the onClick event is blocked for a few ms. Can someone please explain why seperate events are clashing like this. I can't think of any reason why my onclick event is not firing while the request is in flight as its asynchronous.

   {renderWidget({value, selected})}
    {value.count}

The function returned by prefetch is:

    const [searchPrefetch] = useLazyQuery(searchQuery, {
        returnPartialData: true
    });

    const sendSearchPrefetch = (additionalParameters?: IAdditionalSearchParameters) => {
        searchPrefetch({
            variables: getRequestParameters(additionalParameters)
        });
    };

const handlePrefetch = useCallback(
        debounce(async (additionalFacets?: IAdditionalSearchParameters) => {
            sendSearchPrefetch(additionalFacets);
        }, SEARCH_DEBOUNCE_TIMER_MS),
        []
    );

  const prefetch = (filter: string) => (value: string) => () => {
        handlePrefetch({filters: {[filter]: value}});
    };

Body:
This is similar issue to this post. It is not good idea to bind handlers to both the click and mouseenter. So, I would suggest you to update the state instead of handling events. After we get the updated state we can call the handler. Here's a pseudo code to demonstrate that:

const [prefetch, setPrefetch] = useState('')
const [toggle, setToggle] = useState({})

onMouseEnter={setPrefetch(value)}
onClick={setToggle({id,value})}

useEffect(() => { // you may use memoized effect
  if (prefetch) {
    prefetchFunc(prefetch)
  }
  if (toggle) { // you may check additional detail
    toggleFunc(toggle)
  }
}, [prefetch, toggle])


问:
what is the fastest way to toggle images by class
i have a list of image

```<code><img class="onOff" src="/Content/Images/on.png" />
<img class="onOff" src="/Content/Images/on.png" />
<img class="onOff" src="/Content/Images/on.png" />
<img class="onOff" src="/Content/Images/on.png" />
<img class="onOff" src="/Content/Images/on.png" />
</code>```

and i want to change the source of all of the images (by using the class selector .onOff so each of the above images changes to this:

```<code><img class="onOff" src="/Content/Images/off.png" />
</code>```

what is the most efficient way to changing all of these images through jquery?

答:
Prefix the class selector with the tag:

```<code>$('img.onOff').attr('src', '/Content/Images/off.png');
</code>```

However, if you've got some context (such as a container div) you can add that too to improve performance:

```<code> $('img.onOff', '#containerDiv').attr('src', '/Content/Images/off.png');
</code>```

If this is just to change the image though, take a look at CSS Sprites.

Body:
i have a list of image

and i want to change the source of all of the images (by using the class selector .onOff so each of the above images changes to this:

what is the most efficient way to changing all of these images through jquery?

Body:
Prefix the class selector with the tag:

$('img.onOff').attr('src', '/Content/Images/off.png');

However, if you've got some context (such as a container div) you can add that too to improve performance:

 $('img.onOff', '#containerDiv').attr('src', '/Content/Images/off.png');

If this is just to change the image though, take a look at CSS Sprites.


问:
Select and get special svg element by PHP script
Need to get and modify first polygon inside the group g with special (dynamic) id inside SVG file by php script.
Couldn't find this element, using DOMDocument() and DOMXPath. Please, help

PHP:

```<code>$svg = file_get_contents($svgPath);
$doc = new DOMDocument();
$doc->loadXML($svg);
$doc->preserveWhiteSpace = false;
$xpath = new DOMXPath($doc);
$xpath->registerNamespace('svg','http://www.w3.org/2000/svg');
**$curPolygon = $xpath -> query("//svg:g[@id='fl_1']/polygon[0]");**
if ($curPolygon ) {
  $curPolygon [0]->setAttribute('fill', '#ae8f72');
}
$svg = $doc->saveXML($doc);
echo $svg;
</code>```

SVG:

```<code><svg>
...
<g id="Flats">

    ...

    <g id="fl_1">
        <polygon fill="none" points="0,0 436.5,0 436.5,197.7 257,197.7 257,267.1 196.9,267.1 196.9,293.9 0,293.9"/>
        <g> <rect x="209.9" y="84.8" fill="#AE8E72" width="56.3" height="22.1"/> </g>
        <text transform="matrix(1 0 0 1 214.1091 101.5043)"><tspan x="0" y="0">4</tspan></text>
        <text transform="matrix(1 0 0 1 235.5047 101.5042)">132,0</text>
    </g>

    <g id="fl_2">
        <polygon fill="none" points="404.5,388.7 404.5,390 251.7,390 251.7,192.3 436.5,192.3 436.5,388.7"/>
        <g> <rect x="327.7" y="278.4" fill="#AE8E72" width="56.3" height="22.1"/> </g>
        <text transform="matrix(1 0 0 1 331.8962 295.0608)"><tspan x="0" y="0">1</tspan></text>
        <text transform="matrix(1 0 0 1 354.9925 295.0607)">40,7</text>
    </g>

    ...
</g>
...
</svg>
</code>```

Result of var_dump($q) is object(DOMNodeList)#6 (1) { ["length"]=> int(0) }

答:
A couple of things from your code.  The first is that you don't seem to load the document...

```<code>$doc->loadXML($svg);
</code>```

the second part is the XPath expression.  I think if you have the namespace svg as the default namespace, then you would need to apply this to both parts of the XPath expression.  Also XPath arrays start at 1, so the expression should be

```<code>$curPolygon = $xpath -> query("//svg:g[@id='fl_1']/svg:polygon[1]");
</code>```

Body:
Need to get and modify first polygon inside the group g with special (dynamic) id inside SVG file by php script.
Couldn't find this element, using DOMDocument() and DOMXPath. Please, help

PHP:

$svg = file_get_contents($svgPath);
$doc = new DOMDocument();
$doc->loadXML($svg);
$doc->preserveWhiteSpace = false;
$xpath = new DOMXPath($doc);
$xpath->registerNamespace('svg','http://www.w3.org/2000/svg');
**$curPolygon = $xpath -> query("//svg:g[@id='fl_1']/polygon[0]");**
if ($curPolygon ) {
  $curPolygon [0]->setAttribute('fill', '#ae8f72');
}
$svg = $doc->saveXML($doc);
echo $svg;

SVG:

<svg>
...
<g id="Flats">

    ...

    <g id="fl_1">
        <polygon fill="none" points="0,0 436.5,0 436.5,197.7 257,197.7 257,267.1 196.9,267.1 196.9,293.9 0,293.9"/>
        <g> <rect x="209.9" y="84.8" fill="#AE8E72" width="56.3" height="22.1"/> </g>
        <text transform="matrix(1 0 0 1 214.1091 101.5043)"><tspan x="0" y="0">4</tspan></text>
        <text transform="matrix(1 0 0 1 235.5047 101.5042)">132,0</text>
    </g>

    <g id="fl_2">
        <polygon fill="none" points="404.5,388.7 404.5,390 251.7,390 251.7,192.3 436.5,192.3 436.5,388.7"/>
        <g> <rect x="327.7" y="278.4" fill="#AE8E72" width="56.3" height="22.1"/> </g>
        <text transform="matrix(1 0 0 1 331.8962 295.0608)"><tspan x="0" y="0">1</tspan></text>
        <text transform="matrix(1 0 0 1 354.9925 295.0607)">40,7</text>
    </g>

    ...
</g>
...
</svg>

Result of var_dump($q) is object(DOMNodeList)#6 (1) { ["length"]=> int(0) }

Body:
A couple of things from your code.  The first is that you don't seem to load the document...

$doc->loadXML($svg);

the second part is the XPath expression.  I think if you have the namespace svg as the default namespace, then you would need to apply this to both parts of the XPath expression.  Also XPath arrays start at 1, so the expression should be

$curPolygon = $xpath -> query("//svg:g[@id='fl_1']/svg:polygon[1]");


问:
ARKit capturedImage and snapshot are not same
I am trying to get an image without 3D models and 3D models at the same time.

I use

session.currentFrame!.capturedImage

and then I take a snapshot using

sceneView.snapshot()

when both are done. the images look different, how do I get same image twice, one with and without 3D content. preferably in high res.

taken on iPhone 7s plus. so I am guessing the capturedImage and snapshot are using different lens?

Session Captured Image

Scene Session Snapshot

If you see the images. the captured image cropped is not same. somehow the focal length or something is different in the snapshot.

答:
Ask a specific question ;).

The .snapshot() is a capture of the sceneView with takes the whole screen, which is a different aspect ratio to the image. if you superpose your images you can see how they match.

so if you want the same, you need to crop the capturedImage yourself.


问:
Is it possible to have 2 network plugins for the kubernetes cluster?
while going through the network plugin in Kubernetes I end up with a doubt that it is possible to have two network plugin in the cluster created  with kubeadm tool  or can we have alternate plugin so that if one gets any issue it can automatically use another.  can  someone explain me ?</p>

答:
You can have a combination of different CNIs for different functionality such as calico for policy and flannel for networking. But you cannot have two different CNIs performing exact same functionality in the same cluster simultaneously.

https://docs.projectcalico.org/getting-started/kubernetes/flannel/flannel


问:
How to get radio button value as a number
Is there a way to get the value of the radio button as an integer?
I'm submitting a form that but the value that I'm getting from radio buttons is always a string, I've tried many solutions but none of them work.

```<code>  <div class="form-check form-check-inline">
          <input class="form-check-input" formControlName="note" type="radio"  value='3' >
          <label class="form-check-label" for="inlineRadio3">Advanced</label>
        </div>

 <div class="form-check form-check-inline">
          <input class="form-check-input" formControlName="note" type="radio"  value=3 >
          <label class="form-check-label" for="inlineRadio3">Advanced</label>
        </div>
</code>```

here is what i get when i submit the form :

in order to the web API works, I need to have like this note : 3, please help.
[UPDATE]

here's my how i'm submitting the form:

```<code>this.Myser.AddAll(this.rateform.value.lstrates).subscribe(data => console.log(data) );
</code>```

and this is how i declared my form :

```<code>this.rateform = this.fb.group({
      lstrates: this.fb.array([
        this.fb.group({
          fieldId: [''],
          memberId: [''],
          note: [''],
          fieldName:['']
        }),
      ]),
    });
</code>```

but the problem is , the note attribut must be a number. so i dont know how to get it from the radio button as integer, should i create another list and convert it to integer ? or there is a better way ?

答:
You need to use [value]="3" and skip value="3" in this case, it allows to pass any type as a value including objects etc.

See: angular doc binding syntax

Also you might import FormsModule if it wasn't.

Demo: https://stackblitz.com/edit/angular-ivy-ll3ckc?file=src%2Fapp%2Fapp.component.html

Body:
Is there a way to get the value of the radio button as an integer?
I'm submitting a form that but the value that I'm getting from radio buttons is always a string, I've tried many solutions but none of them work.

          <input class="form-check-input" formControlName="note" type="radio"  value='3' >
          Advanced

          <input class="form-check-input" formControlName="note" type="radio"  value=3 >
          Advanced

here is what i get when i submit the form :

in order to the web API works, I need to have like this note : 3, please help.
[UPDATE]

here's my how i'm submitting the form:

this.Myser.AddAll(this.rateform.value.lstrates).subscribe(data => console.log(data) );

and this is how i declared my form :

this.rateform = this.fb.group({
      lstrates: this.fb.array([
        this.fb.group({
          fieldId: [''],
          memberId: [''],
          note: [''],
          fieldName:['']
        }),
      ]),
    });

but the problem is , the note attribut must be a number. so i dont know how to get it from the radio button as integer, should i create another list and convert it to integer ? or there is a better way ?


问:
How I can calculate MAPE in r with actual e predicted values?
I'm trying to calculare MAPE in R but I have any problems.
I have a dataset of food retails from 2017 to 2020 and I split this into training set e and test set. Now, after to calculate forecast value in this way:

```<code>tsData_train <- ts(t1[,3], start= 2017, end= 2019, frequency=12)
tsData_test <- ts(t2[,3], start=2019, end= 2020, frequency=12)

#choose best model with arima

a1 <-auto.arima(tsData_train, max.d = 1, D=1)
fitA <- arima(tsData_train, method="ML")
pred <- predict(fitA,n.ahead = 4)
futurVal <- forecast(a1 ,h=24)`
</code>```

Please, could you tell me if the code is correct. I would like to calculate MAPE manually, my insigh is:

abs((actual-predicted)/predicted)

but I don't know which are actual and predicted.
Help me, please.

答:
The MAPE is the Mean Absolute Persentage Error so it lacks a mean. Moreover :

```<code>MAPE = mean(abs((Y - Yhat)/Y))
</code>```

With Y is actual or observed values and Yhat is the predicted values.

Body:
I'm trying to calculare MAPE in R but I have any problems.
I have a dataset of food retails from 2017 to 2020 and I split this into training set e and test set. Now, after to calculate forecast value in this way:

tsData_train <- ts(t1[,3], start= 2017, end= 2019, frequency=12)
tsData_test <- ts(t2[,3], start=2019, end= 2020, frequency=12)

#choose best model with arima

a1 <-auto.arima(tsData_train, max.d = 1, D=1)
fitA <- arima(tsData_train, method="ML")
pred <- predict(fitA,n.ahead = 4)
futurVal <- forecast(a1 ,h=24)`

Please, could you tell me if the code is correct. I would like to calculate MAPE manually, my insigh is:

abs((actual-predicted)/predicted)

but I don't know which are actual and predicted.
Help me, please.

Body:
The MAPE is the Mean Absolute Persentage Error so it lacks a mean. Moreover :

MAPE = mean(abs((Y - Yhat)/Y))

With Y is actual or observed values and Yhat is the predicted values.


问:
Setting a variable via echo somtimes adds a random ' at the end
I have a bash script with the following functionality:

```<code># usage: setOutput <name> <value>
function setOutput {
  echo "##vso[task.setvariable variable=$1]$2"
}

setOutput environment "dev"
</code>```

This normally sets the variable correctly as ENVIRONMENT=dev - however, sometimes this randomly appends a ' at the end, i.e. ENVIRONMENT=dev'

I tried re-running the same commit on the pipeline multiple times, and sometimes it works, sometimes it doesn't. Any ideas?

答:
I tested it with your sample, it can be displayed normally .

You can try to remove the double quotes of dev to see if this will happen.

```<code>function setOutput {
  echo "##vso[task.setvariable variable=$1]$2"
}

setOutput environment dev
</code>```

Body:
I have a bash script with the following functionality:

# usage: setOutput <name> <value>
function setOutput {
  echo "##vso[task.setvariable variable=$1]$2"
}

setOutput environment "dev"

This normally sets the variable correctly as ENVIRONMENT=dev - however, sometimes this randomly appends a ' at the end, i.e. ENVIRONMENT=dev'

I tried re-running the same commit on the pipeline multiple times, and sometimes it works, sometimes it doesn't. Any ideas?

Body:
I tested it with your sample, it can be displayed normally .

You can try to remove the double quotes of dev to see if this will happen.

function setOutput {
  echo "##vso[task.setvariable variable=$1]$2"
}

setOutput environment dev


答:
I used below php code to convert julian date to gregorian format.

$ts=mktime(0, 0, 0, 1, 136, "20" . 20);

$mydate=date ('m-d-Y', $ts);

echo $mydate;
```

You can also refer to https://www.juliandate.net to convert the dates.

Title: PHP Julian date converter algorithms

Body:
Algorithms for the following:

JD 1099114.5

PHP: 3 Mar -1704 12:00:00 (PHP Internal convertor)

echo jdtogregorian($int_jd);

FLN: 0 Mar -1703 12:00:00 (Fliegel-Van Flandern)

function jd_to_gd_fln ($J) {
   $p = $J + 68569;
   $q = floor(4*$p/146097);
   $r = floor($p - (146097*$q + 3)/4);
   $s = floor(4000*($r+1)/1461001);
   $t = floor($r - (1461*$s/4) + 31);
   $u = floor(80*$t/2447);
   $v = floor($u/11);

     $Y = floor(100*($q-49)+$s+$v);
     $M = floor($u + 2 - 12*$v);
     $D = floor($t - 2447*$u/80);

return "$M/$D/$Y";

}

MEU: 18 Mar -1703 12:00:00 (Jean Meeus "Astronomical Algorithms, 2nd ed., corrected)

function jd_to_greg_meeus($julian) {
    $Z = intval($J+0.5);
 $F = ($J+0.5)-$Z;

  if ($Z < 2299161) {$A = $Z;}
   if ($Z >= 2299161) {
        $alpha = floor(($Z-1867216.25)/36524.25);
         $A = $Z + 1 + $alpha - floor($alpha/4);
         }

         $B = $A + 1524;
         $C = floor( ($B-122.1)/365.25);
         $D = floor( 365.25*$C );
         $E = floor( ($B-$D)/30.6001 );

     $day = floor($B - $D - floor(30.6001*$E));

if ($E < 13.5) {   $month = $E - 1;}
if ($E > 13.5) {   $month = $E - 13;}
if ($month > 2.5) {  $year = $C - 4716; }
if ($month < 2.5) {  $year = $C - 4715; }

    return "$month/$day/$year";
}

RICH: 4 Mar -1703 12:00:00 (Richards in Explanatory Supplement 3rd Ed.)

function jd_to_gd_rchrds ($J) {
$y=4716;
$v=3;
$j=1401;
$u=5;
$m=2;
$s=153;
$n=12;
$w=2;
$r=4;
$B=274277;
$p=1461;
$C=-38;

$f = $J + $j + (((4 * $J + $B) / 146097) * 3) / 4 + $C;

$e = $r * $f + $v;
$g = ($e % $p) / $r;
$h = $u * $g + $w;
$D = floor((($h%$s)) / $u + 1);
$M = floor((($h / $s + $m) % $n) + 1);
$Y = floor(($e / $p) - $y + ($n + $m - $M) / $n);

return "$M/$D/$Y";
}

Each Algorithm has its issues.

What am I doing wrong with the code?

For reference test data should include:

JD: 2399301.5

JD: 1721420

JD: 1721425

JD: 1721426

JD: 2422444

JD: 2222444

Meeus assumes that there is a Gregorian year 0, even if this is astronomically correct, it makes little sense from a calendrical perspective.  Technically then all the results to convert into Gregorian dates are just wrong? Calendrically speaking if there is no 0 but astronomically speaking there is a 0 how does that translate into the same date?

Body:
I used below php code to convert julian date to gregorian format.

$ts=mktime(0, 0, 0, 1, 136, "20" . 20);

$mydate=date ('m-d-Y', $ts);

echo $mydate;

You can also refer to https://www.juliandate.net to convert the dates.


问:
Create Custom SQL Server Role in SQL 2008 Server
I want to add new custom SQL Server Role and assign the new users to these appropriate roles respectively.  I try to find how to create role, but I could not find the place to add that.  Could you please guide me how to achieve my requirement?</p>

答:
You cannot do this in the 2008 version just yet - this is a new feature that you'll get with SQL Server 2011 (a.k.a. "Denali") sometime in 2011/2012.

See some resources:

Create your own fixed server roles

Custom server roles in SQL Server Denali

Add your OWN server role in Denali


问:
Why we need the init_weight function in BERT pretrained model in Huggingface Transformers?
In the code by Hugginface transformers, there are many fine-tuning models have the function init_weight.
For example(here), there is a init_weight function at last.

class BertForSequenceClassification(BertPreTrainedModel):
    def __init__(self, config):
        super().__init__(config)
        self.num_labels = config.num_labels

        self.bert = BertModel(config)
        self.dropout = nn.Dropout(config.hidden_dropout_prob)
        self.classifier = nn.Linear(config.hidden_size, config.num_labels)

        self.init_weights()

```

<p>As I know, it will call the following code</p>

<pre class="lang-py prettyprint-override"><code>def _init_weights(self, module):
    """ Initialize the weights """
    if isinstance(module, (nn.Linear, nn.Embedding)):
        # Slightly different from the TF version which uses truncated_normal for initialization
        # cf https://github.com/pytorch/pytorch/pull/5617
        module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
    elif isinstance(module, BertLayerNorm):
        module.bias.data.zero_()
        module.weight.data.fill_(1.0)
    if isinstance(module, nn.Linear) and module.bias is not None:
        module.bias.data.zero_()
</code>```

My question is If we are loading the pre-trained model, why do we need to initialize the weight for every module?

I guess I must be misunderstanding something here.

答:
Have a look at the code for .from_pretrained(). What actually happens is something like this:

find the correct base model class to initialise

initialise that class with pseudo-random initialisation (by using the _init_weights function that you mention)

find the file with the pretrained weights

overwrite the weights of the model that we just created with the pretrained weights where applicable

This ensure that the layers that were not pretrained (e.g. in some cases the final classification layer) do get initialised in _init_weights but don't get overridden.

Body:
In the code by Hugginface transformers, there are many fine-tuning models have the function init_weight.
For example(here), there is a init_weight function at last.

class BertForSequenceClassification(BertPreTrainedModel):
    def __init__(self, config):
        super().__init__(config)
        self.num_labels = config.num_labels

        self.bert = BertModel(config)
        self.dropout = nn.Dropout(config.hidden_dropout_prob)
        self.classifier = nn.Linear(config.hidden_size, config.num_labels)

        self.init_weights()

As I know, it will call the following code

def _init_weights(self, module):
    """ Initialize the weights """
    if isinstance(module, (nn.Linear, nn.Embedding)):
        # Slightly different from the TF version which uses truncated_normal for initialization
        # cf https://github.com/pytorch/pytorch/pull/5617
        module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
    elif isinstance(module, BertLayerNorm):
        module.bias.data.zero_()
        module.weight.data.fill_(1.0)
    if isinstance(module, nn.Linear) and module.bias is not None:
        module.bias.data.zero_()

My question is If we are loading the pre-trained model, why do we need to initialize the weight for every module?

I guess I must be misunderstanding something here.


问:
Dataset for textual adverts matching
I'm new to machine learning and I'm trying to create a machine learning classifier using python & Jupyter to match textual advertisements to websites that they will be displayed on. Is there any dataset that I could make use of?</p>

答:
You could get a lot of datas to train your NN e.g. on the U.S. government site
Or you load datasets from sklearn: e.g.:
from sklearn import datasets (link to sklearn)

Title: Dataset for textual adverts matching


问:
Codeigniter: unable to upload image (You did not select a file to upload)
When I try to upload a image to my uploads folder i get the following error:

Array ( [error] =>
  You did not select a file to upload.)

My View:

```<code><form action="<?=base_url('create_public_profile_job') ?>" class="create-profile-form" method="POST">
     <input type="file" name="userfile" size="20000" />
     <button type="submit" class="create-profile-button">Submit</button>
</form>
</code>```

My Controller

```<code>public function create_public_profile_job()
{
    if(isset($_POST['userfile']))
    {
            $this->User_model->do_upload($_POST['userfile']);
    }
}
</code>```

My Model

```<code>public function do_upload($userfile)
{
    $this->load->helper('form');
    $this->load->helper('url');

    $config['upload_path']          = 'assets/uploads/';
    $config['allowed_types']        = 'gif|jpg|png';
    $config['max_size']             = 1000000;
    $config['max_width']            = 10240000;
    $config['max_height']           = 7680000;

    $this->load->library('upload', $config);

    if ( ! $this->upload->do_upload($userfile))
    {
            $error = array('error' => $this->upload->display_errors());
            print_r($userfile);
            print_r($error);
    }
    else
    {
            $data = array('upload_data' => $this->upload->data());

            print_r($data);
    }
}
</code>```

The Model part is from the Codeigniter userguide https://codeigniter.com/userguide3/libraries/file_uploading.html

Don't really know where the issue is, because I pass the image through all functions

答:
change view to </p>

```<code><form action="<?=base_url('create_public_profile_job') ?>" class="create-
profile-form" method="POST" enctype="multipart/form-data">
     <input type="file" name="userfile" size="20000" />
     <button type="submit" class="create-profile-button">Submit</button>
</form>
</code>```

Body:
When I try to upload a image to my uploads folder i get the following error:

Array ( [error] =>
  You did not select a file to upload.)

My View:

<form action="<?=base_url('create_public_profile_job') ?>" class="create-profile-form" method="POST">
     <input type="file" name="userfile" size="20000" />
     <button type="submit" class="create-profile-button">Submit</button>
</form>

My Controller

public function create_public_profile_job()
{
    if(isset($_POST['userfile']))
    {
            $this->User_model->do_upload($_POST['userfile']);
    }
}

My Model

public function do_upload($userfile)
{
    $this->load->helper('form');
    $this->load->helper('url');

    $config['upload_path']          = 'assets/uploads/';
    $config['allowed_types']        = 'gif|jpg|png';
    $config['max_size']             = 1000000;
    $config['max_width']            = 10240000;
    $config['max_height']           = 7680000;

    $this->load->library('upload', $config);

    if ( ! $this->upload->do_upload($userfile))
    {
            $error = array('error' => $this->upload->display_errors());
            print_r($userfile);
            print_r($error);
    }
    else
    {
            $data = array('upload_data' => $this->upload->data());

            print_r($data);
    }
}

The Model part is from the Codeigniter userguide https://codeigniter.com/userguide3/libraries/file_uploading.html

Don't really know where the issue is, because I pass the image through all functions

Body:
change view to

<form action="<?=base_url('create_public_profile_job') ?>" class="create-
profile-form" method="POST" enctype="multipart/form-data">
     <input type="file" name="userfile" size="20000" />
     <button type="submit" class="create-profile-button">Submit</button>
</form>