问:
Why is Direct2D not drawing to the screen
I couldn't get it to work in pure assembly so i tried making C code to draw to the screen but the C code won't do it either and i don't know why and nothing is giving error codes. Im trying to draw directly onto the screen with Direct2D through a GDI DC.

My C code,  sorry if its a little messy it was supposed to be temporary for a quick fix

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Windows.h>
#include <d2d1.h>

#pragma comment(lib, "d2d1.lib")

extern "C" ID2D1Bitmap* mybitmapcreate(ID2D1DCRenderTarget*);
float left = 5;
float top = 10;
float Bottom = 10;
float Right = 30;
ID2D1Bitmap* picbitmap;

D2D1_RECT_F myrect = D2D1::RectF(left, top, Bottom, Right);
ID2D1DCRenderTarget* pow;
ID2D1Bitmap* mybitmap;
ID2D1Factory *l;
REFIID x = __uuidof(ID2D1Factory);

struct D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties(
    D2D1_RENDER_TARGET_TYPE_DEFAULT,
    D2D1::PixelFormat(
        DXGI_FORMAT_B8G8R8A8_UNORM,
        D2D1_ALPHA_MODE_IGNORE),
    0,
    0,
    D2D1_RENDER_TARGET_USAGE_NONE,
    D2D1_FEATURE_LEVEL_DEFAULT
);
struct D2D1_BITMAP_PROPERTIES bitmapprops = D2D1::BitmapProperties(
    D2D1::PixelFormat(DXGI_FORMAT_R8G8B8A8_UINT, D2D1_ALPHA_MODE_UNKNOWN), 96.0, 96.0
);

int main()
{
    /*
    long bufferend;
    FILE* mybitmapfile;
    char* mybitmaparray;
    //size_t result;
    mybitmapfile = fopen("bitmap.bin", "rb");
    if (mybitmapfile == NULL) { fputs("File error", stderr); exit(1); }
    fseek(mybitmapfile, 0, SEEK_END);
    //bufferend = ftell(mybitmapfile);
    bufferend = 1204097;
    rewind(mybitmapfile);
    mybitmaparray = (char*) malloc(sizeof(char)*bufferend);
    if (mybitmaparray == NULL) { fputs("Memory error", stderr); exit(2); }
    fread(mybitmaparray, 1, bufferend, mybitmapfile);
    fclose(mybitmapfile);
    */
    HRESULT hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &l);
    l->CreateDCRenderTarget(&props, &pow);
    picbitmap = mybitmapcreate(pow);
    pow->BeginDraw();
    while (true) {
        pow->DrawBitmap(picbitmap, myrect, 1.0F, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, myrect);
    };
    pow->EndDraw();
    return 0;
}
</code>```

This is mybitmapcreate, its return value is the bitmap.

```<code>includelib user32.lib
includelib D2D1.lib
include externals.asm
include wincons.asm
include vtable.asm

.data
include variables.asm
include pic.asm
include riid.asm
include structures.asm
.code
public mybitmapcreate
bitmapcreate proc frame
mybitmapcreate::
    DB 48h
    push rbx
    .pushreg rbx
    push r13
    .pushreg r13
    push rbp
    .pushreg rbp
    sub rsp, 80
    .allocstack 80
    lea rbp, [rsp + 80]
    .setframe rbp, 80
    .endprolog
    mov ID2D1DCRenderTarget, rcx
    call __imp_GetDesktopWindow
    mov rcx, 0
    mov rbx, rax
getdcfail:
    call __imp_GetDC
    cmp rax, 0
    je getdcfail
    mov rcx, rbx
    lea rdx, ScreenSize
    mov screendc, rax
    call __imp_GetWindowRect
    mov rcx, ID2D1DCRenderTarget
    mov rbx, [rcx]
    mov rdx, ScreenDC
    lea r8, ScreenSize
    call ID2D1DCRenderTarget_BindDC
    mov rcx, ID2D1DCRenderTarget
    mov rbx, [rcx]
    mov rdx, 000000199000002E0h
    lea r8, pic1colorbytes
    mov r9, 2944
    lea rax, pic1properties
    mov qword ptr [rsp + 20h], rax
    lea rax, ID2D1Bitmap1
    mov qword ptr [rsp + 28h], rax
    call ID2D1DCRenderTarget_CreateBitmap
    mov rax, ID2D1Bitmap1
    mov rsp, rbp
    pop rbp
    pop r13
    pop rbx
    ret
bitmapcreate endp
end
</code>```

This is my vtable

```<code>;ID2D1RenderTargetVtbl
    ID2D1RenderTarget_QueryInterface                  textequ       <qword ptr [rbx+0]>
    ID2D1RenderTarget_AddRef                          textequ       <qword ptr [rbx+8]>
    ID2D1RenderTarget_Release                         textequ       <qword ptr [rbx+16]>
    ID2D1RenderTarget_GetFactory                      textequ       <qword ptr [rbx+24]>
    ID2D1RenderTarget_CreateBitmap                    textequ       <qword ptr [rbx+32]>
    ID2D1RenderTarget_CreateBitmapFromWicBitmap       textequ       <qword ptr [rbx+40]>
    ID2D1RenderTarget_CreateSharedBitmap              textequ       <qword ptr [rbx+48]>
    ID2D1RenderTarget_CreateBitmapBrush               textequ       <qword ptr [rbx+56]>
    ID2D1RenderTarget_CreateSolidColorBrush           textequ       <qword ptr [rbx+64]>
    ID2D1RenderTarget_CreateGradientStopCollection    textequ       <qword ptr [rbx+72]>
    ID2D1RenderTarget_CreateLinearGradientBrush       textequ       <qword ptr [rbx+80]>
    ID2D1RenderTarget_CreateRadialGradientBrush       textequ       <qword ptr [rbx+88]>
    ID2D1RenderTarget_CreateCompatibleRenderTarget    textequ       <qword ptr [rbx+96]>
    ID2D1RenderTarget_CreateLayer                     textequ       <qword ptr [rbx+104]>
    ID2D1RenderTarget_CreateMesh                      textequ       <qword ptr [rbx+112]>
    ID2D1RenderTarget_DrawLine                        textequ       <qword ptr [rbx+120]>
    ID2D1RenderTarget_DrawRectangle                   textequ       <qword ptr [rbx+128]>
    ID2D1RenderTarget_FillRectangle                   textequ       <qword ptr [rbx+136]>
    ID2D1RenderTarget_DrawRoundedRectangle            textequ       <qword ptr [rbx+144]>
    ID2D1RenderTarget_FillRoundedRectangle            textequ       <qword ptr [rbx+152]>
    ID2D1RenderTarget_DrawEllipse                     textequ       <qword ptr [rbx+160]>
    ID2D1RenderTarget_FillEllipse                     textequ       <qword ptr [rbx+168]>
    ID2D1RenderTarget_DrawGeometry                    textequ       <qword ptr [rbx+176]>
    ID2D1RenderTarget_FillGeometry                    textequ       <qword ptr [rbx+184]>
    ID2D1RenderTarget_FillMesh                        textequ       <qword ptr [rbx+192]>
    ID2D1RenderTarget_FillOpacityMask                 textequ       <qword ptr [rbx+200]>
    ID2D1RenderTarget_DrawBitmap                      textequ       <qword ptr [rbx+208]>
    ID2D1RenderTarget_DrawText                        textequ       <qword ptr [rbx+216]>
    ID2D1RenderTarget_DrawTextLayout                  textequ       <qword ptr [rbx+224]>
    ID2D1RenderTarget_DrawGlyphRun                    textequ       <qword ptr [rbx+232]>
    ID2D1RenderTarget_SetTransform                    textequ       <qword ptr [rbx+240]>
    ID2D1RenderTarget_GetTransform                    textequ       <qword ptr [rbx+248]>
    ID2D1RenderTarget_SetAntialiasMode                textequ       <qword ptr [rbx+256]>
    ID2D1RenderTarget_GetAntialiasMode                textequ       <qword ptr [rbx+264]>
    ID2D1RenderTarget_SetTextAntialiasMode            textequ       <qword ptr [rbx+272]>
    ID2D1RenderTarget_GetTextAntialiasMode            textequ       <qword ptr [rbx+280]>
    ID2D1RenderTarget_SetTextRenderingParams          textequ       <qword ptr [rbx+288]>
    ID2D1RenderTarget_GetTextRenderingParams          textequ       <qword ptr [rbx+296]>
    ID2D1RenderTarget_SetTags                         textequ       <qword ptr [rbx+304]>
    ID2D1RenderTarget_GetTags                         textequ       <qword ptr [rbx+312]>
    ID2D1RenderTarget_PushLayer                       textequ       <qword ptr [rbx+320]>
    ID2D1RenderTarget_PopLayer                        textequ       <qword ptr [rbx+328]>
    ID2D1RenderTarget_Flush                           textequ       <qword ptr [rbx+336]>
    ID2D1RenderTarget_SaveDrawingState                textequ       <qword ptr [rbx+344]>
    ID2D1RenderTarget_RestoreDrawingState             textequ       <qword ptr [rbx+352]>
    ID2D1RenderTarget_PushAxisAlignedClip             textequ       <qword ptr [rbx+360]>
    ID2D1RenderTarget_PopAxisAlignedClip              textequ       <qword ptr [rbx+368]>
    ID2D1RenderTarget_Clear                           textequ       <qword ptr [rbx+376]>
    ID2D1RenderTarget_BeginDraw                       textequ       <qword ptr [rbx+384]>
    ID2D1RenderTarget_EndDraw                         textequ       <qword ptr [rbx+392]>
    ID2D1RenderTarget_GetPixelFormat                  textequ       <qword ptr [rbx+400]>
    ID2D1RenderTarget_SetDpi                          textequ       <qword ptr [rbx+408]>
    ID2D1RenderTarget_GetDpi                          textequ       <qword ptr [rbx+416]>
    ID2D1RenderTarget_GetSize                         textequ       <qword ptr [rbx+424]>
    ID2D1RenderTarget_GetPixelSize                    textequ       <qword ptr [rbx+432]>
    ID2D1RenderTarget_GetMaximumBitmapSize            textequ       <qword ptr [rbx+440]>
    ID2D1RenderTarget_IsSupported                     textequ       <qword ptr [rbx+448]>
;ID2D1Factory
    ID2D1Factory_QueryInterface                     textequ     <qword ptr [rbx+0]>
    ID2D1Factory_AddRef                             textequ     <qword ptr [rbx+8]>
    ID2D1Factory_Release                            textequ     <qword ptr [rbx+16]>
    ID2D1Factory_ReloadSystemMetrics                textequ     <qword ptr [rbx+24]>
    ID2D1Factory_GetDesktopDpi                      textequ     <qword ptr [rbx+32]>
    ID2D1Factory_CreateRectangleGeometry            textequ     <qword ptr [rbx+40]>
    ID2D1Factory_CreateRoundedRectangleGeometry     textequ     <qword ptr [rbx+48]>
    ID2D1Factory_CreateEllipseGeometry              textequ     <qword ptr [rbx+56]>
    ID2D1Factory_CreateGeometryGroup                textequ     <qword ptr [rbx+64]>
    ID2D1Factory_CreateTransformedGeometry          textequ     <qword ptr [rbx+72]>
    ID2D1Factory_CreatePathGeometry                 textequ     <qword ptr [rbx+80]>
    ID2D1Factory_CreateStrokeStyle                  textequ     <qword ptr [rbx+88]>
    ID2D1Factory_CreateDrawingStateBlock            textequ     <qword ptr [rbx+96]>
    ID2D1Factory_CreateWicBitmapRenderTarget        textequ     <qword ptr [rbx+104]>
    ID2D1Factory_CreateHwndRenderTarget             textequ     <qword ptr [rbx+112]>
    ID2D1Factory_CreateDxgiSurfaceRenderTarget      textequ     <qword ptr [rbx+120]>
    ID2D1Factory_CreateDCRenderTarget               textequ     <qword ptr [rbx+128]>
;dcrendertarget
    ID2D1DCRenderTarget_QueryInterface                  textequ     <qword ptr [rbx+0]>
    ID2D1DCRenderTarget_AddRef                          textequ     <qword ptr [rbx+8]>
    ID2D1DCRenderTarget_Release                         textequ     <qword ptr [rbx+16]>
    ID2D1DCRenderTarget_GetFactory                      textequ     <qword ptr [rbx+24]>
    ID2D1DCRenderTarget_CreateBitmap                    textequ     <qword ptr [rbx+32]>
    ID2D1DCRenderTarget_CreateBitmapFromWicBitmap       textequ     <qword ptr [rbx+40]>
    ID2D1DCRenderTarget_CreateSharedBitmap              textequ     <qword ptr [rbx+48]>
    ID2D1DCRenderTarget_CreateBitmapBrush               textequ     <qword ptr [rbx+56]>
    ID2D1DCRenderTarget_CreateSolidColorBrush           textequ     <qword ptr [rbx+64]>
    ID2D1DCRenderTarget_CreateGradientStopCollection    textequ     <qword ptr [rbx+72]>
    ID2D1DCRenderTarget_CreateLinearGradientBrush       textequ     <qword ptr [rbx+80]>
    ID2D1DCRenderTarget_CreateRadialGradientBrush       textequ     <qword ptr [rbx+88]>
    ID2D1DCRenderTarget_CreateCompatibleRenderTarget    textequ     <qword ptr [rbx+96]>
    ID2D1DCRenderTarget_CreateLayer                     textequ     <qword ptr [rbx+104]>
    ID2D1DCRenderTarget_CreateMesh                      textequ     <qword ptr [rbx+112]>
    ID2D1DCRenderTarget_DrawLine                        textequ     <qword ptr [rbx+120]>
    ID2D1DCRenderTarget_DrawRectangle                   textequ     <qword ptr [rbx+128]>
    ID2D1DCRenderTarget_FillRectangle                   textequ     <qword ptr [rbx+136]>
    ID2D1DCRenderTarget_DrawRoundedRectangle            textequ     <qword ptr [rbx+144]>
    ID2D1DCRenderTarget_FillRoundedRectangle            textequ     <qword ptr [rbx+152]>
    ID2D1DCRenderTarget_DrawEllipse                     textequ     <qword ptr [rbx+160]>
    ID2D1DCRenderTarget_FillEllipse                     textequ     <qword ptr [rbx+168]>
    ID2D1DCRenderTarget_DrawGeometry                    textequ     <qword ptr [rbx+176]>
    ID2D1DCRenderTarget_FillGeometry                    textequ     <qword ptr [rbx+184]>
    ID2D1DCRenderTarget_FillMesh                        textequ     <qword ptr [rbx+192]>
    ID2D1DCRenderTarget_FillOpacityMask                 textequ     <qword ptr [rbx+200]>
    ID2D1DCRenderTarget_DrawBitmap                      textequ     <qword ptr [rbx+208]>
    ID2D1DCRenderTarget_DrawText                        textequ     <qword ptr [rbx+216]>
    ID2D1DCRenderTarget_DrawTextLayout                  textequ     <qword ptr [rbx+224]>
    ID2D1DCRenderTarget_DrawGlyphRun                    textequ     <qword ptr [rbx+232]>
    ID2D1DCRenderTarget_SetTransform                    textequ     <qword ptr [rbx+240]>
    ID2D1DCRenderTarget_GetTransform                    textequ     <qword ptr [rbx+248]>
    ID2D1DCRenderTarget_SetAntialiasMode                textequ     <qword ptr [rbx+256]>
    ID2D1DCRenderTarget_GetAntialiasMode                textequ     <qword ptr [rbx+264]>
    ID2D1DCRenderTarget_SetTextAntialiasMode            textequ     <qword ptr [rbx+272]>
    ID2D1DCRenderTarget_GetTextAntialiasMode            textequ     <qword ptr [rbx+280]>
    ID2D1DCRenderTarget_SetTextRenderingParams          textequ     <qword ptr [rbx+288]>
    ID2D1DCRenderTarget_GetTextRenderingParams          textequ     <qword ptr [rbx+296]>
    ID2D1DCRenderTarget_SetTags                         textequ     <qword ptr [rbx+304]>
    ID2D1DCRenderTarget_GetTags                         textequ     <qword ptr [rbx+312]>
    ID2D1DCRenderTarget_PushLayer                       textequ     <qword ptr [rbx+320]>
    ID2D1DCRenderTarget_PopLayer                        textequ     <qword ptr [rbx+328]>
    ID2D1DCRenderTarget_Flush                           textequ     <qword ptr [rbx+336]>
    ID2D1DCRenderTarget_SaveDrawingState                textequ     <qword ptr [rbx+344]>
    ID2D1DCRenderTarget_RestoreDrawingState             textequ     <qword ptr [rbx+352]>
    ID2D1DCRenderTarget_PushAxisAlignedClip             textequ     <qword ptr [rbx+360]>
    ID2D1DCRenderTarget_PopAxisAlignedClip              textequ     <qword ptr [rbx+368]>
    ID2D1DCRenderTarget_Clear                           textequ     <qword ptr [rbx+376]>
    ID2D1DCRenderTarget_BeginDraw                       textequ     <qword ptr [rbx+384]>
    ID2D1DCRenderTarget_EndDraw                         textequ     <qword ptr [rbx+392]>
    ID2D1DCRenderTarget_GetPixelFormat                  textequ     <qword ptr [rbx+400]>
    ID2D1DCRenderTarget_SetDpi                          textequ     <qword ptr [rbx+408]>
    ID2D1DCRenderTarget_GetDpi                          textequ     <qword ptr [rbx+416]>
    ID2D1DCRenderTarget_GetSize                         textequ     <qword ptr [rbx+424]>
    ID2D1DCRenderTarget_GetPixelSize                    textequ     <qword ptr [rbx+432]>
    ID2D1DCRenderTarget_GetMaximumBitmapSize            textequ     <qword ptr [rbx+440]>
    ID2D1DCRenderTarget_IsSupported                     textequ     <qword ptr [rbx+448]>
    ID2D1DCRenderTarget_BindDC                          textequ     <qword ptr [rbx+456]>
</code>```

答:
You lack some necessary conditions:

need a win32 window

refer: Creating a Window

need to initialize IWICImagingFactory interface

refer: How to Load a Bitmap from a File

need to use BindDC method to associate it with a GDI DC.

refer: Direct2D and GDI Interoperability Overview

Modified code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Windows.h>
#include <d2d1.h>

#include <wincodec.h>

#pragma comment(lib, "d2d1.lib")
#pragma comment(lib, "Windowscodecs.lib")

#define SAFE_RELEASE(P) if(P){P->Release() ; P = NULL ;}

extern "C" ID2D1Bitmap* mybitmapcreate(ID2D1DCRenderTarget*);
float left = 5;
float top = 10;
float Bottom = 10;
float Right = 30;
ID2D1Bitmap *pBitmap = NULL;
IWICImagingFactory *pIWICFactory = NULL;

void initize();
void draw();
D2D1_RECT_F myrect = D2D1::RectF(left, top, Bottom, Right);
ID2D1DCRenderTarget* pow;
ID2D1Bitmap* mybitmap;
ID2D1Factory *l;
REFIID x = __uuidof(ID2D1Factory);

HRESULT LoadBitmapFromFile(
    ID2D1RenderTarget *pRenderTarget,
    IWICImagingFactory *pIWICFactory,
    PCWSTR uri,
    UINT destinationWidth,
    UINT destinationHeight
)
{
    HRESULT hr = S_OK;

    IWICBitmapDecoder *pDecoder = NULL;
    IWICBitmapFrameDecode *pSource = NULL;
    IWICStream *pStream = NULL;
    IWICFormatConverter *pConverter = NULL;
    IWICBitmapScaler *pScaler = NULL;

    hr = pIWICFactory->CreateDecoderFromFilename(
        uri,
        NULL,
        GENERIC_READ,
        WICDecodeMetadataCacheOnLoad,
        &pDecoder
    );
    if (SUCCEEDED(hr))
    {

        // Create the initial frame.
        hr = pDecoder->GetFrame(0, &pSource);
    }
    if (SUCCEEDED(hr))
    {
        hr = pIWICFactory->CreateFormatConverter(&pConverter);
    }
    // If a new width or height was specified, create an
// IWICBitmapScaler and use it to resize the image.
    if (destinationWidth != 0 || destinationHeight != 0)
    {
        UINT originalWidth, originalHeight;
        hr = pSource->GetSize(&originalWidth, &originalHeight);
        if (SUCCEEDED(hr))
        {
            if (destinationWidth == 0)
            {
                FLOAT scalar = static_cast<FLOAT>(destinationHeight) / static_cast<FLOAT>(originalHeight);
                destinationWidth = static_cast<UINT>(scalar * static_cast<FLOAT>(originalWidth));
            }
            else if (destinationHeight == 0)
            {
                FLOAT scalar = static_cast<FLOAT>(destinationWidth) / static_cast<FLOAT>(originalWidth);
                destinationHeight = static_cast<UINT>(scalar * static_cast<FLOAT>(originalHeight));
            }

            hr = pIWICFactory->CreateBitmapScaler(&pScaler);
            if (SUCCEEDED(hr))
            {
                hr = pScaler->Initialize(
                    pSource,
                    destinationWidth,
                    destinationHeight,
                    WICBitmapInterpolationModeCubic
                );
            }
            if (SUCCEEDED(hr))
            {
                hr = pConverter->Initialize(
                    pScaler,
                    GUID_WICPixelFormat32bppPBGRA,
                    WICBitmapDitherTypeNone,
                    NULL,
                    0.f,
                    WICBitmapPaletteTypeMedianCut
                );
            }
        }
    }
    if (SUCCEEDED(hr))
    {
        // Create a Direct2D bitmap from the WIC bitmap.
        hr = pRenderTarget->CreateBitmapFromWicBitmap(
            pConverter,
            NULL,
            &pBitmap
        );
    }

    SAFE_RELEASE(pDecoder);
    SAFE_RELEASE(pSource);
    SAFE_RELEASE(pStream);
    SAFE_RELEASE(pConverter);
    SAFE_RELEASE(pScaler);

    return TRUE;
}

LRESULT CALLBACK WndProcFunc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    RECT rc;
    switch (message)
    {
    case WM_PAINT:
    {
        PAINTSTRUCT ps;
        HDC hdc = BeginPaint(hwnd, &ps);
        GetClientRect(hwnd, &rc);
        pow->BindDC(ps.hdc, &rc);
        draw();
        EndPaint(hwnd, &ps);
    }
    break;
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    }
    return DefWindowProc(hwnd, message, wParam, lParam);
}
int main(int argc, char* argv[])
{
    WNDCLASS wc{};
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WndProcFunc;
    wc.hInstance = GetModuleHandle(NULL);
    wc.lpszClassName = L"Class_Name";
    wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
    RegisterClass(&wc);

    HWND hWnd = CreateWindow(L"Class_Name", L"Test", WS_OVERLAPPEDWINDOW, 100, 100, 1000, 500, NULL, NULL, GetModuleHandle(NULL), NULL);
    initize();

    ShowWindow(hWnd, 1);
    UpdateWindow(hWnd);

    MSG Msg;
    while (GetMessage(&Msg, NULL, 0, 0))
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }

    return 0;
}

void initize()
{
    CoInitializeEx(NULL, COINIT_MULTITHREADED);
    CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory, reinterpret_cast<void **>(&pIWICFactory));

    // Create a Direct2D render target.
    D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties(
        D2D1_RENDER_TARGET_TYPE_DEFAULT,
        D2D1::PixelFormat(
            DXGI_FORMAT_B8G8R8A8_UNORM,
            D2D1_ALPHA_MODE_IGNORE),
        0,
        0,
        D2D1_RENDER_TARGET_USAGE_NONE,
        D2D1_FEATURE_LEVEL_DEFAULT
    );

    HRESULT hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &l);
    l->CreateDCRenderTarget(&props, &pow);

}

void draw()
{

    LoadBitmapFromFile(pow, pIWICFactory, L"Path\\test.bmp", 650, 400);

    pow->BeginDraw();

    pow->Clear(D2D1::ColorF(D2D1::ColorF::White));

    D2D1_SIZE_F size = pBitmap->GetSize();
    D2D1_POINT_2F upperLeftCorner = D2D1::Point2F(0.f, 0.f);

    // Draw bitmap
    pow->DrawBitmap(
        pBitmap,
        D2D1::RectF(
            upperLeftCorner.x,
            upperLeftCorner.y,
            upperLeftCorner.x + size.width,
            upperLeftCorner.y + size.height)
    );
    pow->EndDraw();

}
</code>```

There may be some redundancy in the code, you can freely add and delete.

Debug:

Body:
I couldn't get it to work in pure assembly so i tried making C code to draw to the screen but the C code won't do it either and i don't know why and nothing is giving error codes. Im trying to draw directly onto the screen with Direct2D through a GDI DC.

My C code,  sorry if its a little messy it was supposed to be temporary for a quick fix

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Windows.h>
#include <d2d1.h>

#pragma comment(lib, "d2d1.lib")

extern "C" ID2D1Bitmap* mybitmapcreate(ID2D1DCRenderTarget*);
float left = 5;
float top = 10;
float Bottom = 10;
float Right = 30;
ID2D1Bitmap* picbitmap;

D2D1_RECT_F myrect = D2D1::RectF(left, top, Bottom, Right);
ID2D1DCRenderTarget* pow;
ID2D1Bitmap* mybitmap;
ID2D1Factory *l;
REFIID x = __uuidof(ID2D1Factory);

struct D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties(
    D2D1_RENDER_TARGET_TYPE_DEFAULT,
    D2D1::PixelFormat(
        DXGI_FORMAT_B8G8R8A8_UNORM,
        D2D1_ALPHA_MODE_IGNORE),
    0,
    0,
    D2D1_RENDER_TARGET_USAGE_NONE,
    D2D1_FEATURE_LEVEL_DEFAULT
);
struct D2D1_BITMAP_PROPERTIES bitmapprops = D2D1::BitmapProperties(
    D2D1::PixelFormat(DXGI_FORMAT_R8G8B8A8_UINT, D2D1_ALPHA_MODE_UNKNOWN), 96.0, 96.0
);

int main()
{
    /*
    long bufferend;
    FILE* mybitmapfile;
    char* mybitmaparray;
    //size_t result;
    mybitmapfile = fopen("bitmap.bin", "rb");
    if (mybitmapfile == NULL) { fputs("File error", stderr); exit(1); }
    fseek(mybitmapfile, 0, SEEK_END);
    //bufferend = ftell(mybitmapfile);
    bufferend = 1204097;
    rewind(mybitmapfile);
    mybitmaparray = (char*) malloc(sizeof(char)*bufferend);
    if (mybitmaparray == NULL) { fputs("Memory error", stderr); exit(2); }
    fread(mybitmaparray, 1, bufferend, mybitmapfile);
    fclose(mybitmapfile);
    */
    HRESULT hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &l);
    l->CreateDCRenderTarget(&props, &pow);
    picbitmap = mybitmapcreate(pow);
    pow->BeginDraw();
    while (true) {
        pow->DrawBitmap(picbitmap, myrect, 1.0F, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, myrect);
    };
    pow->EndDraw();
    return 0;
}

This is mybitmapcreate, its return value is the bitmap.

includelib user32.lib
includelib D2D1.lib
include externals.asm
include wincons.asm
include vtable.asm

.data
include variables.asm
include pic.asm
include riid.asm
include structures.asm
.code
public mybitmapcreate
bitmapcreate proc frame
mybitmapcreate::
    DB 48h
    push rbx
    .pushreg rbx
    push r13
    .pushreg r13
    push rbp
    .pushreg rbp
    sub rsp, 80
    .allocstack 80
    lea rbp, [rsp + 80]
    .setframe rbp, 80
    .endprolog
    mov ID2D1DCRenderTarget, rcx
    call __imp_GetDesktopWindow
    mov rcx, 0
    mov rbx, rax
getdcfail:
    call __imp_GetDC
    cmp rax, 0
    je getdcfail
    mov rcx, rbx
    lea rdx, ScreenSize
    mov screendc, rax
    call __imp_GetWindowRect
    mov rcx, ID2D1DCRenderTarget
    mov rbx, [rcx]
    mov rdx, ScreenDC
    lea r8, ScreenSize
    call ID2D1DCRenderTarget_BindDC
    mov rcx, ID2D1DCRenderTarget
    mov rbx, [rcx]
    mov rdx, 000000199000002E0h
    lea r8, pic1colorbytes
    mov r9, 2944
    lea rax, pic1properties
    mov qword ptr [rsp + 20h], rax
    lea rax, ID2D1Bitmap1
    mov qword ptr [rsp + 28h], rax
    call ID2D1DCRenderTarget_CreateBitmap
    mov rax, ID2D1Bitmap1
    mov rsp, rbp
    pop rbp
    pop r13
    pop rbx
    ret
bitmapcreate endp
end

This is my vtable

;ID2D1RenderTargetVtbl
    ID2D1RenderTarget_QueryInterface                  textequ       <qword ptr [rbx+0]>
    ID2D1RenderTarget_AddRef                          textequ       <qword ptr [rbx+8]>
    ID2D1RenderTarget_Release                         textequ       <qword ptr [rbx+16]>
    ID2D1RenderTarget_GetFactory                      textequ       <qword ptr [rbx+24]>
    ID2D1RenderTarget_CreateBitmap                    textequ       <qword ptr [rbx+32]>
    ID2D1RenderTarget_CreateBitmapFromWicBitmap       textequ       <qword ptr [rbx+40]>
    ID2D1RenderTarget_CreateSharedBitmap              textequ       <qword ptr [rbx+48]>
    ID2D1RenderTarget_CreateBitmapBrush               textequ       <qword ptr [rbx+56]>
    ID2D1RenderTarget_CreateSolidColorBrush           textequ       <qword ptr [rbx+64]>
    ID2D1RenderTarget_CreateGradientStopCollection    textequ       <qword ptr [rbx+72]>
    ID2D1RenderTarget_CreateLinearGradientBrush       textequ       <qword ptr [rbx+80]>
    ID2D1RenderTarget_CreateRadialGradientBrush       textequ       <qword ptr [rbx+88]>
    ID2D1RenderTarget_CreateCompatibleRenderTarget    textequ       <qword ptr [rbx+96]>
    ID2D1RenderTarget_CreateLayer                     textequ       <qword ptr [rbx+104]>
    ID2D1RenderTarget_CreateMesh                      textequ       <qword ptr [rbx+112]>
    ID2D1RenderTarget_DrawLine                        textequ       <qword ptr [rbx+120]>
    ID2D1RenderTarget_DrawRectangle                   textequ       <qword ptr [rbx+128]>
    ID2D1RenderTarget_FillRectangle                   textequ       <qword ptr [rbx+136]>
    ID2D1RenderTarget_DrawRoundedRectangle            textequ       <qword ptr [rbx+144]>
    ID2D1RenderTarget_FillRoundedRectangle            textequ       <qword ptr [rbx+152]>
    ID2D1RenderTarget_DrawEllipse                     textequ       <qword ptr [rbx+160]>
    ID2D1RenderTarget_FillEllipse                     textequ       <qword ptr [rbx+168]>
    ID2D1RenderTarget_DrawGeometry                    textequ       <qword ptr [rbx+176]>
    ID2D1RenderTarget_FillGeometry                    textequ       <qword ptr [rbx+184]>
    ID2D1RenderTarget_FillMesh                        textequ       <qword ptr [rbx+192]>
    ID2D1RenderTarget_FillOpacityMask                 textequ       <qword ptr [rbx+200]>
    ID2D1RenderTarget_DrawBitmap                      textequ       <qword ptr [rbx+208]>
    ID2D1RenderTarget_DrawText                        textequ       <qword ptr [rbx+216]>
    ID2D1RenderTarget_DrawTextLayout                  textequ       <qword ptr [rbx+224]>
    ID2D1RenderTarget_DrawGlyphRun                    textequ       <qword ptr [rbx+232]>
    ID2D1RenderTarget_SetTransform                    textequ       <qword ptr [rbx+240]>
    ID2D1RenderTarget_GetTransform                    textequ       <qword ptr [rbx+248]>
    ID2D1RenderTarget_SetAntialiasMode                textequ       <qword ptr [rbx+256]>
    ID2D1RenderTarget_GetAntialiasMode                textequ       <qword ptr [rbx+264]>
    ID2D1RenderTarget_SetTextAntialiasMode            textequ       <qword ptr [rbx+272]>
    ID2D1RenderTarget_GetTextAntialiasMode            textequ       <qword ptr [rbx+280]>
    ID2D1RenderTarget_SetTextRenderingParams          textequ       <qword ptr [rbx+288]>
    ID2D1RenderTarget_GetTextRenderingParams          textequ       <qword ptr [rbx+296]>
    ID2D1RenderTarget_SetTags                         textequ       <qword ptr [rbx+304]>
    ID2D1RenderTarget_GetTags                         textequ       <qword ptr [rbx+312]>
    ID2D1RenderTarget_PushLayer                       textequ       <qword ptr [rbx+320]>
    ID2D1RenderTarget_PopLayer                        textequ       <qword ptr [rbx+328]>
    ID2D1RenderTarget_Flush                           textequ       <qword ptr [rbx+336]>
    ID2D1RenderTarget_SaveDrawingState                textequ       <qword ptr [rbx+344]>
    ID2D1RenderTarget_RestoreDrawingState             textequ       <qword ptr [rbx+352]>
    ID2D1RenderTarget_PushAxisAlignedClip             textequ       <qword ptr [rbx+360]>
    ID2D1RenderTarget_PopAxisAlignedClip              textequ       <qword ptr [rbx+368]>
    ID2D1RenderTarget_Clear                           textequ       <qword ptr [rbx+376]>
    ID2D1RenderTarget_BeginDraw                       textequ       <qword ptr [rbx+384]>
    ID2D1RenderTarget_EndDraw                         textequ       <qword ptr [rbx+392]>
    ID2D1RenderTarget_GetPixelFormat                  textequ       <qword ptr [rbx+400]>
    ID2D1RenderTarget_SetDpi                          textequ       <qword ptr [rbx+408]>
    ID2D1RenderTarget_GetDpi                          textequ       <qword ptr [rbx+416]>
    ID2D1RenderTarget_GetSize                         textequ       <qword ptr [rbx+424]>
    ID2D1RenderTarget_GetPixelSize                    textequ       <qword ptr [rbx+432]>
    ID2D1RenderTarget_GetMaximumBitmapSize            textequ       <qword ptr [rbx+440]>
    ID2D1RenderTarget_IsSupported                     textequ       <qword ptr [rbx+448]>
;ID2D1Factory
    ID2D1Factory_QueryInterface                     textequ     <qword ptr [rbx+0]>
    ID2D1Factory_AddRef                             textequ     <qword ptr [rbx+8]>
    ID2D1Factory_Release                            textequ     <qword ptr [rbx+16]>
    ID2D1Factory_ReloadSystemMetrics                textequ     <qword ptr [rbx+24]>
    ID2D1Factory_GetDesktopDpi                      textequ     <qword ptr [rbx+32]>
    ID2D1Factory_CreateRectangleGeometry            textequ     <qword ptr [rbx+40]>
    ID2D1Factory_CreateRoundedRectangleGeometry     textequ     <qword ptr [rbx+48]>
    ID2D1Factory_CreateEllipseGeometry              textequ     <qword ptr [rbx+56]>
    ID2D1Factory_CreateGeometryGroup                textequ     <qword ptr [rbx+64]>
    ID2D1Factory_CreateTransformedGeometry          textequ     <qword ptr [rbx+72]>
    ID2D1Factory_CreatePathGeometry                 textequ     <qword ptr [rbx+80]>
    ID2D1Factory_CreateStrokeStyle                  textequ     <qword ptr [rbx+88]>
    ID2D1Factory_CreateDrawingStateBlock            textequ     <qword ptr [rbx+96]>
    ID2D1Factory_CreateWicBitmapRenderTarget        textequ     <qword ptr [rbx+104]>
    ID2D1Factory_CreateHwndRenderTarget             textequ     <qword ptr [rbx+112]>
    ID2D1Factory_CreateDxgiSurfaceRenderTarget      textequ     <qword ptr [rbx+120]>
    ID2D1Factory_CreateDCRenderTarget               textequ     <qword ptr [rbx+128]>
;dcrendertarget
    ID2D1DCRenderTarget_QueryInterface                  textequ     <qword ptr [rbx+0]>
    ID2D1DCRenderTarget_AddRef                          textequ     <qword ptr [rbx+8]>
    ID2D1DCRenderTarget_Release                         textequ     <qword ptr [rbx+16]>
    ID2D1DCRenderTarget_GetFactory                      textequ     <qword ptr [rbx+24]>
    ID2D1DCRenderTarget_CreateBitmap                    textequ     <qword ptr [rbx+32]>
    ID2D1DCRenderTarget_CreateBitmapFromWicBitmap       textequ     <qword ptr [rbx+40]>
    ID2D1DCRenderTarget_CreateSharedBitmap              textequ     <qword ptr [rbx+48]>
    ID2D1DCRenderTarget_CreateBitmapBrush               textequ     <qword ptr [rbx+56]>
    ID2D1DCRenderTarget_CreateSolidColorBrush           textequ     <qword ptr [rbx+64]>
    ID2D1DCRenderTarget_CreateGradientStopCollection    textequ     <qword ptr [rbx+72]>
    ID2D1DCRenderTarget_CreateLinearGradientBrush       textequ     <qword ptr [rbx+80]>
    ID2D1DCRenderTarget_CreateRadialGradientBrush       textequ     <qword ptr [rbx+88]>
    ID2D1DCRenderTarget_CreateCompatibleRenderTarget    textequ     <qword ptr [rbx+96]>
    ID2D1DCRenderTarget_CreateLayer                     textequ     <qword ptr [rbx+104]>
    ID2D1DCRenderTarget_CreateMesh                      textequ     <qword ptr [rbx+112]>
    ID2D1DCRenderTarget_DrawLine                        textequ     <qword ptr [rbx+120]>
    ID2D1DCRenderTarget_DrawRectangle                   textequ     <qword ptr [rbx+128]>
    ID2D1DCRenderTarget_FillRectangle                   textequ     <qword ptr [rbx+136]>
    ID2D1DCRenderTarget_DrawRoundedRectangle            textequ     <qword ptr [rbx+144]>
    ID2D1DCRenderTarget_FillRoundedRectangle            textequ     <qword ptr [rbx+152]>
    ID2D1DCRenderTarget_DrawEllipse                     textequ     <qword ptr [rbx+160]>
    ID2D1DCRenderTarget_FillEllipse                     textequ     <qword ptr [rbx+168]>
    ID2D1DCRenderTarget_DrawGeometry                    textequ     <qword ptr [rbx+176]>
    ID2D1DCRenderTarget_FillGeometry                    textequ     <qword ptr [rbx+184]>
    ID2D1DCRenderTarget_FillMesh                        textequ     <qword ptr [rbx+192]>
    ID2D1DCRenderTarget_FillOpacityMask                 textequ     <qword ptr [rbx+200]>
    ID2D1DCRenderTarget_DrawBitmap                      textequ     <qword ptr [rbx+208]>
    ID2D1DCRenderTarget_DrawText                        textequ     <qword ptr [rbx+216]>
    ID2D1DCRenderTarget_DrawTextLayout                  textequ     <qword ptr [rbx+224]>
    ID2D1DCRenderTarget_DrawGlyphRun                    textequ     <qword ptr [rbx+232]>
    ID2D1DCRenderTarget_SetTransform                    textequ     <qword ptr [rbx+240]>
    ID2D1DCRenderTarget_GetTransform                    textequ     <qword ptr [rbx+248]>
    ID2D1DCRenderTarget_SetAntialiasMode                textequ     <qword ptr [rbx+256]>
    ID2D1DCRenderTarget_GetAntialiasMode                textequ     <qword ptr [rbx+264]>
    ID2D1DCRenderTarget_SetTextAntialiasMode            textequ     <qword ptr [rbx+272]>
    ID2D1DCRenderTarget_GetTextAntialiasMode            textequ     <qword ptr [rbx+280]>
    ID2D1DCRenderTarget_SetTextRenderingParams          textequ     <qword ptr [rbx+288]>
    ID2D1DCRenderTarget_GetTextRenderingParams          textequ     <qword ptr [rbx+296]>
    ID2D1DCRenderTarget_SetTags                         textequ     <qword ptr [rbx+304]>
    ID2D1DCRenderTarget_GetTags                         textequ     <qword ptr [rbx+312]>
    ID2D1DCRenderTarget_PushLayer                       textequ     <qword ptr [rbx+320]>
    ID2D1DCRenderTarget_PopLayer                        textequ     <qword ptr [rbx+328]>
    ID2D1DCRenderTarget_Flush                           textequ     <qword ptr [rbx+336]>
    ID2D1DCRenderTarget_SaveDrawingState                textequ     <qword ptr [rbx+344]>
    ID2D1DCRenderTarget_RestoreDrawingState             textequ     <qword ptr [rbx+352]>
    ID2D1DCRenderTarget_PushAxisAlignedClip             textequ     <qword ptr [rbx+360]>
    ID2D1DCRenderTarget_PopAxisAlignedClip              textequ     <qword ptr [rbx+368]>
    ID2D1DCRenderTarget_Clear                           textequ     <qword ptr [rbx+376]>
    ID2D1DCRenderTarget_BeginDraw                       textequ     <qword ptr [rbx+384]>
    ID2D1DCRenderTarget_EndDraw                         textequ     <qword ptr [rbx+392]>
    ID2D1DCRenderTarget_GetPixelFormat                  textequ     <qword ptr [rbx+400]>
    ID2D1DCRenderTarget_SetDpi                          textequ     <qword ptr [rbx+408]>
    ID2D1DCRenderTarget_GetDpi                          textequ     <qword ptr [rbx+416]>
    ID2D1DCRenderTarget_GetSize                         textequ     <qword ptr [rbx+424]>
    ID2D1DCRenderTarget_GetPixelSize                    textequ     <qword ptr [rbx+432]>
    ID2D1DCRenderTarget_GetMaximumBitmapSize            textequ     <qword ptr [rbx+440]>
    ID2D1DCRenderTarget_IsSupported                     textequ     <qword ptr [rbx+448]>
    ID2D1DCRenderTarget_BindDC                          textequ     <qword ptr [rbx+456]>

Body:
You lack some necessary conditions:

need a win32 window

refer: Creating a Window

need to initialize IWICImagingFactory interface

refer: How to Load a Bitmap from a File

need to use BindDC method to associate it with a GDI DC.

refer: Direct2D and GDI Interoperability Overview

Modified code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Windows.h>
#include <d2d1.h>

#include <wincodec.h>

#pragma comment(lib, "d2d1.lib")
#pragma comment(lib, "Windowscodecs.lib")

#define SAFE_RELEASE(P) if(P){P->Release() ; P = NULL ;}

extern "C" ID2D1Bitmap* mybitmapcreate(ID2D1DCRenderTarget*);
float left = 5;
float top = 10;
float Bottom = 10;
float Right = 30;
ID2D1Bitmap *pBitmap = NULL;
IWICImagingFactory *pIWICFactory = NULL;

void initize();
void draw();
D2D1_RECT_F myrect = D2D1::RectF(left, top, Bottom, Right);
ID2D1DCRenderTarget* pow;
ID2D1Bitmap* mybitmap;
ID2D1Factory *l;
REFIID x = __uuidof(ID2D1Factory);

HRESULT LoadBitmapFromFile(
    ID2D1RenderTarget *pRenderTarget,
    IWICImagingFactory *pIWICFactory,
    PCWSTR uri,
    UINT destinationWidth,
    UINT destinationHeight
)
{
    HRESULT hr = S_OK;

    IWICBitmapDecoder *pDecoder = NULL;
    IWICBitmapFrameDecode *pSource = NULL;
    IWICStream *pStream = NULL;
    IWICFormatConverter *pConverter = NULL;
    IWICBitmapScaler *pScaler = NULL;

    hr = pIWICFactory->CreateDecoderFromFilename(
        uri,
        NULL,
        GENERIC_READ,
        WICDecodeMetadataCacheOnLoad,
        &pDecoder
    );
    if (SUCCEEDED(hr))
    {

        // Create the initial frame.
        hr = pDecoder->GetFrame(0, &pSource);
    }
    if (SUCCEEDED(hr))
    {
        hr = pIWICFactory->CreateFormatConverter(&pConverter);
    }
    // If a new width or height was specified, create an
// IWICBitmapScaler and use it to resize the image.
    if (destinationWidth != 0 || destinationHeight != 0)
    {
        UINT originalWidth, originalHeight;
        hr = pSource->GetSize(&originalWidth, &originalHeight);
        if (SUCCEEDED(hr))
        {
            if (destinationWidth == 0)
            {
                FLOAT scalar = static_cast<FLOAT>(destinationHeight) / static_cast<FLOAT>(originalHeight);
                destinationWidth = static_cast<UINT>(scalar * static_cast<FLOAT>(originalWidth));
            }
            else if (destinationHeight == 0)
            {
                FLOAT scalar = static_cast<FLOAT>(destinationWidth) / static_cast<FLOAT>(originalWidth);
                destinationHeight = static_cast<UINT>(scalar * static_cast<FLOAT>(originalHeight));
            }

            hr = pIWICFactory->CreateBitmapScaler(&pScaler);
            if (SUCCEEDED(hr))
            {
                hr = pScaler->Initialize(
                    pSource,
                    destinationWidth,
                    destinationHeight,
                    WICBitmapInterpolationModeCubic
                );
            }
            if (SUCCEEDED(hr))
            {
                hr = pConverter->Initialize(
                    pScaler,
                    GUID_WICPixelFormat32bppPBGRA,
                    WICBitmapDitherTypeNone,
                    NULL,
                    0.f,
                    WICBitmapPaletteTypeMedianCut
                );
            }
        }
    }
    if (SUCCEEDED(hr))
    {
        // Create a Direct2D bitmap from the WIC bitmap.
        hr = pRenderTarget->CreateBitmapFromWicBitmap(
            pConverter,
            NULL,
            &pBitmap
        );
    }

    SAFE_RELEASE(pDecoder);
    SAFE_RELEASE(pSource);
    SAFE_RELEASE(pStream);
    SAFE_RELEASE(pConverter);
    SAFE_RELEASE(pScaler);

    return TRUE;
}

LRESULT CALLBACK WndProcFunc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    RECT rc;
    switch (message)
    {
    case WM_PAINT:
    {
        PAINTSTRUCT ps;
        HDC hdc = BeginPaint(hwnd, &ps);
        GetClientRect(hwnd, &rc);
        pow->BindDC(ps.hdc, &rc);
        draw();
        EndPaint(hwnd, &ps);
    }
    break;
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    }
    return DefWindowProc(hwnd, message, wParam, lParam);
}
int main(int argc, char* argv[])
{
    WNDCLASS wc{};
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WndProcFunc;
    wc.hInstance = GetModuleHandle(NULL);
    wc.lpszClassName = L"Class_Name";
    wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
    RegisterClass(&wc);

    HWND hWnd = CreateWindow(L"Class_Name", L"Test", WS_OVERLAPPEDWINDOW, 100, 100, 1000, 500, NULL, NULL, GetModuleHandle(NULL), NULL);
    initize();

    ShowWindow(hWnd, 1);
    UpdateWindow(hWnd);

    MSG Msg;
    while (GetMessage(&Msg, NULL, 0, 0))
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }

    return 0;
}

void initize()
{
    CoInitializeEx(NULL, COINIT_MULTITHREADED);
    CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory, reinterpret_cast<void **>(&pIWICFactory));

    // Create a Direct2D render target.
    D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties(
        D2D1_RENDER_TARGET_TYPE_DEFAULT,
        D2D1::PixelFormat(
            DXGI_FORMAT_B8G8R8A8_UNORM,
            D2D1_ALPHA_MODE_IGNORE),
        0,
        0,
        D2D1_RENDER_TARGET_USAGE_NONE,
        D2D1_FEATURE_LEVEL_DEFAULT
    );

    HRESULT hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &l);
    l->CreateDCRenderTarget(&props, &pow);

}

void draw()
{

    LoadBitmapFromFile(pow, pIWICFactory, L"Path\\test.bmp", 650, 400);

    pow->BeginDraw();

    pow->Clear(D2D1::ColorF(D2D1::ColorF::White));

    D2D1_SIZE_F size = pBitmap->GetSize();
    D2D1_POINT_2F upperLeftCorner = D2D1::Point2F(0.f, 0.f);

    // Draw bitmap
    pow->DrawBitmap(
        pBitmap,
        D2D1::RectF(
            upperLeftCorner.x,
            upperLeftCorner.y,
            upperLeftCorner.x + size.width,
            upperLeftCorner.y + size.height)
    );
    pow->EndDraw();

}

There may be some redundancy in the code, you can freely add and delete.

Debug:


来源: stackexchange

问:
Initialization in a parameterless constructor should be avoided?
some of my colleagues demand to avoid parameterless constructor and it's initialization completly.
Because they tell me that a default initialization of a string property for example quickly hides the ability to find out the source of the error.

But a standard initialization of objects prevent the raise of a NullReferenceException in advance.
And don't unit tests prevent those 'hard to find' errors?

So what is the best practice of doing this in C#?

What if i had a class with 10 Properties? Should the properties also be initialized via parameters of the constructor if i want to avoid the parameterless constructor? Isn't it to verbose?

For example i have this class, so people told me that i shouldn't do the default initialzation this way:

```<code>public class UserForCreationDto
{
    public UserForCreationDto()
    {
        Username = "";
        Email = "";
    }

    [Required]
    [MaxLength(100)]
    public string Username { get; set; }

    [Required]
    [MaxLength(100)]
    public string Email { get; set; }
}
</code>```

答:
Initialization in a parameterless constructor should be avoided?

another way to ask this is

Side effects should be avoided?

there are benefits to avoiding side effects, which is probably what your colleagues are talking about without saying so many words. this is much interconnected with the benefits of immutability and dependency injection.

ContentLicense: CC BY-SA 4.0

Body:
some of my colleagues demand to avoid parameterless constructor and it's initialization completly.
Because they tell me that a default initialization of a string property for example quickly hides the ability to find out the source of the error.

But a standard initialization of objects prevent the raise of a NullReferenceException in advance.
And don't unit tests prevent those 'hard to find' errors?

So what is the best practice of doing this in C#?

What if i had a class with 10 Properties? Should the properties also be initialized via parameters of the constructor if i want to avoid the parameterless constructor? Isn't it to verbose?

For example i have this class, so people told me that i shouldn't do the default initialzation this way:

public class UserForCreationDto
{
    public UserForCreationDto()
    {
        Username = "";
        Email = "";
    }

    [Required]
    [MaxLength(100)]
    public string Username { get; set; }

    [Required]
    [MaxLength(100)]
    public string Email { get; set; }
}


问:
Spooky action observed in Python context manager
Using contextmanager in Python 3 (I haven't tested Python 2) has some weird behavior regarding variables declared in the scope within the with clause.

It seems to me that the variables are behaving like 'spooky action at a distance' in the sense that only when observed they appear to exist (joke from a non-physics savvy engineer).

Inside a context managers scope, after the yield point:

If you...

print out locals()

then the variable does not exist.

But if you:

print out locals();

do anything with the variable of the managed scope

THEN THE VARIABLE EXISTS!!

See this example:

from contextlib import contextmanager

def groucho():
    @contextmanager
    def groucho_manager(**kwargs):
        yield
        print("groucho_manager locals", locals())
        a

    with groucho_manager(lolcat=10):
        a = 50

def harpo():
    @contextmanager
    def harpo_manager(**kwargs):
        yield
        print("harpo_manager locals", locals())

    with harpo_manager(lolcat=10):
        b = 100

groucho()
harpo()
```

<p>outputs:</p>

<pre class="lang-py prettyprint-override"><code>groucho_manager locals {'kwargs': {'lolcat': 10}, 'a': 50}
harpo_manager locals {'kwargs': {'lolcat': 10}}
</code>```

Possibly related to Python class inheritance - spooky action, but I am not sure.

答:
My initial usecase was to make a inner scope aware context manager to take care of logging.

I thought i could abuse the odd behavior listed in the question, but as @jasonharper pointed out: its to do with nested scopes and not to be abused.

So... i decided to make a really hacky/abusive solution to all of this:

scope_injected_contextmanager on pypi

here is the simple example from the README:

from scope_injected_contextmanager import scope_injected_contextmanager

fetch = lambda request: ("ok", 200)

@scope_injected_contextmanager
def log_request(request, response):
    print(f"request: {request} response: {response}")

with log_request:
    request = {
        "query_args": {
            'foo': 10
        }
    }
    response = fetch(request)

# prints
# request: {'query_args': {'foo': 10}} response: ('ok', 200)
```

see more at github

beware... its:

really hacky

completely not tested-enough

really ugly and abusive

uses inspect heavily (see 1-3)

Body:
Using contextmanager in Python 3 (I haven't tested Python 2) has some weird behavior regarding variables declared in the scope within the with clause.

It seems to me that the variables are behaving like 'spooky action at a distance' in the sense that only when observed they appear to exist (joke from a non-physics savvy engineer).

Inside a context managers scope, after the yield point:

If you...

print out locals()

then the variable does not exist.

But if you:

print out locals();

do anything with the variable of the managed scope

THEN THE VARIABLE EXISTS!!

See this example:

from contextlib import contextmanager

def groucho():
    @contextmanager
    def groucho_manager(**kwargs):
        yield
        print("groucho_manager locals", locals())
        a

    with groucho_manager(lolcat=10):
        a = 50

def harpo():
    @contextmanager
    def harpo_manager(**kwargs):
        yield
        print("harpo_manager locals", locals())

    with harpo_manager(lolcat=10):
        b = 100

groucho()
harpo()

outputs:

groucho_manager locals {'kwargs': {'lolcat': 10}, 'a': 50}
harpo_manager locals {'kwargs': {'lolcat': 10}}

Possibly related to Python class inheritance - spooky action, but I am not sure.

Body:
My initial usecase was to make a inner scope aware context manager to take care of logging.

I thought i could abuse the odd behavior listed in the question, but as @jasonharper pointed out: its to do with nested scopes and not to be abused.

So... i decided to make a really hacky/abusive solution to all of this:

scope_injected_contextmanager on pypi

here is the simple example from the README:

from scope_injected_contextmanager import scope_injected_contextmanager

fetch = lambda request: ("ok", 200)

@scope_injected_contextmanager
def log_request(request, response):
    print(f"request: {request} response: {response}")

with log_request:
    request = {
        "query_args": {
            'foo': 10
        }
    }
    response = fetch(request)

# prints
# request: {'query_args': {'foo': 10}} response: ('ok', 200)

see more at github

beware... its:

really hacky

completely not tested-enough

really ugly and abusive

uses inspect heavily (see 1-3)


问:
Use column if it exists, another if doesn't in SQL Server
I have a number of SQL Server databases (different versions from 2012 to 2019). The schema in each one is very similar but not exactly the same.  For example, there's table ORDERS, which has about 50 columns - and one column is called differently in two different databases:

in DB1: select p_user from orders

in DB2: select userpk from orders

Note that I showed two databases above, but there are actually more than 20 - some are DB1 type, the others are DB2 type

I can't do much about these differences - they are historic - and changing the schema to match is not an option.

I want to be able to run the same SQL statement against all of these databases at once.  I'd like to write the query in such a way that it would use one column if it exists and another if it doesn't.  For example:

```<code>select
    case
        when COL_LENGTH('orders', 'p_user') IS NOT NULL
    then
        orders.p_user
    else
        orders.userpk
    end
from orders
</code>```

This unfortunately doesn't work, as SQL server seems to try to evaluate both results regardless of whether the condition is true or false.  The same thing happens if I use IIF function.

If I simply run

```<code>select
    case
        when COL_LENGTH('orders', 'p_user') IS NOT NULL
    then
        'orders.p_user'
    else
        'orders.userpk'
    end
</code>```

then I do get the correct string, which means my condition is correct.

How can I formulate the SQL statement to use one or the other column based on whether the first one exists?

答:
```<code>create table orders1(colA int, colB int, colABC int);
insert into orders1 values(1, 2, 3);
go
create table orders2(colA int, colB int, colKLM int);
insert into orders2 values(5, 6, 7);
go
create table orders3(colA int, colB int, colXYZ int);
insert into orders3 values(10, 11, 12);
go

select colA, colB, vcolname as [ABC_KLM_XYZ]
from
(
select *,
(select o.* for xml path(''), elements, type).query('
/*[local-name() = ("colABC", "colKLM", "colXYZ")][1]
').value('.', 'int') as vcolname
from orders1 as o
) as src;

select colA, colB, vcolname as [ABC_KLM_XYZ]
from
(
select *,
(select o.* for xml path(''), elements, type).query('
/*[local-name() = ("colABC", "colKLM", "colXYZ")][1]
').value('.', 'int') as vcolname
from orders2 as o
) as src;

select colA, colB, vcolname as [ABC_KLM_XYZ]
from
(
select *,
(select o.* for xml path(''), elements, type).query('
/*[local-name() = ("colABC", "colKLM", "colXYZ")][1]
').value('.', 'int') as vcolname
from orders3 as o
) as src;
go

drop table orders1
drop table orders2
drop table orders3
go
</code>```

Body:
I have a number of SQL Server databases (different versions from 2012 to 2019). The schema in each one is very similar but not exactly the same.  For example, there's table ORDERS, which has about 50 columns - and one column is called differently in two different databases:

in DB1: select p_user from orders

in DB2: select userpk from orders

Note that I showed two databases above, but there are actually more than 20 - some are DB1 type, the others are DB2 type

I can't do much about these differences - they are historic - and changing the schema to match is not an option.

I want to be able to run the same SQL statement against all of these databases at once.  I'd like to write the query in such a way that it would use one column if it exists and another if it doesn't.  For example:

select
    case
        when COL_LENGTH('orders', 'p_user') IS NOT NULL
    then
        orders.p_user
    else
        orders.userpk
    end
from orders

This unfortunately doesn't work, as SQL server seems to try to evaluate both results regardless of whether the condition is true or false.  The same thing happens if I use IIF function.

If I simply run

select
    case
        when COL_LENGTH('orders', 'p_user') IS NOT NULL
    then
        'orders.p_user'
    else
        'orders.userpk'
    end

then I do get the correct string, which means my condition is correct.

How can I formulate the SQL statement to use one or the other column based on whether the first one exists?


问:
Android RxJava - call multiple single until condition and return a single
I'm stuck on a simple task and i'm pretty sure i'm heading the wrong way.
I just need to fetch a list of items. I can only get items by 50 and I don't know the exact number of page.

So what I need to do is make the call and repeat it until I get less than 50 items (which means it's the last page), then return the complete list with an insert in a db

The api call is a single, and I need to return a single.
Api call:

```<code>@GET("posts")
    fun getItems(@Query("page") page: Int, @Query("per_page") perPage: Int): Single<List<Item>>
</code>```

This is what I got so far:

```<code>fun getItems(): Single<List<Item>> {
    var result = listOf<Item>()
    return Observable.range(1, Integer.MAX_VALUE).concatMapSingle { page ->
            remoteDataSource.getItems(page, 50).map {
                result = it
                it
            }
        }.repeatUntil {
            result.size != 50
        }.single(emptyList()).map {
            localDataSource.insertItems(it)
            it
        }
}
</code>```

The problem is I got an error when the second page is fetched:
java.lang.IllegalArgumentException: Sequence contains more than one element!

How can I do to append each calls to a list and emit that list when I reached the last page?
Should I change single to flowable for example?

答:
You need takeUntil to cut off the paging and re-accumulate all the individual pages:

```<code>Observable.range(1, Integer.MAX_VALUE)
.concatMapSingle { page ->
        remoteDataSource.getItems(page, 50)
}
.takeUntil {
        it.size != 50
}
.flatMapIterable { it }
.toList()
</code>```

Body:
I'm stuck on a simple task and i'm pretty sure i'm heading the wrong way.
I just need to fetch a list of items. I can only get items by 50 and I don't know the exact number of page.

So what I need to do is make the call and repeat it until I get less than 50 items (which means it's the last page), then return the complete list with an insert in a db

The api call is a single, and I need to return a single.
Api call:

@GET("posts")
    fun getItems(@Query("page") page: Int, @Query("per_page") perPage: Int): Single<List<Item>>

This is what I got so far:

fun getItems(): Single<List<Item>> {
    var result = listOf<Item>()
    return Observable.range(1, Integer.MAX_VALUE).concatMapSingle { page ->
            remoteDataSource.getItems(page, 50).map {
                result = it
                it
            }
        }.repeatUntil {
            result.size != 50
        }.single(emptyList()).map {
            localDataSource.insertItems(it)
            it
        }
}

The problem is I got an error when the second page is fetched:
java.lang.IllegalArgumentException: Sequence contains more than one element!

How can I do to append each calls to a list and emit that list when I reached the last page?
Should I change single to flowable for example?

Body:
You need takeUntil to cut off the paging and re-accumulate all the individual pages:

Observable.range(1, Integer.MAX_VALUE)
.concatMapSingle { page ->
        remoteDataSource.getItems(page, 50)
}
.takeUntil {
        it.size != 50
}
.flatMapIterable { it }
.toList()


问:
why count(*) is slow even with index?
This is my query:

```<code>   select count(*)
    FROM TB_E2V_DOCUMENTOS_CICLO D
    WHERE (D.TIPOCLIENTE = null or null is null)
      AND (D.TIPODOCUMENTOCLIENTE = null or null is null)
      AND (D.NUMDOCUMENTOCLIENTE = null or null is null)
      AND (D.BA = null or null is null)
      AND (D.FA = null or null is null)
      AND (D.NOMBRECLIENTE = null or null is null)
      AND (D.NUMTELEFONO = null or null is null)
      AND (D.NUMSUSCRIPCION = null or null is null)
      AND (D.TIPORECIBO in ('Recibo'))
      AND (D.NUMRECIBO = null or null is null)
      AND (TO_DATE(D.FECHAEMISION, 'yyyy/MM/dd') BETWEEN TO_DATE('2019-5-1', 'yyyy-MM-dd') AND TO_DATE('2020-2-18', 'yyyy-MM-dd'))
      AND (D.MONTORECIBO = null or null is null)
      AND (D.NUMPAGINAS = 0 or 0 = 0)
      AND (D.NOMBREARCHIVO = null or null is null)
      AND (D.NEGOCIO = null or null is null)
      AND (D.NOMBREMETADATACARGA = null or null is null)
      AND (D.FECHACARGA = TO_DATE(null) or TO_DATE(null) is null);
</code>```

This query returns

And when I do a Xplain For:

The cost is very high, but this query uses the index. The query lasts 10 seconds approximately.
How can I improve the performance of the query?

I'm using Oracle 12c

答:
Notes:  All of the " and ( = null or null is null)" predicates will always evaluate to true; Oracle does not define null so null does not equal null, so instead if you want to check for null then use "is null"

```<code>select * from dual where null = null; -- returns no rows
select * from dual where not (null <> null); -- returns no rows
select * from dual where null is null;  -- returns 1 row
select * from dual where not(null is not null);  -- returns 1 row
</code>```

As far as indexing goes, you need an index that is selective (i.e. return much fewer rows) and is present in the where clause predicate.  In this case it looks like a function-based index on TO_DATE(D.FECHAEMISION, 'yyyy/MM/dd')
along with D.TIPORECIBO is in order.  The INDEX SKIP SCAN is used in this case probably because D.TIPORECIBO is not the leading column; INDEX SKIP SCANs are slower then INDEX RANGE SCANs because it needs to read more index blocks.

Title: why count(*) is slow even with index?

Body:
This is my query:

   select count(*)
    FROM TB_E2V_DOCUMENTOS_CICLO D
    WHERE (D.TIPOCLIENTE = null or null is null)
      AND (D.TIPODOCUMENTOCLIENTE = null or null is null)
      AND (D.NUMDOCUMENTOCLIENTE = null or null is null)
      AND (D.BA = null or null is null)
      AND (D.FA = null or null is null)
      AND (D.NOMBRECLIENTE = null or null is null)
      AND (D.NUMTELEFONO = null or null is null)
      AND (D.NUMSUSCRIPCION = null or null is null)
      AND (D.TIPORECIBO in ('Recibo'))
      AND (D.NUMRECIBO = null or null is null)
      AND (TO_DATE(D.FECHAEMISION, 'yyyy/MM/dd') BETWEEN TO_DATE('2019-5-1', 'yyyy-MM-dd') AND TO_DATE('2020-2-18', 'yyyy-MM-dd'))
      AND (D.MONTORECIBO = null or null is null)
      AND (D.NUMPAGINAS = 0 or 0 = 0)
      AND (D.NOMBREARCHIVO = null or null is null)
      AND (D.NEGOCIO = null or null is null)
      AND (D.NOMBREMETADATACARGA = null or null is null)
      AND (D.FECHACARGA = TO_DATE(null) or TO_DATE(null) is null);

This query returns

And when I do a Xplain For:

The cost is very high, but this query uses the index. The query lasts 10 seconds approximately.
How can I improve the performance of the query?

I'm using Oracle 12c

Body:
Notes:  All of the " and ( = null or null is null)" predicates will always evaluate to true; Oracle does not define null so null does not equal null, so instead if you want to check for null then use "is null"

select * from dual where null = null; -- returns no rows
select * from dual where not (null <> null); -- returns no rows
select * from dual where null is null;  -- returns 1 row
select * from dual where not(null is not null);  -- returns 1 row

As far as indexing goes, you need an index that is selective (i.e. return much fewer rows) and is present in the where clause predicate.  In this case it looks like a function-based index on TO_DATE(D.FECHAEMISION, 'yyyy/MM/dd')
along with D.TIPORECIBO is in order.  The INDEX SKIP SCAN is used in this case probably because D.TIPORECIBO is not the leading column; INDEX SKIP SCANs are slower then INDEX RANGE SCANs because it needs to read more index blocks.


问:
iPad App: Merge PDF files into 1 PDF document / Create PDF Document of multi-page scrollview
I am writing an iPad application which uses a scrollview with page control.
I need to create a PDF of all the pages as 1 PDF file.
So far, I figured that I should loop through all the sub-views (pages) and create PDF files for each (using CGPDFContext). BUT I do need to combine all the files into 1 PDF document. Can you help me to do so??

OR if you have a better way to create a PDF document with multiple pages from this scrollview, that would even be better!!

Please help. I've searched everywhere and saw that Mac OS has something using PDFDocument, insertPage function. I can't find a similar method for iOS??

答:
to create a multi-part PDF:

```<code>-(CGContextRef) createPDFContext:(CGRect)inMediaBox path:(NSString *) path
{
    CGContextRef myOutContext = NULL;
    NSURL * url;

    url = [NSURL fileURLWithPath:path];
    if (url != NULL) {
        myOutContext = CGPDFContextCreateWithURL (url,// 2
                                                  &inMediaBox,
                                                  NULL);
    }
    return myOutContext;// 4
}

-(void)createPdfFromScrollview:(UIScrollView *)scrollview
{

    CGContextRef pdfContext = [self createPDFContext:CGRectMake(0, 0, WIDTH, HEIGHT) path:outputFilePath];

    for(UIView * view in scrollview.subviews)
    {
        CGContextBeginPage (pdfContext,nil);
        CGAffineTransform transform = CGAffineTransformIdentity;
        transform = CGAffineTransformMakeTranslation(0, HEIGHT);
        transform = CGAffineTransformScale(transform, 1.0, -1.0);
        CGContextConcatCTM(pdfContext, transform);
        //Draw view into PDF
        [view.layer renderInContext:pdfContext];

        CGContextEndPage (pdfContext);
    }

    CGContextRelease (pdfContext);
}
</code>```

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
to create a multi-part PDF:

-(CGContextRef) createPDFContext:(CGRect)inMediaBox path:(NSString *) path
{
    CGContextRef myOutContext = NULL;
    NSURL * url;

    url = [NSURL fileURLWithPath:path];
    if (url != NULL) {
        myOutContext = CGPDFContextCreateWithURL (url,// 2
                                                  &inMediaBox,
                                                  NULL);
    }
    return myOutContext;// 4
}

-(void)createPdfFromScrollview:(UIScrollView *)scrollview
{

    CGContextRef pdfContext = [self createPDFContext:CGRectMake(0, 0, WIDTH, HEIGHT) path:outputFilePath];

    for(UIView * view in scrollview.subviews)
    {
        CGContextBeginPage (pdfContext,nil);
        CGAffineTransform transform = CGAffineTransformIdentity;
        transform = CGAffineTransformMakeTranslation(0, HEIGHT);
        transform = CGAffineTransformScale(transform, 1.0, -1.0);
        CGContextConcatCTM(pdfContext, transform);
        //Draw view into PDF
        [view.layer renderInContext:pdfContext];

        CGContextEndPage (pdfContext);
    }

    CGContextRelease (pdfContext);
}

Hope this helps.


问:
SlideAnimation Not Starting Again After Calling SetState()
I made a simple class for animating a widget into the screen:

```<code>class CustomSlideAnimation extends StatefulWidget {
  static const String FROM_LEFT = 'FROM_LEFT';
  static const String FROM_RIGHT = 'FROM_RIGHT';
  final String from;
  final Widget child;

  const CustomSlideAnimation(
      {Key key, this.from = FROM_LEFT, @required this.child})
      : super(key: key);

  @override
  _CustomSlideAnimationState createState() => _CustomSlideAnimationState();
}

class _CustomSlideAnimationState extends State<CustomSlideAnimation>
    with SingleTickerProviderStateMixin {
  Animation<Offset> _offsetAnimation;
  AnimationController _animationController;

  @override
  void initState() {
    super.initState();
    _animationController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 300));
    _offsetAnimation = widget.from == CustomSlideAnimation.FROM_LEFT
        ? Tween<Offset>(
            begin: Offset(-1.0, 0.0),
            end: Offset.zero,
          ).animate(CurvedAnimation(
            curve: Curves.linear,
            parent: _animationController,
          ))
        : Tween<Offset>(
            begin: Offset(1.0, 0.0),
            end: Offset.zero,
          ).animate(CurvedAnimation(
            curve: Curves.linear,
            parent: _animationController,
          ));
    _animationController.forward();
  }

  @override
  void dispose() {
    super.dispose();
    _animationController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SlideTransition(
      position: _offsetAnimation,
      child: widget.child,
    );
  }
}
</code>```

And a simple app to demonstrate the problem:

```<code>void main() => runApp(Test());

class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  bool widget1 = true;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: widget1
              ? CustomSlideAnimation(
                  child: InkWell(
                    child: Text('widget1'),
                    onTap: () {
                      setState(() {
                        widget1 = false;
                      });
                    },
                  ),
                  from: CustomSlideAnimation.FROM_LEFT,
                )
              : CustomSlideAnimation(
                  child: InkWell(
                    child: Text('widget2'),
                    onTap: () {
                      setState(() {
                        widget1 = true;
                      });
                    },
                  ),
                  from: CustomSlideAnimation.FROM_LEFT,
                ),
        ),
      ),
    );
  }
}
</code>```

When I start the app for first time the Text widget as expected slides in to the screen,
but then I tap it and thus calling setState() the second Text widget just appears suddenly into the screen and no slide transition happens.

I printed the times when build get called in all the classes and I see that setState() is triggering builds in Test and CustomSlideTransition classes but not triggering initState() in the CustomSlideTransition.

EDIT for more clarification: even putting controller.forward() inside the build() method didn't work.

So what am I missing?

答:
You just need to add a UniqueKey() to every CustomSlideAnimation() to tell flutter to treat them like different widgets.

```<code>void main() => runApp(Test());

class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  bool widget1 = true;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: widget1
              ? CustomSlideAnimation(
                  key: UniqueKey(),
                  child: InkWell(
                    child: Text('widget1'),
                    onTap: () {
                      setState(() {
                        widget1 = false;
                      });
                    },
                  ),
                  from: CustomSlideAnimation.FROM_LEFT,
                )
              : CustomSlideAnimation(
                  key: UniqueKey(),
                  child: InkWell(
                    child: Text('widget2'),
                    onTap: () {
                      setState(() {
                        widget1 = true;
                      });
                    },
                  ),
                  from: CustomSlideAnimation.FROM_LEFT,
                ),
        ),
      ),
    );
  }
}
</code>```

Also, keep controller.forward() inside initState()

Body:
I made a simple class for animating a widget into the screen:

class CustomSlideAnimation extends StatefulWidget {
  static const String FROM_LEFT = 'FROM_LEFT';
  static const String FROM_RIGHT = 'FROM_RIGHT';
  final String from;
  final Widget child;

  const CustomSlideAnimation(
      {Key key, this.from = FROM_LEFT, @required this.child})
      : super(key: key);

  @override
  _CustomSlideAnimationState createState() => _CustomSlideAnimationState();
}

class _CustomSlideAnimationState extends State<CustomSlideAnimation>
    with SingleTickerProviderStateMixin {
  Animation<Offset> _offsetAnimation;
  AnimationController _animationController;

  @override
  void initState() {
    super.initState();
    _animationController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 300));
    _offsetAnimation = widget.from == CustomSlideAnimation.FROM_LEFT
        ? Tween<Offset>(
            begin: Offset(-1.0, 0.0),
            end: Offset.zero,
          ).animate(CurvedAnimation(
            curve: Curves.linear,
            parent: _animationController,
          ))
        : Tween<Offset>(
            begin: Offset(1.0, 0.0),
            end: Offset.zero,
          ).animate(CurvedAnimation(
            curve: Curves.linear,
            parent: _animationController,
          ));
    _animationController.forward();
  }

  @override
  void dispose() {
    super.dispose();
    _animationController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SlideTransition(
      position: _offsetAnimation,
      child: widget.child,
    );
  }
}

And a simple app to demonstrate the problem:

void main() => runApp(Test());

class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  bool widget1 = true;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: widget1
              ? CustomSlideAnimation(
                  child: InkWell(
                    child: Text('widget1'),
                    onTap: () {
                      setState(() {
                        widget1 = false;
                      });
                    },
                  ),
                  from: CustomSlideAnimation.FROM_LEFT,
                )
              : CustomSlideAnimation(
                  child: InkWell(
                    child: Text('widget2'),
                    onTap: () {
                      setState(() {
                        widget1 = true;
                      });
                    },
                  ),
                  from: CustomSlideAnimation.FROM_LEFT,
                ),
        ),
      ),
    );
  }
}

When I start the app for first time the Text widget as expected slides in to the screen,
but then I tap it and thus calling setState() the second Text widget just appears suddenly into the screen and no slide transition happens.

I printed the times when build get called in all the classes and I see that setState() is triggering builds in Test and CustomSlideTransition classes but not triggering initState() in the CustomSlideTransition.

EDIT for more clarification: even putting controller.forward() inside the build() method didn't work.

So what am I missing?

Body:
You just need to add a UniqueKey() to every CustomSlideAnimation() to tell flutter to treat them like different widgets.

void main() => runApp(Test());

class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  bool widget1 = true;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: widget1
              ? CustomSlideAnimation(
                  key: UniqueKey(),
                  child: InkWell(
                    child: Text('widget1'),
                    onTap: () {
                      setState(() {
                        widget1 = false;
                      });
                    },
                  ),
                  from: CustomSlideAnimation.FROM_LEFT,
                )
              : CustomSlideAnimation(
                  key: UniqueKey(),
                  child: InkWell(
                    child: Text('widget2'),
                    onTap: () {
                      setState(() {
                        widget1 = true;
                      });
                    },
                  ),
                  from: CustomSlideAnimation.FROM_LEFT,
                ),
        ),
      ),
    );
  }
}

Also, keep controller.forward() inside initState()


问:
Bootstrap dropdown menu doesn't open
Navber code:

                Home (current)

                  Behandelingen

                  Sportmassage
                  Massagetherapie
                  Ontspanningsmassage

                Afspraak maken

                Tarieven

                Contact

      ```
</div>
</div>
</p>

<p>Bootstrap code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
          integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"></code>```

Dropdown menu inside the navbar doesn't open, anyone an idea on how to fix this?
Not very experienced with bootstrap and don't now what the problem is.

答:
Your button don't call your div

```<code><button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
 Dropdown button
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
  <a class="dropdown-item" href="#">Action</a>
  <a class="dropdown-item" href="#">Another action</a>
  <a class="dropdown-item" href="#">Something else here</a>
</div>
</div>
</code>```

your "aria-labelledby" does not match the button id "id="dropdownMenuButton""

it's in the bootstrap documentation

Title: Bootstrap dropdown menu doesn't open

Body:
Navber code:

                Home (current)

                  Behandelingen

                  Sportmassage
                  Massagetherapie
                  Ontspanningsmassage

                Afspraak maken

                Tarieven

                Contact

Bootstrap code:

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
          integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Dropdown menu inside the navbar doesn't open, anyone an idea on how to fix this?
Not very experienced with bootstrap and don't now what the problem is.

Body:
Your button don't call your div

<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
 Dropdown button
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
  <a class="dropdown-item" href="#">Action</a>
  <a class="dropdown-item" href="#">Another action</a>
  <a class="dropdown-item" href="#">Something else here</a>
</div>
</div>

your "aria-labelledby" does not match the button id "id="dropdownMenuButton""

it's in the bootstrap documentation


问:
woocommerce show/get product thumbnails
I am trying to implement wooCommerce in a custom theme I am building based on bootstrap framework (because I'm picky about how things look) So what I am trying to do is relocate wooCommerce product thumbnail gallery images. I am aware of the various functions and hooks that are available through wooCommerce like the ones listed in the wc-template-hooks.php and they work great except in my particular situation. I used the "woocommerce_before_main_content" and "woocommerce_after_main_content"hooks to wrap the product info in my bootstrap frame like so...

```<code>...
<div class="row">
  <div class="col-md-1"> *where I want my gallery images to go* </div>
  <div class="col-md-7 *woocommerce-main"> where my woocommerce product is loaded* </div>
  <div class="col-md-4"> *some other product info is loaded here* </div>
</div>...
</code>```

What I have run into is that I can't seem to use any of the product hooks or functions until after the product section is called/loaded (which makes perfect sense of course) but I need to be able to load the product gallery images into the first column "col-md-1"... so my question is... how do I get the product gallery images before everything has completed loading or can I retroactively process what goes into the first column after everything has loaded?

Thanks

EDIT: complete woocommerce hooks in my functions.php

```<code><?php
remove_action( 'woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10);
remove_action( 'woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10);
remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_product_data_tabs', 10 );
remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 );
remove_action( 'woocommerce_product_thumbnails', 'woocommerce_show_product_thumbnails', 20 );

add_action('woocommerce_before_main_content', 'underwire_wrapper_start', 10);
add_action('woocommerce_after_main_content', 'underwire_wrapper_end', 10);

function underwire_wrapper_start() {
  echo '<div class="row">';
  if ( is_product() ) {
      echo '<div class="col-md-1">';
      echo woocommerce_get_product_thumbnail();
      //woocommerce_show_product_thumbnails();
    echo '</div>';
    echo '<div class="col-md-7 woocommerce-main">';
  } else {
    echo '<div class="col-sm-12 woocommerce-main">';
  }
}

function underwire_wrapper_end() {
  if ( is_product() ) {
    echo '</div> <!-- /.woocommerce-main --><div class="col-md-4">';
    woocommerce_output_product_data_tabs();
    //woocommerce_output_related_products();
    echo '</div></div>';
  } else {
    echo '</div> <!-- /.woocommerce-main --></div>';
  }
}
?>
</code>```

答:
2020 answer: This is an old post, but for anyone reading this, I believe you can hook into any part of the product page, and then in your custom hook function, use something like this to access the photo ids, using the $product object:

```<code>// priority number at the end can be whatever you want
add_action('action_you_want_to_hook_into', 'your_custom_function', 10);

function your_custom_function() {
    global $product;
    image_ids[] = $product->get_gallery_image_ids();
    // do something with image_ids[]
}
</code>```

hope this helps anyone who stumbles in here!

and here is a useful list of functions you can call on $product

Title: woocommerce show/get product thumbnails

Body:
I am trying to implement wooCommerce in a custom theme I am building based on bootstrap framework (because I'm picky about how things look) So what I am trying to do is relocate wooCommerce product thumbnail gallery images. I am aware of the various functions and hooks that are available through wooCommerce like the ones listed in the wc-template-hooks.php and they work great except in my particular situation. I used the "woocommerce_before_main_content" and "woocommerce_after_main_content"hooks to wrap the product info in my bootstrap frame like so...

...

 *where I want my gallery images to go*

 where my woocommerce product is loaded*

 *some other product info is loaded here*

...

What I have run into is that I can't seem to use any of the product hooks or functions until after the product section is called/loaded (which makes perfect sense of course) but I need to be able to load the product gallery images into the first column "col-md-1"... so my question is... how do I get the product gallery images before everything has completed loading or can I retroactively process what goes into the first column after everything has loaded?

Thanks

EDIT: complete woocommerce hooks in my functions.php

<?php
remove_action( 'woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10);
remove_action( 'woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10);
remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_product_data_tabs', 10 );
remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 );
remove_action( 'woocommerce_product_thumbnails', 'woocommerce_show_product_thumbnails', 20 );

add_action('woocommerce_before_main_content', 'underwire_wrapper_start', 10);
add_action('woocommerce_after_main_content', 'underwire_wrapper_end', 10);

function underwire_wrapper_start() {
  echo '
';
  if ( is_product() ) {
      echo '
';
      echo woocommerce_get_product_thumbnail();
      //woocommerce_show_product_thumbnails();
    echo '
';
    echo '
';
  } else {
    echo '
';
  }
}

function underwire_wrapper_end() {
  if ( is_product() ) {
    echo '

';
    woocommerce_output_product_data_tabs();
    //woocommerce_output_related_products();
    echo '

';
  } else {
    echo '

';
  }
}
?>

Body:
2020 answer: This is an old post, but for anyone reading this, I believe you can hook into any part of the product page, and then in your custom hook function, use something like this to access the photo ids, using the $product object:

// priority number at the end can be whatever you want
add_action('action_you_want_to_hook_into', 'your_custom_function', 10);

function your_custom_function() {
    global $product;
    image_ids[] = $product->get_gallery_image_ids();
    // do something with image_ids[]
}

hope this helps anyone who stumbles in here!

and here is a useful list of functions you can call on $product


问:
How to check current status of a Data Factory pipelinerun with just Pipeline name?
Is it possible to check the current status of a Azure Data Factory pipelinerun with just Pipeline name either through Powershell or API ?

I have seen that you can use Get-AzDataFactoryV2PipelineRun but that requires you to have the pipelinerunid.

My goal is to build a script that will first check if a pipeline run is running and if not trigger it. I want to avoid the script to trigger a pipelinerun so that there will be multiple pipeline runs running at the same time.

答:
I've done it with PowerShell, although I'm sure there are better ways, this is the solution I've come up with.

It basically gets all the pipeline run ids from a week ago to this day, iterates through each one and if it finds one that is "InProgress", it will not do anything. If no pipeline run id is in that state, then execute it.

You obviously need to be authenticated previously to run this:

```<code>$before = get-date
$after = (get-date).AddDays(-7)
$runIds = Get-AzDataFactoryV2PipelineRun -DataFactoryName $DataFactoryName -ResourceGroupName $ResourceGroupName -LastUpdatedAfter $after -LastUpdatedBefore
$before
$shouldRun = 1

$runIds | ForEach-Object {
    ## Check for all statuses
    if($_.Status -eq "InProgress"){
        $shouldRun = 0
    }
}

if($shouldRun){
    ## Logic to run pipeline, this is just an example.
    Invoke-AzDataFactoryV2Pipeline -PipelineName $PipelineName -ResourceGroupName $ResourceGroupName -DataFactoryName $DataFactoryName
}
</code>```

Body:
I've done it with PowerShell, although I'm sure there are better ways, this is the solution I've come up with.

It basically gets all the pipeline run ids from a week ago to this day, iterates through each one and if it finds one that is "InProgress", it will not do anything. If no pipeline run id is in that state, then execute it.

You obviously need to be authenticated previously to run this:

$before = get-date
$after = (get-date).AddDays(-7)
$runIds = Get-AzDataFactoryV2PipelineRun -DataFactoryName $DataFactoryName -ResourceGroupName $ResourceGroupName -LastUpdatedAfter $after -LastUpdatedBefore
$before
$shouldRun = 1

$runIds | ForEach-Object {
    ## Check for all statuses
    if($_.Status -eq "InProgress"){
        $shouldRun = 0
    }
}

if($shouldRun){
    ## Logic to run pipeline, this is just an example.
    Invoke-AzDataFactoryV2Pipeline -PipelineName $PipelineName -ResourceGroupName $ResourceGroupName -DataFactoryName $DataFactoryName
}


问:
Path to resources inside custom module
I have a module:

Obs.: It's not the root module

```
my-module
├── components
|   └── my-component
|        └── my-component.html
└── images
    └── my-image.png
```

I am trying to set the path to "my-image.png" inside "my-component.html".

I have already tried to following ways:

```

    img src="./images/my-image.png"
    img src="../images/my-image.png"
    img src="/images/my-image.png"

```

But when i serve my app, angular resolves my paths to:

```

    localhost:4200/./images/my-image.png
    localhost:4200/../images/my-image.png
    localhost:4200/images/my-image.png

```

I want angular to resolve my path relative to the module where my html file is inside.
How can i do that?

答:
You can achive this by adding path in angular.json like below

```<code> "assets": [
              "src/favicon.ico",
              "src/assets",
              "my-module/images"
            ],
</code>```

and in img try this

```<code>img src="images/my-image.png"
</code>```

Hope useful

Title: Path to resources inside custom module

Body:
I have a module:

Obs.: It's not the root module

my-module
├── components
|   └── my-component
|        └── my-component.html
└── images
    └── my-image.png

I am trying to set the path to "my-image.png" inside "my-component.html".

I have already tried to following ways:

    img src="./images/my-image.png"
    img src="../images/my-image.png"
    img src="/images/my-image.png"

But when i serve my app, angular resolves my paths to:

    localhost:4200/./images/my-image.png
    localhost:4200/../images/my-image.png
    localhost:4200/images/my-image.png

I want angular to resolve my path relative to the module where my html file is inside.
How can i do that?

Body:
You can achive this by adding path in angular.json like below

 "assets": [
              "src/favicon.ico",
              "src/assets",
              "my-module/images"
            ],

and in img try this

img src="images/my-image.png"

Hope useful


问:
How to include array content in HTML?
I have this code

```<code>var users = result.users; // array

$("#dialog:ui-dialog").dialog("destroy");

$("#dialog-confirm").dialog({
    resizable: false,
    height: 140,
    modal: true,
    open: function() {
    $(this).children('div.dialog-text').replaceWith("<b>New text goes here</b>");
    },

    buttons: {
    "Okay": function() {
        $(this).dialog("close");
    },
    Cancel: function() {
        is_okay = 0;
        $(this).dialog("close");
    }
    }
});
</code>```

where the array contain data in the form of

```<code>{"ss":"Sandra Schlichting","fn":"Full name"}
</code>```

What I am trying to accomplish is to get the content of the arrays in the form of (white space inserted for readability)

```<code><table>
  <tr>  <td>Initials</td>  <td>Full Name         </td>  </tr>
  <tr>  <td>ss      </td>  <td>Sandra Schlichting</td>  </tr>
  <tr>  <td>fn      </td>  <td>Full name         </td>  </tr>
</table>
</code>```

and have that replaced with New text goes here in

```<code>$(this).children('div.dialog-text').replaceWith("<b>New text goes here</b>");
</code>```

From what I can tell $.each() should be used for this.

But still I can't quite figure out how to get started.

Can anyone help me out?

答:
You can use a JS for-in to loop through it.

```<code><table id='nameTable'>
  <tr>  <td>Initials</td>  <td>Full Name         </td>  </tr>
</table>

var names = {
    "ss": "Sandra Schlichting",
    "fn": "Full name"
};
var $table = $('#nameTable');
var row   = '';
for (name in names) {
    row += '<tr><td>' + name + '</td><td>' + names[name] + '</td></tr>';
}
$table.append(row)
</code>```

Here's a fiddle : http://jsfiddle.net/exP2b/4/

Title: How to include array content in HTML?

Body:
I have this code

var users = result.users; // array

$("#dialog:ui-dialog").dialog("destroy");

$("#dialog-confirm").dialog({
    resizable: false,
    height: 140,
    modal: true,
    open: function() {
    $(this).children('div.dialog-text').replaceWith("New text goes here");
    },

    buttons: {
    "Okay": function() {
        $(this).dialog("close");
    },
    Cancel: function() {
        is_okay = 0;
        $(this).dialog("close");
    }
    }
});

where the array contain data in the form of

{"ss":"Sandra Schlichting","fn":"Full name"}

What I am trying to accomplish is to get the content of the arrays in the form of (white space inserted for readability)

  Initials	  Full Name

  ss      	  Sandra Schlichting

  fn      	  Full name

and have that replaced with New text goes here in

$(this).children('div.dialog-text').replaceWith("New text goes here");

From what I can tell $.each() should be used for this.

But still I can't quite figure out how to get started.

Can anyone help me out?

Body:
You can use a JS for-in to loop through it.

<table id='nameTable'>
  <tr>  <td>Initials</td>  <td>Full Name         </td>  </tr>
</table>

var names = {
    "ss": "Sandra Schlichting",
    "fn": "Full name"
};
var $table = $('#nameTable');
var row   = '';
for (name in names) {
    row += '<tr><td>' + name + '</td><td>' + names[name] + '</td></tr>';
}
$table.append(row)

Here's a fiddle : http://jsfiddle.net/exP2b/4/


问:
Get element index of array of objects with the "highest" value for given key
Let's say I have the following array of objects:

```<code>[
   { name: 'january', score: 3.02 },
   { name: 'february', score: 1.02 },
   { name: 'march', score: 0 },
   { name: 'april', score: 12 },
]
</code>```

What would be the quickest method for extract the position (index) of the element of the object with the highest score value...so, in the above case, the value would be index 3...

N.B. Scores are dynamic, and the "winning" element is the highest value...

答:
var data = [
   { name: 'january', score: 3.02 },
   { name: 'february', score: 1.02 },
   { name: 'march', score: 0 },
   { name: 'april', score: 12 },
];

var resultValue = null;
var tempValue = Number.NEGATIVE_INFINITY;
data.forEach(function(element, index) {
    if(element.score > tempValue) {
        tempValue = element.score;
        resultValue = index;
    }
});

console.log(resultValue);```

Body:
Let's say I have the following array of objects:

[
   { name: 'january', score: 3.02 },
   { name: 'february', score: 1.02 },
   { name: 'march', score: 0 },
   { name: 'april', score: 12 },
]

What would be the quickest method for extract the position (index) of the element of the object with the highest score value...so, in the above case, the value would be index 3...

N.B. Scores are dynamic, and the "winning" element is the highest value...


问:
How can overwrite objects that have the same key in updating State with state hooks
I want to update the state when new filters are selected. the initial state shows the object structure i am aiming for. for example, i add a filter selection (for example "f2"), the label is fixed per filter, so we can neglect it, but the value maybe "va". Thats works fine, but when i want to change the value for "f2" to "vb", i now have two entries in my state {"f2":"va"} and {"f2":"vb"}, while i would rather have the first one  overwritten by the second.

```<code> const [filterValues, setFilterValues] = useState([{"f1":["l","v"]}]);

 const handleChange = (filter, label, value) => {
   setFilterValues([
     ...filterValues,
     {[filter]: [label, value]}
   ]);
 };
</code>```

i tried callin setFilterValues twice (once with mapping the entries to my condition) to solve the problem, but then i didnt even update state at all:

```<code> const handleChange = (filter, label, value) => {
    setFilterValues([
      ...filterValues,
      {[filter]: [label, value]}
    ]);
    let key = filter
    setFilterValues(
      filterValues.map(
        el => el.key == key?  { [key]: [label, value] } : el
      )
    )
  };
</code>```

i am a little bit new to react, so maybe i dont get a fundamental thing with updating state in functional components. can anybody help me with this? thank you!

答:
The way to do it would be finding the right object and changing its value before setting the state:

```<code>const handleChange = (filter, label, value) => {
   const currentFilters = [...filterValues] // A new copy of the state.
   const newFilters = currentFilters.map(stateFilter => stateFilter[filter] ? {[filter]: [label, value]} : stateFilter)
   setFilterValues(newFilters);
 };
</code>```

While I believe this solves your case, I think it would be better if you stored your filters in an array, meanning an object structure of:

```<code>[[l1,v1], [l1, v2]]
</code>```

That way, filter one is just index 0 on your filter array, and so on. So to do what you want, you will have a function that receives a filter number, label and value:

```<code>const handleChange = (filter, label, value) => {
   let newFilters = [...filterValues] // A new copy of the state.
   newFilters[filter - 1] = [label, value];
   setFilterValues(newFilters);
 };
</code>```

Please note that if you receive a filter number of 1, meanning the first filter, you want to access place 0 on the filters array.

Body:
I want to update the state when new filters are selected. the initial state shows the object structure i am aiming for. for example, i add a filter selection (for example "f2"), the label is fixed per filter, so we can neglect it, but the value maybe "va". Thats works fine, but when i want to change the value for "f2" to "vb", i now have two entries in my state {"f2":"va"} and {"f2":"vb"}, while i would rather have the first one  overwritten by the second.

 const [filterValues, setFilterValues] = useState([{"f1":["l","v"]}]);

 const handleChange = (filter, label, value) => {
   setFilterValues([
     ...filterValues,
     {[filter]: [label, value]}
   ]);
 };

i tried callin setFilterValues twice (once with mapping the entries to my condition) to solve the problem, but then i didnt even update state at all:

 const handleChange = (filter, label, value) => {
    setFilterValues([
      ...filterValues,
      {[filter]: [label, value]}
    ]);
    let key = filter
    setFilterValues(
      filterValues.map(
        el => el.key == key?  { [key]: [label, value] } : el
      )
    )
  };

i am a little bit new to react, so maybe i dont get a fundamental thing with updating state in functional components. can anybody help me with this? thank you!

Body:
The way to do it would be finding the right object and changing its value before setting the state:

const handleChange = (filter, label, value) => {
   const currentFilters = [...filterValues] // A new copy of the state.
   const newFilters = currentFilters.map(stateFilter => stateFilter[filter] ? {[filter]: [label, value]} : stateFilter)
   setFilterValues(newFilters);
 };

While I believe this solves your case, I think it would be better if you stored your filters in an array, meanning an object structure of:

[[l1,v1], [l1, v2]]

That way, filter one is just index 0 on your filter array, and so on. So to do what you want, you will have a function that receives a filter number, label and value:

const handleChange = (filter, label, value) => {
   let newFilters = [...filterValues] // A new copy of the state.
   newFilters[filter - 1] = [label, value];
   setFilterValues(newFilters);
 };

Please note that if you receive a filter number of 1, meanning the first filter, you want to access place 0 on the filters array.


问:
Download all dependencies recursively from a rpm file
I know that I can retrieve all dependencies recursively using yumdownloader  --downloadonly. But is there a way that I can do it by passing the an rpm file instead of the package name? like yum install ./google-chrome-stable_current_x86_64.rpm --downloadonly --downloaddir=xx with some option to download dependencies of chrome's dependencies.

答:
Why dont you pull the NEVRA from the RPM file and pass it to yumdownloader

yumdownloader --resolve $(rpm -qp ./<RPMPACKAGE>.rpm --queryformat="%{nevra}")


答:
You could get the keys and reduce the indices by checking the score.

var data = [{ name: 'january', score: 3.02 }, { name: 'february', score: 1.02 }, { name: 'march', score: 0 }, { name: 'april', score: 12 }],
    index = [...data.keys()].reduce((a, b) => data[a].score > data[b].score ? a : b);

console.log(index);```

Title: Get element index of array of objects with the "highest" value for given key