问:
error C2664: cannot convert argument 1 from 'NvPhysicalGpuHandle'
I'm trying to add Nvidia API into kodi for HDR switching.
I don't have much knowledge of code, I'm trying to adapt a project HDR Switcher into kodi functions.

When compiling the HDR Switcher into an exe with visual studio it works and triggers HDR.
Now I need to make it work with kodi for seamless HDR pasthrough playback.

This uses the NVidia private APIs.

Please help this will be valuable for many users if it gets implemented.

The error:
error C2664: 'NvAPI_St
atus NvAPI_GPU_GetConnectedDisplayIds(NvPhysicalGpuHandle,NV_GPU_DISPLAYIDS *,NvU32 *,NvU32)': cannot convert argument
1 from 'NvPhysicalGpuHandle [64]' to 'NvPhysicalGpuHandle'

```<code>#include "WinRenderer.h"
#include "RenderCapture.h"
#include "RenderFactory.h"
#include "RenderFlags.h"
#include "rendering/dx/RenderContext.h"
#include "settings/Settings.h"
#include "settings/SettingsComponent.h"
#include "utils/log.h"
#include "windows/RendererDXVA.h"
#include "windows/RendererSoftware.h"
#include "windows/RendererShaders.h"
#include "windowing/GraphicContext.h"
#include "windowing/WinSystem.h"
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include "DeviceManager.h"
#include "nvapi.h"
#include "uhdDisplay.h"

struct render_details
{
  using map = std::map<RenderMethod, int>;
  using weights_fn = std::function<void(map&, const VideoPicture&)>;
  using create_fn = std::function<CRendererBase*(CVideoSettings&)>;

  RenderMethod method;
  std::string name;
  create_fn create;
  weights_fn weights;

  template<class T>
  constexpr static render_details get(RenderMethod method, const std::string& name)
  {
    return { method, name, T::Create, T::GetWeight };
  }
};

static std::vector<render_details> RenderMethodDetails =
{
  render_details::get<CRendererSoftware>(RENDER_SW, "Software"),
  render_details::get<CRendererShaders>(RENDER_PS, "Pixel Shaders"),
  render_details::get<CRendererDXVA>(RENDER_DXVA, "DXVA"),
};

CBaseRenderer* CWinRenderer::Create(CVideoBuffer*)
{
  return new CWinRenderer();
}

bool CWinRenderer::Register()
{
  VIDEOPLAYER::CRendererFactory::RegisterRenderer("default", Create);
  return true;
}

CWinRenderer::CWinRenderer()
{
  m_format = AV_PIX_FMT_NONE;
  PreInit();
}

CWinRenderer::~CWinRenderer()
{
  CWinRenderer::UnInit();
}

CRendererBase* CWinRenderer::SelectRenderer(const VideoPicture& picture)
{
  int iRequestedMethod = CServiceBroker::GetSettingsComponent()->GetSettings()->GetInt(CSettings::SETTING_VIDEOPLAYER_RENDERMETHOD);
  CLog::LogF(LOGDEBUG, "requested render method: %d", iRequestedMethod);

  std::map<RenderMethod, int> weights;
  for (auto& details : RenderMethodDetails)
    details.weights(weights, picture);

  RenderMethod method;
  switch (iRequestedMethod)
  {
  case RENDER_METHOD_SOFTWARE:
    if (weights[RENDER_SW])
    {
      method = RENDER_SW;
      break;
    }
    // fallback to PS
  case RENDER_METHOD_D3D_PS:
    if (weights[RENDER_PS])
    {
      method = RENDER_PS;
      break;
    }
    //fallback to DXVA
  case RENDER_METHOD_DXVA:
    if (weights[RENDER_DXVA])
    {
      method = RENDER_DXVA;
      break;
    }
    // fallback to AUTO
  case RENDER_METHOD_AUTO:
  default:
  {
    const auto it = std::max_element(weights.begin(), weights.end(),
      [](auto& w1, auto& w2) { return w1.second < w2.second; });

    if (it != weights.end())
    {
      method = it->first;
      break;
    }

    // there is no elements in weights, so no renderer which supports incoming video buffer
    CLog::LogF(LOGERROR, "unable to select render method for video buffer");
    return nullptr;
  }
  }

  const auto it = std::find_if(RenderMethodDetails.begin(), RenderMethodDetails.end(),
    [method](render_details& d) { return d.method == method; });

  if (it != RenderMethodDetails.end())
  {
    CLog::LogF(LOGDEBUG, "selected render method: {}", it->name);
    return it->create(m_videoSettings);
  }

  // something goes really wrong
  return nullptr;
}

CRect CWinRenderer::GetScreenRect() const
{
  CRect screenRect(0.f, 0.f,
    static_cast<float>(CServiceBroker::GetWinSystem()->GetGfxContext().GetWidth()),
    static_cast<float>(CServiceBroker::GetWinSystem()->GetGfxContext().GetHeight()));

  switch (CServiceBroker::GetWinSystem()->GetGfxContext().GetStereoMode())
  {
  case RENDER_STEREO_MODE_SPLIT_HORIZONTAL:
    screenRect.y2 *= 2;
    break;
  case RENDER_STEREO_MODE_SPLIT_VERTICAL:
    screenRect.x2 *= 2;
    break;
  default:
    break;
  }

  return screenRect;
}

bool CWinRenderer::Configure(const VideoPicture &picture, float fps, unsigned int orientation)
{
  m_sourceWidth       = picture.iWidth;
  m_sourceHeight      = picture.iHeight;
  m_renderOrientation = orientation;
  m_fps = fps;
  m_iFlags = GetFlagsChromaPosition(picture.chroma_position)
           | GetFlagsColorMatrix(picture.color_space, picture.iWidth, picture.iHeight)
           | GetFlagsColorPrimaries(picture.color_primaries)
           | GetFlagsStereoMode(picture.stereoMode);
  m_format = picture.videoBuffer->GetFormat();

  // calculate the input frame aspect ratio
  CalculateFrameAspectRatio(picture.iDisplayWidth, picture.iDisplayHeight);
  SetViewMode(m_videoSettings.m_ViewMode);
  // if (picture.hasDisplayMetadata || picture.hasLightMetadata) {
  SetHdrMonitorMode(true);
    // }
  ManageRenderArea();

  m_renderer.reset(SelectRenderer(picture));
  if (!m_renderer || !m_renderer->Configure(picture, fps, orientation))
  {
    m_renderer.reset();
    return false;
  }

  m_bConfigured = true;
  return true;
}
static bool first = true;

void CWinRenderer::SetHdrMonitorMode(bool enableHDR)
{
    if (first)
    {
        NvAPI_Initialize();
        first = false;
    }

    NvAPI_Status nvStatus = NVAPI_OK;
    NvDisplayHandle hNvDisplay = NULL;

    // get first display handle which should work for all NVAPI calls for all GPUs
    if ((nvStatus = NvAPI_EnumNvidiaDisplayHandle(0, &hNvDisplay)) != NVAPI_OK)
    {
        printf("NvAPI_EnumNvidiaDisplayHandle returned error code %d\r\n", nvStatus);

        return;
    }

    NvU32 gpuCount = 0;
    NvU32 maxDisplayIndex = 0;
    NvPhysicalGpuHandle ahGPU[NVAPI_MAX_PHYSICAL_GPUS] = {};

    // get the list of displays connected, populate the dynamic components
    nvStatus = NvAPI_EnumPhysicalGPUs(ahGPU, &gpuCount);

    if (NVAPI_OK != nvStatus)
    {
        printf("NvAPI_EnumPhysicalGPUs returned error code %d\r\n", nvStatus);

        return;
    }

    for (NvU32 i = 0; i < gpuCount; ++i)
    {
        NvU32 displayIdCount = 16;
        NvU32 flags = 0;
        NV_GPU_DISPLAYIDS displayIdArray[16] = {};
        displayIdArray[0].version = NV_GPU_DISPLAYIDS_VER;

        nvStatus = NvAPI_GPU_GetConnectedDisplayIds(ahGPU, displayIdArray, &displayIdCount, flags);

        if (NVAPI_OK == nvStatus)
        {
            printf("Display count %d\r\n", displayIdCount);

            for (maxDisplayIndex = 0; maxDisplayIndex < displayIdCount; ++maxDisplayIndex)
            {
                printf("Display tested %d\r\n", maxDisplayIndex);

                NV_HDR_CAPABILITIES hdrCapabilities = {};

                hdrCapabilities.version = NV_HDR_CAPABILITIES_VER;

                if (NVAPI_OK == NvAPI_Disp_GetHdrCapabilities(displayIdArray[maxDisplayIndex].displayId, &hdrCapabilities))
                {
                    if (hdrCapabilities.isST2084EotfSupported)
                    {
                        printf("Display %d supports ST2084 EOTF\r\n", maxDisplayIndex);

                        NV_HDR_COLOR_DATA hdrColorData = {};

                        memset(&hdrColorData, 0, sizeof(hdrColorData));

                        hdrColorData.version = NV_HDR_COLOR_DATA_VER;
                        hdrColorData.cmd = NV_HDR_CMD_SET;
                        hdrColorData.static_metadata_descriptor_id = NV_STATIC_METADATA_TYPE_1;

                        hdrColorData.hdrMode = enableHDR ? NV_HDR_MODE_UHDBD : NV_HDR_MODE_OFF;

                        nvStatus = NvAPI_Disp_HdrColorControl(displayIdArray[maxDisplayIndex].displayId, &hdrColorData);

                        if (NVAPI_OK == nvStatus)
                        {
                            printf("NvAPI_Disp_SethdrColorData call has succeeded: ");
                        }
                        else
                        {
                            NvAPI_ShortString szDesc;
                            NvAPI_GetErrorMessage(nvStatus, szDesc);
                            printf("NvAPI_Disp_HdrColorControl returned %s (%x)\r\n", szDesc, nvStatus);
                        }
                    }
                }
                else
                {
                    NvAPI_ShortString szDesc;
                    NvAPI_GetErrorMessage(nvStatus, szDesc);
                    printf("NvAPI_Disp_GetHdrCapabilities returned %s (%x)\r\n", szDesc, nvStatus);
                }
            }
        }
        else
        {
            NvAPI_ShortString szDesc;
            NvAPI_GetErrorMessage(nvStatus, szDesc);
            printf("NvAPI_GPU_GetConnectedDisplayIds returned %s (%x)\r\n", szDesc, nvStatus);
        }
    }
  }

int CWinRenderer::NextBuffer() const
{
  return m_renderer->NextBuffer();
}

void CWinRenderer::AddVideoPicture(const VideoPicture &picture, int index)
{
  m_renderer->AddVideoPicture(picture, index);
}

void CWinRenderer::Update()
{
  if (!m_bConfigured)
    return;

  ManageRenderArea();
  m_renderer->ManageTextures();
}

void CWinRenderer::RenderUpdate(int index, int index2, bool clear, unsigned int flags, unsigned int alpha)
{
  if (!m_bConfigured)
    return;

  if (clear)
    CServiceBroker::GetWinSystem()->GetGfxContext().Clear(DX::Windowing()->UseLimitedColor() ? 0x101010 : 0);
  DX::Windowing()->SetAlphaBlendEnable(alpha < 255);

  ManageRenderArea();
  m_renderer->Render(index, index2, DX::Windowing()->GetBackBuffer(),
                     m_sourceRect, m_destRect, GetScreenRect(), flags);
}

bool CWinRenderer::RenderCapture(CRenderCapture* capture)
{
  if (!m_bConfigured)
    return false;

  capture->BeginRender();
  if (capture->GetState() != CAPTURESTATE_FAILED)
  {
    const CRect destRect(0, 0, static_cast<float>(capture->GetWidth()), static_cast<float>(capture->GetHeight()));

    m_renderer->Render(capture->GetTarget(), m_sourceRect, destRect, GetScreenRect());
    capture->EndRender();

    return true;
  }

  return false;
}

void CWinRenderer::SetBufferSize(int numBuffers)
{
  if (!m_bConfigured)
    return;

  m_renderer->SetBufferSize(numBuffers);
}

void CWinRenderer::PreInit()
{
  CSingleLock lock(CServiceBroker::GetWinSystem()->GetGfxContext());
  m_bConfigured = false;
  UnInit();
}

void CWinRenderer::UnInit()
{
  CSingleLock lock(CServiceBroker::GetWinSystem()->GetGfxContext());

  m_renderer.reset();
  m_bConfigured = false;
}

bool CWinRenderer::Flush(bool saveBuffers)
{
  if (!m_bConfigured)
    return false;

  return m_renderer->Flush(saveBuffers);
}

bool CWinRenderer::Supports(ERENDERFEATURE feature)
{
  if(feature == RENDERFEATURE_BRIGHTNESS)
    return true;

  if(feature == RENDERFEATURE_CONTRAST)
    return true;

  if (feature == RENDERFEATURE_STRETCH         ||
      feature == RENDERFEATURE_NONLINSTRETCH   ||
      feature == RENDERFEATURE_ZOOM            ||
      feature == RENDERFEATURE_VERTICAL_SHIFT  ||
      feature == RENDERFEATURE_PIXEL_RATIO     ||
      feature == RENDERFEATURE_ROTATION        ||
      feature == RENDERFEATURE_POSTPROCESS     ||
      feature == RENDERFEATURE_TONEMAP)
    return true;

  return false;
}

bool CWinRenderer::Supports(ESCALINGMETHOD method)
{
  if (!m_bConfigured)
    return false;

  return m_renderer->Supports(method);
}

bool CWinRenderer::WantsDoublePass()
{
  if (!m_bConfigured)
    return false;

  return m_renderer->WantsDoublePass();
}

bool CWinRenderer::ConfigChanged(const VideoPicture& picture)
{
  if (!m_bConfigured)
    return true;

  return picture.videoBuffer->GetFormat() != m_format;
}

CRenderInfo CWinRenderer::GetRenderInfo()
{
  if (!m_bConfigured)
    return {};

  return m_renderer->GetRenderInfo();
}

void CWinRenderer::ReleaseBuffer(int idx)
{
  if (!m_bConfigured)
    return;

  m_renderer->ReleaseBuffer(idx);
}

bool CWinRenderer::NeedBuffer(int idx)
{
  if (!m_bConfigured)
    return false;

  return m_renderer->NeedBuffer(idx);
}

´´´
</code>```

答:
Change

```<code>nvStatus = NvAPI_GPU_GetConnectedDisplayIds(ahGPU, displayIdArray, &displayIdCount, flags);
</code>```

to

```<code>nvStatus = NvAPI_GPU_GetConnectedDisplayIds(ahGPU[i], displayIdArray, &displayIdCount, flags);
</code>```

Thanks to @1201ProgramAlarm

Body:
I'm trying to add Nvidia API into kodi for HDR switching.
I don't have much knowledge of code, I'm trying to adapt a project HDR Switcher into kodi functions.

When compiling the HDR Switcher into an exe with visual studio it works and triggers HDR.
Now I need to make it work with kodi for seamless HDR pasthrough playback.

This uses the NVidia private APIs.

Please help this will be valuable for many users if it gets implemented.

The error:
error C2664: 'NvAPI_St
atus NvAPI_GPU_GetConnectedDisplayIds(NvPhysicalGpuHandle,NV_GPU_DISPLAYIDS *,NvU32 *,NvU32)': cannot convert argument
1 from 'NvPhysicalGpuHandle [64]' to 'NvPhysicalGpuHandle'

#include "WinRenderer.h"
#include "RenderCapture.h"
#include "RenderFactory.h"
#include "RenderFlags.h"
#include "rendering/dx/RenderContext.h"
#include "settings/Settings.h"
#include "settings/SettingsComponent.h"
#include "utils/log.h"
#include "windows/RendererDXVA.h"
#include "windows/RendererSoftware.h"
#include "windows/RendererShaders.h"
#include "windowing/GraphicContext.h"
#include "windowing/WinSystem.h"
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include "DeviceManager.h"
#include "nvapi.h"
#include "uhdDisplay.h"

struct render_details
{
  using map = std::map<RenderMethod, int>;
  using weights_fn = std::function<void(map&, const VideoPicture&)>;
  using create_fn = std::function<CRendererBase*(CVideoSettings&)>;

  RenderMethod method;
  std::string name;
  create_fn create;
  weights_fn weights;

  template<class T>
  constexpr static render_details get(RenderMethod method, const std::string& name)
  {
    return { method, name, T::Create, T::GetWeight };
  }
};

static std::vector<render_details> RenderMethodDetails =
{
  render_details::get<CRendererSoftware>(RENDER_SW, "Software"),
  render_details::get<CRendererShaders>(RENDER_PS, "Pixel Shaders"),
  render_details::get<CRendererDXVA>(RENDER_DXVA, "DXVA"),
};

CBaseRenderer* CWinRenderer::Create(CVideoBuffer*)
{
  return new CWinRenderer();
}

bool CWinRenderer::Register()
{
  VIDEOPLAYER::CRendererFactory::RegisterRenderer("default", Create);
  return true;
}

CWinRenderer::CWinRenderer()
{
  m_format = AV_PIX_FMT_NONE;
  PreInit();
}

CWinRenderer::~CWinRenderer()
{
  CWinRenderer::UnInit();
}

CRendererBase* CWinRenderer::SelectRenderer(const VideoPicture& picture)
{
  int iRequestedMethod = CServiceBroker::GetSettingsComponent()->GetSettings()->GetInt(CSettings::SETTING_VIDEOPLAYER_RENDERMETHOD);
  CLog::LogF(LOGDEBUG, "requested render method: %d", iRequestedMethod);

  std::map<RenderMethod, int> weights;
  for (auto& details : RenderMethodDetails)
    details.weights(weights, picture);

  RenderMethod method;
  switch (iRequestedMethod)
  {
  case RENDER_METHOD_SOFTWARE:
    if (weights[RENDER_SW])
    {
      method = RENDER_SW;
      break;
    }
    // fallback to PS
  case RENDER_METHOD_D3D_PS:
    if (weights[RENDER_PS])
    {
      method = RENDER_PS;
      break;
    }
    //fallback to DXVA
  case RENDER_METHOD_DXVA:
    if (weights[RENDER_DXVA])
    {
      method = RENDER_DXVA;
      break;
    }
    // fallback to AUTO
  case RENDER_METHOD_AUTO:
  default:
  {
    const auto it = std::max_element(weights.begin(), weights.end(),
      [](auto& w1, auto& w2) { return w1.second < w2.second; });

    if (it != weights.end())
    {
      method = it->first;
      break;
    }

    // there is no elements in weights, so no renderer which supports incoming video buffer
    CLog::LogF(LOGERROR, "unable to select render method for video buffer");
    return nullptr;
  }
  }

  const auto it = std::find_if(RenderMethodDetails.begin(), RenderMethodDetails.end(),
    [method](render_details& d) { return d.method == method; });

  if (it != RenderMethodDetails.end())
  {
    CLog::LogF(LOGDEBUG, "selected render method: {}", it->name);
    return it->create(m_videoSettings);
  }

  // something goes really wrong
  return nullptr;
}

CRect CWinRenderer::GetScreenRect() const
{
  CRect screenRect(0.f, 0.f,
    static_cast<float>(CServiceBroker::GetWinSystem()->GetGfxContext().GetWidth()),
    static_cast<float>(CServiceBroker::GetWinSystem()->GetGfxContext().GetHeight()));

  switch (CServiceBroker::GetWinSystem()->GetGfxContext().GetStereoMode())
  {
  case RENDER_STEREO_MODE_SPLIT_HORIZONTAL:
    screenRect.y2 *= 2;
    break;
  case RENDER_STEREO_MODE_SPLIT_VERTICAL:
    screenRect.x2 *= 2;
    break;
  default:
    break;
  }

  return screenRect;
}

bool CWinRenderer::Configure(const VideoPicture &picture, float fps, unsigned int orientation)
{
  m_sourceWidth       = picture.iWidth;
  m_sourceHeight      = picture.iHeight;
  m_renderOrientation = orientation;
  m_fps = fps;
  m_iFlags = GetFlagsChromaPosition(picture.chroma_position)
           | GetFlagsColorMatrix(picture.color_space, picture.iWidth, picture.iHeight)
           | GetFlagsColorPrimaries(picture.color_primaries)
           | GetFlagsStereoMode(picture.stereoMode);
  m_format = picture.videoBuffer->GetFormat();

  // calculate the input frame aspect ratio
  CalculateFrameAspectRatio(picture.iDisplayWidth, picture.iDisplayHeight);
  SetViewMode(m_videoSettings.m_ViewMode);
  // if (picture.hasDisplayMetadata || picture.hasLightMetadata) {
  SetHdrMonitorMode(true);
    // }
  ManageRenderArea();

  m_renderer.reset(SelectRenderer(picture));
  if (!m_renderer || !m_renderer->Configure(picture, fps, orientation))
  {
    m_renderer.reset();
    return false;
  }

  m_bConfigured = true;
  return true;
}
static bool first = true;

void CWinRenderer::SetHdrMonitorMode(bool enableHDR)
{
    if (first)
    {
        NvAPI_Initialize();
        first = false;
    }

    NvAPI_Status nvStatus = NVAPI_OK;
    NvDisplayHandle hNvDisplay = NULL;

    // get first display handle which should work for all NVAPI calls for all GPUs
    if ((nvStatus = NvAPI_EnumNvidiaDisplayHandle(0, &hNvDisplay)) != NVAPI_OK)
    {
        printf("NvAPI_EnumNvidiaDisplayHandle returned error code %d\r\n", nvStatus);

        return;
    }

    NvU32 gpuCount = 0;
    NvU32 maxDisplayIndex = 0;
    NvPhysicalGpuHandle ahGPU[NVAPI_MAX_PHYSICAL_GPUS] = {};

    // get the list of displays connected, populate the dynamic components
    nvStatus = NvAPI_EnumPhysicalGPUs(ahGPU, &gpuCount);

    if (NVAPI_OK != nvStatus)
    {
        printf("NvAPI_EnumPhysicalGPUs returned error code %d\r\n", nvStatus);

        return;
    }

    for (NvU32 i = 0; i < gpuCount; ++i)
    {
        NvU32 displayIdCount = 16;
        NvU32 flags = 0;
        NV_GPU_DISPLAYIDS displayIdArray[16] = {};
        displayIdArray[0].version = NV_GPU_DISPLAYIDS_VER;

        nvStatus = NvAPI_GPU_GetConnectedDisplayIds(ahGPU, displayIdArray, &displayIdCount, flags);

        if (NVAPI_OK == nvStatus)
        {
            printf("Display count %d\r\n", displayIdCount);

            for (maxDisplayIndex = 0; maxDisplayIndex < displayIdCount; ++maxDisplayIndex)
            {
                printf("Display tested %d\r\n", maxDisplayIndex);

                NV_HDR_CAPABILITIES hdrCapabilities = {};

                hdrCapabilities.version = NV_HDR_CAPABILITIES_VER;

                if (NVAPI_OK == NvAPI_Disp_GetHdrCapabilities(displayIdArray[maxDisplayIndex].displayId, &hdrCapabilities))
                {
                    if (hdrCapabilities.isST2084EotfSupported)
                    {
                        printf("Display %d supports ST2084 EOTF\r\n", maxDisplayIndex);

                        NV_HDR_COLOR_DATA hdrColorData = {};

                        memset(&hdrColorData, 0, sizeof(hdrColorData));

                        hdrColorData.version = NV_HDR_COLOR_DATA_VER;
                        hdrColorData.cmd = NV_HDR_CMD_SET;
                        hdrColorData.static_metadata_descriptor_id = NV_STATIC_METADATA_TYPE_1;

                        hdrColorData.hdrMode = enableHDR ? NV_HDR_MODE_UHDBD : NV_HDR_MODE_OFF;

                        nvStatus = NvAPI_Disp_HdrColorControl(displayIdArray[maxDisplayIndex].displayId, &hdrColorData);

                        if (NVAPI_OK == nvStatus)
                        {
                            printf("NvAPI_Disp_SethdrColorData call has succeeded: ");
                        }
                        else
                        {
                            NvAPI_ShortString szDesc;
                            NvAPI_GetErrorMessage(nvStatus, szDesc);
                            printf("NvAPI_Disp_HdrColorControl returned %s (%x)\r\n", szDesc, nvStatus);
                        }
                    }
                }
                else
                {
                    NvAPI_ShortString szDesc;
                    NvAPI_GetErrorMessage(nvStatus, szDesc);
                    printf("NvAPI_Disp_GetHdrCapabilities returned %s (%x)\r\n", szDesc, nvStatus);
                }
            }
        }
        else
        {
            NvAPI_ShortString szDesc;
            NvAPI_GetErrorMessage(nvStatus, szDesc);
            printf("NvAPI_GPU_GetConnectedDisplayIds returned %s (%x)\r\n", szDesc, nvStatus);
        }
    }
  }

int CWinRenderer::NextBuffer() const
{
  return m_renderer->NextBuffer();
}

void CWinRenderer::AddVideoPicture(const VideoPicture &picture, int index)
{
  m_renderer->AddVideoPicture(picture, index);
}

void CWinRenderer::Update()
{
  if (!m_bConfigured)
    return;

  ManageRenderArea();
  m_renderer->ManageTextures();
}

void CWinRenderer::RenderUpdate(int index, int index2, bool clear, unsigned int flags, unsigned int alpha)
{
  if (!m_bConfigured)
    return;

  if (clear)
    CServiceBroker::GetWinSystem()->GetGfxContext().Clear(DX::Windowing()->UseLimitedColor() ? 0x101010 : 0);
  DX::Windowing()->SetAlphaBlendEnable(alpha < 255);

  ManageRenderArea();
  m_renderer->Render(index, index2, DX::Windowing()->GetBackBuffer(),
                     m_sourceRect, m_destRect, GetScreenRect(), flags);
}

bool CWinRenderer::RenderCapture(CRenderCapture* capture)
{
  if (!m_bConfigured)
    return false;

  capture->BeginRender();
  if (capture->GetState() != CAPTURESTATE_FAILED)
  {
    const CRect destRect(0, 0, static_cast<float>(capture->GetWidth()), static_cast<float>(capture->GetHeight()));

    m_renderer->Render(capture->GetTarget(), m_sourceRect, destRect, GetScreenRect());
    capture->EndRender();

    return true;
  }

  return false;
}

void CWinRenderer::SetBufferSize(int numBuffers)
{
  if (!m_bConfigured)
    return;

  m_renderer->SetBufferSize(numBuffers);
}

void CWinRenderer::PreInit()
{
  CSingleLock lock(CServiceBroker::GetWinSystem()->GetGfxContext());
  m_bConfigured = false;
  UnInit();
}

void CWinRenderer::UnInit()
{
  CSingleLock lock(CServiceBroker::GetWinSystem()->GetGfxContext());

  m_renderer.reset();
  m_bConfigured = false;
}

bool CWinRenderer::Flush(bool saveBuffers)
{
  if (!m_bConfigured)
    return false;

  return m_renderer->Flush(saveBuffers);
}

bool CWinRenderer::Supports(ERENDERFEATURE feature)
{
  if(feature == RENDERFEATURE_BRIGHTNESS)
    return true;

  if(feature == RENDERFEATURE_CONTRAST)
    return true;

  if (feature == RENDERFEATURE_STRETCH         ||
      feature == RENDERFEATURE_NONLINSTRETCH   ||
      feature == RENDERFEATURE_ZOOM            ||
      feature == RENDERFEATURE_VERTICAL_SHIFT  ||
      feature == RENDERFEATURE_PIXEL_RATIO     ||
      feature == RENDERFEATURE_ROTATION        ||
      feature == RENDERFEATURE_POSTPROCESS     ||
      feature == RENDERFEATURE_TONEMAP)
    return true;

  return false;
}

bool CWinRenderer::Supports(ESCALINGMETHOD method)
{
  if (!m_bConfigured)
    return false;

  return m_renderer->Supports(method);
}

bool CWinRenderer::WantsDoublePass()
{
  if (!m_bConfigured)
    return false;

  return m_renderer->WantsDoublePass();
}

bool CWinRenderer::ConfigChanged(const VideoPicture& picture)
{
  if (!m_bConfigured)
    return true;

  return picture.videoBuffer->GetFormat() != m_format;
}

CRenderInfo CWinRenderer::GetRenderInfo()
{
  if (!m_bConfigured)
    return {};

  return m_renderer->GetRenderInfo();
}

void CWinRenderer::ReleaseBuffer(int idx)
{
  if (!m_bConfigured)
    return;

  m_renderer->ReleaseBuffer(idx);
}

bool CWinRenderer::NeedBuffer(int idx)
{
  if (!m_bConfigured)
    return false;

  return m_renderer->NeedBuffer(idx);
}

´´´

Body:
Change

nvStatus = NvAPI_GPU_GetConnectedDisplayIds(ahGPU, displayIdArray, &displayIdCount, flags);

to

nvStatus = NvAPI_GPU_GetConnectedDisplayIds(ahGPU[i], displayIdArray, &displayIdCount, flags);

Thanks to @1201ProgramAlarm


来源: stackexchange

问:
UniSharp laravel-filemanager integration with TinyMCE 5
the documentation from Unisharp to integrate it with TinyMCE 4 :

```<code><script>
var editor_config = {
  /* replace textarea having class .tinymce with tinymce editor */
  selector: "textarea.tinymce",
  path_absolute : "/",
  relative_urls: false,
  height: 129,
  file_browser_callback : function(field_name, value, type, meta) {
    var x = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth;
    var y = window.innerHeight|| document.documentElement.clientHeight|| document.getElementsByTagName('body')[0].clientHeight;

    var cmsURL = editor_config.path_absolute + 'laravel-filemanager?field_name=' + field_name;
    if (type == 'image') {
        cmsURL = cmsURL + "&type=Images";
    } else {
        cmsURL = cmsURL + "&type=Files";
    }

    tinyMCE.activeEditor.windowManager.open({
      file : cmsURL,
      title : 'Gestionnaire de fichiers',
      width : x * 0.8,
      height : y * 0.8,
      resizable : "yes",
      close_previous : "no"
    });
  },

    /* theme of the editor
    theme: "modern",
    skin: "lightgray", */

    /* width and height of the editor */
    width: "100%",
    height: 500,

    /* display statusbar */
    statubar: true,

    /* plugin */
    plugins: [
        "advlist link image autolink autosave link image lists charmap print preview hr anchor pagebreak",
        "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
        "save table directionality emoticons template paste"
    ],

    /* toolbar */
    toolbar: " insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | ltr rtl | insertfile media image link | forecolor backcolor | code preview fullscreen",

    /* style */
    style_formats: [
        {title: "Headers", items: [
            {title: "Header 1", format: "h1"},
            {title: "Header 2", format: "h2"},
            {title: "Header 3", format: "h3"},
            {title: "Header 4", format: "h4"},
            {title: "Header 5", format: "h5"},
            {title: "Header 6", format: "h6"}
        ]},
        {title: "Inline", items: [
            {title: "Bold", icon: "bold", format: "bold"},
            {title: "Italic", icon: "italic", format: "italic"},
            {title: "Underline", icon: "underline", format: "underline"},
            {title: "Strikethrough", icon: "strikethrough", format: "strikethrough"},
            {title: "Superscript", icon: "superscript", format: "superscript"},
            {title: "Subscript", icon: "subscript", format: "subscript"},
            {title: "Code", icon: "code", format: "code"}
        ]},
        {title: "Blocks", items: [
            {title: "Paragraph", format: "p"},
            {title: "Blockquote", format: "blockquote"},
            {title: "Div", format: "div"},
            {title: "Pre", format: "pre"}
        ]},
        {title: "Alignment", items: [
            {title: "Left", icon: "alignleft", format: "alignleft"},
            {title: "Center", icon: "aligncenter", format: "aligncenter"},
            {title: "Right", icon: "alignright", format: "alignright"},
            {title: "Justify", icon: "alignjustify", format: "alignjustify"}
        ]}
    ]
};

tinymce.init(editor_config);

</script>
</code>```

the documentation on TinyMCE 5 says :

```<code><script>
tinymce.init({
  selector: 'textarea',  // change this value according to your HTML
  file_picker_callback: function(callback, value, meta) {
    // Provide file and text for the link dialog
    if (meta.filetype == 'file') {
      callback('mypage.html', {text: 'My text'});
    }

    // Provide image and alt text for the image dialog
    if (meta.filetype == 'image') {
      callback('myimage.jpg', {alt: 'My alt text'});
    }

    // Provide alternative source and posted for the media dialog
    if (meta.filetype == 'media') {
      callback('movie.mp4', {source2: 'alt.ogg', poster: 'image.jpg'});
    }
  }
});
</script>
</code>```

so my question is there any possible way to make UniSharp laravel file manager working with TinyMCE 5 or tinyMCE.activeEditor.windowManager.open({file : cmsURL});}, is no longer supported ?

答:
Upgrade Tinymce to 5.0.6+

Execute the following command if you have not previously executed:

php artisan vendor:publish --tag=lfm_view

In the "resources/views/vendor/laravel-filemanager/index.php" replace
the

{!! \File::get(base_path('vendor/unisharp/laravel-filemanager/public/js/script.js')) !!}

with

{!! \File::get(resource_path('assets/vendor/laravel-filemanager/script.js')) !!}

Copy the "vendor/unisharp/laravel-filemanager/public/js/script.js" to
"resources/assets/vendor/laravel-filemanager/script.js".

Open the "resources/assets/vendor/laravel-filemanager/script.js" and
after function "useTinymce3" insert the follow code:

function useTinymce5(url) {
parent.postMessage({
  mceAction: 'insert',
  content: url
});
parent.postMessage({ mceAction: 'close' });
}
Then replace:
if (window.opener || window.tinyMCEPopup || field_name || getUrlParam('CKEditorCleanUpFuncNum') || is_ckeditor)

with

if ('tinymce5' === getUrlParam('editor')) {
  useTinymce5(url);
} else if (window.opener || window.tinyMCEPopup || field_name || getUrlParam('CKEditorCleanUpFuncNum') || is_ckeditor)

Config the Tinymce
(https://unisharp.github.io/laravel-filemanager/integration):

var editor_config = {
    // ...
    file_picker_callback: function (callback, value, meta) {
        let x = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth;
        let y = window.innerHeight|| document.documentElement.clientHeight|| document.getElementsByTagName('body')[0].clientHeight;

```<code>    let type = 'image' === meta.filetype ? 'Images' : 'Files',
        url  = editor_config.path_absolute + 'laravel-filemanager?editor=tinymce5&type=' + type;

    tinymce.activeEditor.windowManager.openUrl({
        url : url,
        title : 'Filemanager',
        width : x * 0.8,
        height : y * 0.8,
        onMessage: (api, message) => {
            callback(message.content);
        }
    });
}
</code>```

};

Download TinyMCE Community from here
here

ContentLicense: CC BY-SA 4.0

Body:
the documentation from Unisharp to integrate it with TinyMCE 4 :

the documentation on TinyMCE 5 says :

so my question is there any possible way to make UniSharp laravel file manager working with TinyMCE 5 or tinyMCE.activeEditor.windowManager.open({file : cmsURL});}, is no longer supported ?

Body:
Upgrade Tinymce to 5.0.6+

Execute the following command if you have not previously executed:

php artisan vendor:publish --tag=lfm_view

In the "resources/views/vendor/laravel-filemanager/index.php" replace
the

{!! \File::get(base_path('vendor/unisharp/laravel-filemanager/public/js/script.js')) !!}

with

{!! \File::get(resource_path('assets/vendor/laravel-filemanager/script.js')) !!}

Copy the "vendor/unisharp/laravel-filemanager/public/js/script.js" to
"resources/assets/vendor/laravel-filemanager/script.js".

Open the "resources/assets/vendor/laravel-filemanager/script.js" and
after function "useTinymce3" insert the follow code:

function useTinymce5(url) {
parent.postMessage({
  mceAction: 'insert',
  content: url
});
parent.postMessage({ mceAction: 'close' });
}
Then replace:
if (window.opener || window.tinyMCEPopup || field_name || getUrlParam('CKEditorCleanUpFuncNum') || is_ckeditor)

with

if ('tinymce5' === getUrlParam('editor')) {
  useTinymce5(url);
} else if (window.opener || window.tinyMCEPopup || field_name || getUrlParam('CKEditorCleanUpFuncNum') || is_ckeditor)

Config the Tinymce
(https://unisharp.github.io/laravel-filemanager/integration):

var editor_config = {
    // ...
    file_picker_callback: function (callback, value, meta) {
        let x = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth;
        let y = window.innerHeight|| document.documentElement.clientHeight|| document.getElementsByTagName('body')[0].clientHeight;

    let type = 'image' === meta.filetype ? 'Images' : 'Files',
        url  = editor_config.path_absolute + 'laravel-filemanager?editor=tinymce5&type=' + type;

    tinymce.activeEditor.windowManager.openUrl({
        url : url,
        title : 'Filemanager',
        width : x * 0.8,
        height : y * 0.8,
        onMessage: (api, message) => {
            callback(message.content);
        }
    });
}

};

Download TinyMCE Community from here
here


问:
Fancybox avoid caching of ajax requests
I'm currently facing an annoying (suspected) cache issue with fancybox 3.4.1:

```<code><a data-fancybox="" data-type="ajax" data-src="src/views/forms/SpeiseplanCreateForm.php?ValidFrom=1560117600" href="javascript:;" id="fancybox-SpeiseplanCreateForm"><button id="fancybox-SpeiseplanCreateForm-button">Speiseplan bearbeiten</button></a>
</code>```

has a GET parameter which is then evaluated by my PHP script, however, when I click on it for the first time, it works fine, but when I change the value of ValidFrom via JavaScript and try to open the box a second time, the get parameter is still the same as in the first call. I assume it's related to fancybox caching the requests.

I have verified that the URL parameter is getting changed properly and I also tried disabling the cache by adding this to my header:

```<code>     <script>
        $(document).ready(function() {
         $(".data-fancybox").fancybox({
         type       : 'ajax',
         ajax       : { cache: false }
          });
        });
    </script>
</code>```

as suggested here: https://stackoverflow.com/a/17621281/4934937

Is there a way to disable the cache?

答:
I just found a very dirty workaround for this. After editing the element in Firefox (Edit HTML), it worked. So I guessed it must have something in common with some weird caching (browser or fancybox, who knows).

The workaround is to create a new a element, remove the old a and append it to the old a's parent again.

```<code>let newElement = document.createElement("a");
newElement.setAttribute("id","fancybox-"+id)
newElement.setAttribute("data-fancybox","");
newElement.setAttribute("data-type","ajax");
newElement.setAttribute("href","javascript:;");
newElement.setAttribute("data-src",fancyboxSrc);
newElement.appendChild(button);

fancybox.outerHTML = "";
parent.appendChild(newElement);
</code>```

Title: Fancybox avoid caching of ajax requests

Body:
I'm currently facing an annoying (suspected) cache issue with fancybox 3.4.1:

<button id="fancybox-SpeiseplanCreateForm-button">Speiseplan bearbeiten</button>

has a GET parameter which is then evaluated by my PHP script, however, when I click on it for the first time, it works fine, but when I change the value of ValidFrom via JavaScript and try to open the box a second time, the get parameter is still the same as in the first call. I assume it's related to fancybox caching the requests.

I have verified that the URL parameter is getting changed properly and I also tried disabling the cache by adding this to my header:

as suggested here: https://stackoverflow.com/a/17621281/4934937

Is there a way to disable the cache?

Body:
I just found a very dirty workaround for this. After editing the element in Firefox (Edit HTML), it worked. So I guessed it must have something in common with some weird caching (browser or fancybox, who knows).

The workaround is to create a new a element, remove the old a and append it to the old a's parent again.

let newElement = document.createElement("a");
newElement.setAttribute("id","fancybox-"+id)
newElement.setAttribute("data-fancybox","");
newElement.setAttribute("data-type","ajax");
newElement.setAttribute("href","javascript:;");
newElement.setAttribute("data-src",fancyboxSrc);
newElement.appendChild(button);

fancybox.outerHTML = "";
parent.appendChild(newElement);


问:
Check if event target is hyperlink
I have a large div inside there which are smaller divs, achor tags and other elements.
Each large div in my program is bound to "mousedown" event and inside the onMouseDown handler, I basically check the event.target.

If a user clicks on an items that is a hyper link, I want to check if event.target was hyperlink and then navigate to that link if event.target was a hyperlink. How can that be done?

Here's the structure of the divsa and elements.

```<code><div class="camp-name">
    <span class="btnCampaign"><div class=""></div></span>
    <span class="campaign-name">
       <a href="http://www.google.com">Some Link here</a>
    </span>
</div>
<div class="campaign-name-sub">
   <span class="campaign-accountname">Some Text here</span>
   <span class="seprator">|</span>
   <span class="brandname">Some Text here</span>
</div>
</code>```

JS

```<code>var label = label.createElement("DIV");
label.innerHMTL = src //src is the above html that is seen here
    Plugin.addEventListener(label, "mousedown", params.onMouseDown);

Plugin.onMouseDown() = function(event) {
var target = (event.currentTarget) ? event.currentTarget : event.srcElement;
        if (target.tagName.toLowerCase() === "a" && target !== undefined) {
            console.log(target.href);
            Plugin.stopPropagation(event);
        }
};
</code>```

答:
You could check the tagName property, as said by @parthik-gosar.
Another way is to use the instanceof operator to check the element class (hyperlinks are of type HTMLAnchorElement):

```<code>if (event.target instanceof HTMLAnchorElement) {
  console.log(event.target.href);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Check if event target is hyperlink

Body:
I have a large div inside there which are smaller divs, achor tags and other elements.
Each large div in my program is bound to "mousedown" event and inside the onMouseDown handler, I basically check the event.target.

If a user clicks on an items that is a hyper link, I want to check if event.target was hyperlink and then navigate to that link if event.target was a hyperlink. How can that be done?

Here's the structure of the divsa and elements.

       Some Link here

   Some Text here
   |
   Some Text here

JS

var label = label.createElement("DIV");
label.innerHMTL = src //src is the above html that is seen here
    Plugin.addEventListener(label, "mousedown", params.onMouseDown);

Plugin.onMouseDown() = function(event) {
var target = (event.currentTarget) ? event.currentTarget : event.srcElement;
        if (target.tagName.toLowerCase() === "a" && target !== undefined) {
            console.log(target.href);
            Plugin.stopPropagation(event);
        }
};

Body:
You could check the tagName property, as said by @parthik-gosar.
Another way is to use the instanceof operator to check the element class (hyperlinks are of type HTMLAnchorElement):

if (event.target instanceof HTMLAnchorElement) {
  console.log(event.target.href);
}


问:
How to update a Milestone's description with GitHubs's GraphQL API v4?
I'm trying to update a milestone's description through the GraphQL API.

While updating a milestone was possible through the v3 REST API by:

PATCH /repos/:owner/:repo/milestones/:number

I'm unable to find a mutation for this purpose on the v4 docs here: https://developer.github.com/v4/mutation/

Is this feature not available in the v4 api?

答:
```<code>curl -i -H "Authorization: token >>Insert your token<<"
     --data "{ \"title\": \"Milestone name\", \"state\": \"open\", \"description\": \"Write the new description\"}"
     -X PATCH  https://api.github.com/repos/>>Github account name or group name<</>>name of project<</milestones/>>Id of the milestone<<
</code>```

In the >> << you need to insert your information

How to do a token https://microclimate.dev/creatingpat

Normaly Id is 1 ... not a high number

this works on Windows cmd

Body:
curl -i -H "Authorization: token >>Insert your token<<"
     --data "{ \"title\": \"Milestone name\", \"state\": \"open\", \"description\": \"Write the new description\"}"
     -X PATCH  https://api.github.com/repos/>>Github account name or group name<</>>name of project<</milestones/>>Id of the milestone<<

In the >> << you need to insert your information

How to do a token https://microclimate.dev/creatingpat

Normaly Id is 1 ... not a high number

this works on Windows cmd


问:
How can I get all possible combinations of element in set? (power set)
I have a array of number:

```<code>$numbers = array(1,2,3);
</code>```

The order does not mean anything.  If the numbers given were 1, 2 and 3, then I would want to receive this as a result:

```<code>1
2
3
1 2
1 3
2 3
1 2 3
</code>```

How can I achieve that?

答:
You can use the following recursion function:

```<code>function powerSet($arr) {
    if (!$arr) return array([]);
    $firstElement = array_shift($arr);
    $recursionCombination = powerSet($arr);
    $currentResult = [];
    foreach($recursionCombination as $comb) {
        $currentResult[] = array_merge($comb, [$firstElement]);
    }
    return array_merge($currentResult, $recursionCombination );
}
</code>```

Now  print_r(powerSet([1,2,3])); will give you all those option as arrays.

Edited with adding option of empty array as powerSet

Body:
I have a array of number:

$numbers = array(1,2,3);

The order does not mean anything.  If the numbers given were 1, 2 and 3, then I would want to receive this as a result:

1
2
3
1 2
1 3
2 3
1 2 3

How can I achieve that?

Body:
You can use the following recursion function:

function powerSet($arr) {
    if (!$arr) return array([]);
    $firstElement = array_shift($arr);
    $recursionCombination = powerSet($arr);
    $currentResult = [];
    foreach($recursionCombination as $comb) {
        $currentResult[] = array_merge($comb, [$firstElement]);
    }
    return array_merge($currentResult, $recursionCombination );
}

Now  print_r(powerSet([1,2,3])); will give you all those option as arrays.

Edited with adding option of empty array as powerSet


问:
Angular Material Dialog - content projection
Is it possible to use dynamic content inside an angular material dialog?

```<code>let dialogRef = dialog.open(YourDialog, {
  data: { name: 'austin' },
});
</code>```

Instead of { name: 'austin' }, I would like to use a dynamic template which includes html tags.

```<code>@Component({
  selector: 'your-dialog',
  template: 'passed in {{ data.name }}',
  // template: '{{ data.template }}'
})
export class YourDialog {
  constructor(@Inject(MAT_DIALOG_DATA) public data: any) { }
}
</code>```

答:
Yes just instead of use {{ }} use something like this

```<code>[innerHTML]="data.template"
</code>```

in a div for example

Body:
Is it possible to use dynamic content inside an angular material dialog?

let dialogRef = dialog.open(YourDialog, {
  data: { name: 'austin' },
});

Instead of { name: 'austin' }, I would like to use a dynamic template which includes html tags.

@Component({
  selector: 'your-dialog',
  template: 'passed in {{ data.name }}',
  // template: '{{ data.template }}'
})
export class YourDialog {
  constructor(@Inject(MAT_DIALOG_DATA) public data: any) { }
}

Body:
Yes just instead of use {{ }} use something like this

[innerHTML]="data.template"

in a div for example


问:
How to fix facebook sharer button that appears cutted on wordpress
I want to put a facebook sharer button in my articles. I'm using incubator wordpress theme.
I got the code on fb developers site and it works very well, but it appears cutted (doesn't show how many times the article was shared).

I went to facebook developers page (https://developers.facebook.com/docs/plugins/share-button/) , created the code below, and put it in a html type of content, in wordpress. I changed the 75 width in the code, and it didn't work.

```

It was no errors, only appears cutted on the right side. Do you know what can I do for it to totally appear?

Thank you all for your possible help. :)

答:
Try the below code, make width="100" of iframe

```<code><iframe src="https://www.facebook.com/plugins/share_button.php?href=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2Fplugins%2F&layout=button_count&size=small&width=88&height=20&appId" width="100" height="20" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true" allow="encrypted-media"></iframe>
</code>```

Body:
I want to put a facebook sharer button in my articles. I'm using incubator wordpress theme.
I got the code on fb developers site and it works very well, but it appears cutted (doesn't show how many times the article was shared).

I went to facebook developers page (https://developers.facebook.com/docs/plugins/share-button/) , created the code below, and put it in a html type of content, in wordpress. I changed the 75 width in the code, and it didn't work.

It was no errors, only appears cutted on the right side. Do you know what can I do for it to totally appear?

Thank you all for your possible help. :)

Body:
Try the below code, make width="100" of iframe

<iframe src="https://www.facebook.com/plugins/share_button.php?href=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2Fplugins%2F&layout=button_count&size=small&width=88&height=20&appId" width="100" height="20" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true" allow="encrypted-media"></iframe>


问:
Wagtail "schedule_published_pages" Management Command
I was wondering why my scheduled posts were not working automatically in Wagtail, but I see in the documentation that a management command is needed to make this happen. I am unfamiliar with writing custom management commands, and I am wondering how to make the python manage.py publish_scheduled_pages command fire off automatically every hour?

Where would this code go in the document tree? Is there code that I just need to drop in and it runs from there? Or is something required on the server to run these commands on a schedule?

Any help would be appreciated. I couldn't find any existing code anywhere for this functionality in Wagtail and I'm wondering why the button is in the admin to schedule a post, but the functionality is not already built in?

答:
You are probably familiar with management commands since python manage.py runserver and makemigrations and migrate are management commands.

You can see all available commands with python manage.py -h

publish_scheduled_pages should be called periodically. Form the Wagtail docs:

This command publishes, updates or unpublishes pages that have had these actions scheduled by an editor. We recommend running this command once an hour.

Periodically executing a command can be done in various ways. Via crontab is probably the most common. To edit the crontab:

```<code>$ crontab -e
</code>```

Add (for every fist minute of the hour):

```<code>0 * * * * python /path/to/your/manage.py publish_scheduled_pages --settings=your.settings
</code>```

Body:
You are probably familiar with management commands since python manage.py runserver and makemigrations and migrate are management commands.

You can see all available commands with python manage.py -h

publish_scheduled_pages should be called periodically. Form the Wagtail docs:

This command publishes, updates or unpublishes pages that have had these actions scheduled by an editor. We recommend running this command once an hour.

Periodically executing a command can be done in various ways. Via crontab is probably the most common. To edit the crontab:

$ crontab -e

Add (for every fist minute of the hour):

0 * * * * python /path/to/your/manage.py publish_scheduled_pages --settings=your.settings


问:
Angular CLI and auto-refresh
I work with the Angular CLI and when I run "ng serve" the project is supposed to refresh automatically. However, sometimes, it's not perfect. Sometimes, changes are not refreshed automatically and sometimes it does. When changes are not refreshed, I have to re-run 'ng serve' which wastes a lot of time.

Do you have any way to know in what cases changes are refreshed automatically and when they are not? Also, if I see that I have to re-run 'ng serve', is there any faster way to refresh the project?

答:
This helps me </p>

```<code>echo 65536 | sudo tee -a /proc/sys/fs/inotify/max_user_watches
</code>```

Title: Angular CLI and auto-refresh

Body:
This helps me

echo 65536 | sudo tee -a /proc/sys/fs/inotify/max_user_watches


问:
model returning null array
i have a model named Student_model and fetchDataPro function inside the model

```<code>class Student_model extends CI_Model
{
    public function fetchDataPro($from,$to)
    {
            $query=$this->db->select(['signuppro.id','fname','lname','cname','profile_pic'])
            ->from('signuppro')
            ->join('course','cid=course.id')
            ->limit($from,$to)
            ->get();
            $result=$query->result();
            print_r($result);exit;
    }
}
</code>```

It's printing a null array. I think i had writter wrong something related limit because if i remove the limit it's returning me proper data

答:
Say something more like this

```<code>      <?php
class Student_model extends CI_Model
    {
        public function fetchDataPro($from,$to)
        {
                $query=$this->db->select(signuppro.id,fname,lname,cname,profile_pic')
                ->from('signuppro')
                ->join('course cid','cid.id  = signuppro.id_course','inner')
                ->limit($from,$to)
                ->get();
                $result= $query->result();
                return $result;
        }
    }
</code>```

Check your join it has an error on the fields to attach

a+

Title: model returning null array

Body:
i have a model named Student_model and fetchDataPro function inside the model

class Student_model extends CI_Model
{
    public function fetchDataPro($from,$to)
    {
            $query=$this->db->select(['signuppro.id','fname','lname','cname','profile_pic'])
            ->from('signuppro')
            ->join('course','cid=course.id')
            ->limit($from,$to)
            ->get();
            $result=$query->result();
            print_r($result);exit;
    }
}

It's printing a null array. I think i had writter wrong something related limit because if i remove the limit it's returning me proper data

Body:
Say something more like this

      <?php
class Student_model extends CI_Model
    {
        public function fetchDataPro($from,$to)
        {
                $query=$this->db->select(signuppro.id,fname,lname,cname,profile_pic')
                ->from('signuppro')
                ->join('course cid','cid.id  = signuppro.id_course','inner')
                ->limit($from,$to)
                ->get();
                $result= $query->result();
                return $result;
        }
    }

Check your join it has an error on the fields to attach

a+


问:
Android/IOS Mobile application test automation : need recommendation on which framework to use?
Appium with webdriver-io (javascript) or Appium with java, selenium is better for Mobile application testing?

I am testing a mobile application which runs in both Android and IOS. Need to use the browserstack service to run the test suit in different devices. At present unable to decide which framework should be used. Using webdriver-io will be convenient of not?

答:
If you have good understanding of JAVAScript then you can use Appium with webdriver-io.

2.If you have good understanding of JAVA then you can use Appium with JAVA and use page object with Page factory framework.

I do not suggest selenium for mobile automation testing. You can use appium for mobile automation as it has better method to deal with Native and WebView/Hybrid/Web apps/Angular based apps.

If you plan to use JAVA you can create single framework for iOS and Android using Page Factory annotations provided by Appium.


问:
Getting error in convert a string of a hex to a byte array in Java
I am looking for a way to convert string that represents hex values into a byte array. This code is perfect working for even number string length but not for odd number string length. If string length is odd then I get java.lang.StringIndexOutOfBoundsException. Please help. </p>

```<code>public byte[] hexStringToByteArray(String s) {
     byte[] data = null;
         if(! s.equals("")){
            int len = s.length();
            data = new byte[len / 2];
            for (int i = 0; i < len; i += 2) {
                data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                                     + Character.digit(s.charAt(i+1), 16));
            }
         }
     return data;
}
</code>```

答:
data in case of odd number becomes of less size.

Suppose string length is 7 then data array would be of size 3,

7/2 = 3 (takes integer value)

Later in the loop you are trying to access data for 0 to 3 (which are 4 size).

Also you are accessing element in s.charAt(i+1) which is resulting larger index as your loop starts with 0 to 7. Value of i changes as :

0
2
4
6

when it is 6 then s.charAt(7) will throw StringIndexOutOfBoundsException. As string is of length 7 (index 0 to 6). 7th index is not present for string.

Solution is to reduce the no. of times loop is running by changing loop condition.

Body:
I am looking for a way to convert string that represents hex values into a byte array. This code is perfect working for even number string length but not for odd number string length. If string length is odd then I get java.lang.StringIndexOutOfBoundsException. Please help.

public byte[] hexStringToByteArray(String s) {
     byte[] data = null;
         if(! s.equals("")){
            int len = s.length();
            data = new byte[len / 2];
            for (int i = 0; i < len; i += 2) {
                data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                                     + Character.digit(s.charAt(i+1), 16));
            }
         }
     return data;
}


问:
Send model value to observer.next();
I have a function like below. I am trying to figure out how to send userDetails to the observer.next()

```<code>  getUserDetails(userId: string): Observable<GetUserByIdModel> {
    const url = `${this.candidateUrl}/Get`;
    this._http.get<any>(url + '/' + userId).subscribe((resp) => {
      const userDetails: GetUserByIdModel = {
        firstname: 'Joyce',
        contactChannels: [
          { type: 1, value: 'test@gmail.com' },
          { type: 2, value: '0111111111' }
        ],
      };
    })

    return new Observable((observer) => {
      observer.next(userDetails);
      observer.complete();
    });

  }
</code>```

Currently I get "Cannot find name 'userDetails'" even if I change  const userDetails: GetUserByIdModel to a let/var userDetails: GetUserByIdModel

答:
First of all you want to return user when you get response from subscriber ? If answer is yes you can add returning inside subscribe or you want to return a new Observable because you have someone subscribed to this Observable you should do something like this:

First of all declare a variable

```<code>userDetails: GetUserByIdModel = {};
</code>```

Inside your subscriber use this variable

```<code>getUserDetails(userId: string): Observable<GetUserByIdModel> {
    const url = `${this.candidateUrl}/Get`;
    this._http.get<any>(url + '/' + userId).subscribe((resp) => {
      this.userDetails = {
        firstname: 'Joyce',
        contactChannels: [
          { type: 1, value: 'test@gmail.com' },
          { type: 2, value: '0111111111' }
        ],
      };
    })

    return new Observable((observer) => {
      observer.next(this.userDetails);
      observer.complete();
    });

  }

</code>```

But it doesn't make sense to return a new variable inside subscriber, it make sense to return the response what you get from subscriber, something like this:

```<code>observer: Subject<any>  = new BehaviorSubject<any>;

getUserDetails(userId: string): Observable<GetUserByIdModel> {
    const url = `${this.candidateUrl}/Get`;
    this._http.get<any>(url + '/' + userId).subscribe((resp) => {

    // Now you emitting new data as soon as possible you get data
    this.observer.next(resp);
    })

  }
</code>```

and in other place you'll have something like this

```<code>observer.subscriber(data => {
  // and here you'll have data from that observer
  console.log(data)
})
</code>```

Please be more clear next time, and if you have any question feel free to ask.

Title: Send model value to observer.next();

Body:
I have a function like below. I am trying to figure out how to send userDetails to the observer.next()

  getUserDetails(userId: string): Observable<GetUserByIdModel> {
    const url = `${this.candidateUrl}/Get`;
    this._http.get<any>(url + '/' + userId).subscribe((resp) => {
      const userDetails: GetUserByIdModel = {
        firstname: 'Joyce',
        contactChannels: [
          { type: 1, value: 'test@gmail.com' },
          { type: 2, value: '0111111111' }
        ],
      };
    })

    return new Observable((observer) => {
      observer.next(userDetails);
      observer.complete();
    });

  }

Currently I get "Cannot find name 'userDetails'" even if I change  const userDetails: GetUserByIdModel to a let/var userDetails: GetUserByIdModel

Body:
First of all you want to return user when you get response from subscriber ? If answer is yes you can add returning inside subscribe or you want to return a new Observable because you have someone subscribed to this Observable you should do something like this:

First of all declare a variable

userDetails: GetUserByIdModel = {};

Inside your subscriber use this variable

getUserDetails(userId: string): Observable<GetUserByIdModel> {
    const url = `${this.candidateUrl}/Get`;
    this._http.get<any>(url + '/' + userId).subscribe((resp) => {
      this.userDetails = {
        firstname: 'Joyce',
        contactChannels: [
          { type: 1, value: 'test@gmail.com' },
          { type: 2, value: '0111111111' }
        ],
      };
    })

    return new Observable((observer) => {
      observer.next(this.userDetails);
      observer.complete();
    });

  }

But it doesn't make sense to return a new variable inside subscriber, it make sense to return the response what you get from subscriber, something like this:

observer: Subject<any>  = new BehaviorSubject<any>;

getUserDetails(userId: string): Observable<GetUserByIdModel> {
    const url = `${this.candidateUrl}/Get`;
    this._http.get<any>(url + '/' + userId).subscribe((resp) => {

    // Now you emitting new data as soon as possible you get data
    this.observer.next(resp);
    })

  }

and in other place you'll have something like this

observer.subscriber(data => {
  // and here you'll have data from that observer
  console.log(data)
})

Please be more clear next time, and if you have any question feel free to ask.


问:
In a layered architecture using Entity Framework, should I return POCO classes from the BLL? (Architecture guidance needed)
I've been reading too much probably and am suffering from some information overload. So I would appreciate some explicit guidance.

From what I've gathered, I can use VS2010's T4 template thingy to generate POCO classes that aren't tied directly to the EF. I would place these in their own project while my DAL would have an ObjectContext-derived class, right?

Once I have these classes, is it acceptable practice to use them in the UI layer? That is, say one of the generated classes is BookInfo that holds stuff about books for a public library (Title, edition, pages, summary etc.).

My BLL would contain a class BooksBLL for example like so:

```<code>public class BooksBLL
{
    ObjectContext _context;

    public void AddBook(BookInfo book) { ... }
    public void DeleteBook(int bookID) { ... }
    public void UpdateBook(int bookID, BookInfo newBook) { ... }

    //Advanced search taking possibly all fields into consideration
    public List<BookInfo> ResolveSearch(Func<BookInfo, bool> filter) { ... }

    //etc...
}
</code>```

So, my ViewModels in my MVVM UI app will be communicating with the above BLL class and exchanging BookInfo instances. Is that okay?

Furthermore, MVVM posts on the Web suggest implementing IDataErrorInfo for validation purposes. Is it okay if I implement said interface on the generated POCO class? I see from samples that those generated POCO classes contain all virtual properties and stuf and I hope adding my own logic would be okay?

If it makes any difference, at present, my app does not use WCF (or any networking stuff).

Also, if you see something terribly wrong with the way I'm trying to build my BLL, please feel free to offer help in that area too.

Update (Additional info as requested):

I'm trying to create a library automation application. It is not network based at present.

I am thinking about having layers as follows:

A project consisting of generated POCO classes (BookInfo, Author, Member, Publisher,  Contact etc.)

A project with the ObjectContext-derived class (DAL?)

A Business Logic Layer with classes like the one I mentioned above (BooksBLL, AuthorsBLL etc)

A WPF UI layer using the MVVM pattern. (Hence my sub-question about IDataErrorInfo implementation).

So I'm wondering about stuff like using an instance of BooksBLL in a ViewModel class, calling ResolveSearch() on it to obtain a List<BookInfo> and presenting it... that is, using the POCO classes everywhere.

Or should I have additional classes that mirror the POCO classes exposed from my BLL?

If any more detail is needed, please ask.

答:
What you're doing is basically the Repository pattern, for which Entity Framework and POCO are a great fit.

So, my ViewModels in my MVVM UI app will be communicating with the above BLL class and exchanging BookInfo instances. Is that okay?

That's exactly what POCO objects are for; there's no difference between the classes that are generated and how you would write them by hand. It's your ObjectContext that encapsulates all the logic around persisting any changes back to the database, and that's not directly exposed to your UI.

I'm not personally familiar with IDataErrorInfo but if right now your entities will only be used in this single app, I don't see any reason not to put it directly in the generated classes. Adding it to the T4 template would be ideal if that's possible, it would save you having to code it by hand for every class if the error messages follow any logical pattern.

Also, if you see something terribly wrong with the way I'm trying to build my BLL, please feel free to offer help in that area too.

This isn't terribly wrong by any means, but if you plan to write unit tests against your BLL (which I would recommend), you will want to change your ObjectContext member to IObjectContext. That way you can substitute any class implementing the IObjectContext interface at runtime (such as your actual ObjectContext), which will allow you to do testing against an in-memory (i.e. mocked) context and not have to hit the database.

Similarly, think about replacing your List<BookInfo> with an interface of some kind such as IList<BookInfo> or IBindingList<BookInfo> or the lowest common denominator IEnumerable<BookInfo>. That way you're not tied directly to the specific class List<T> and if your needs change over time, which tends to happen, it will reduce the refactoring necessary to replace your List<BookInfo> with something else, assuming whatever you're replacing it with implements the interface you've chosen.

Body:
I've been reading too much probably and am suffering from some information overload. So I would appreciate some explicit guidance.

From what I've gathered, I can use VS2010's T4 template thingy to generate POCO classes that aren't tied directly to the EF. I would place these in their own project while my DAL would have an ObjectContext-derived class, right?

Once I have these classes, is it acceptable practice to use them in the UI layer? That is, say one of the generated classes is BookInfo that holds stuff about books for a public library (Title, edition, pages, summary etc.).

My BLL would contain a class BooksBLL for example like so:

public class BooksBLL
{
    ObjectContext _context;

    public void AddBook(BookInfo book) { ... }
    public void DeleteBook(int bookID) { ... }
    public void UpdateBook(int bookID, BookInfo newBook) { ... }

    //Advanced search taking possibly all fields into consideration
    public List<BookInfo> ResolveSearch(Func<BookInfo, bool> filter) { ... }

    //etc...
}

So, my ViewModels in my MVVM UI app will be communicating with the above BLL class and exchanging BookInfo instances. Is that okay?

Furthermore, MVVM posts on the Web suggest implementing IDataErrorInfo for validation purposes. Is it okay if I implement said interface on the generated POCO class? I see from samples that those generated POCO classes contain all virtual properties and stuf and I hope adding my own logic would be okay?

If it makes any difference, at present, my app does not use WCF (or any networking stuff).

Also, if you see something terribly wrong with the way I'm trying to build my BLL, please feel free to offer help in that area too.

Update (Additional info as requested):

I'm trying to create a library automation application. It is not network based at present.

I am thinking about having layers as follows:

A project consisting of generated POCO classes (BookInfo, Author, Member, Publisher,  Contact etc.)

A project with the ObjectContext-derived class (DAL?)

A Business Logic Layer with classes like the one I mentioned above (BooksBLL, AuthorsBLL etc)

A WPF UI layer using the MVVM pattern. (Hence my sub-question about IDataErrorInfo implementation).

So I'm wondering about stuff like using an instance of BooksBLL in a ViewModel class, calling ResolveSearch() on it to obtain a List<BookInfo> and presenting it... that is, using the POCO classes everywhere.

Or should I have additional classes that mirror the POCO classes exposed from my BLL?

If any more detail is needed, please ask.


问:
OCaml-ssl with Unix.select leads to read errors
I’m using SSL for reading data from various remote services over secure websockets as follows: I create the socket, embed it in the SSL context and add the socket to the reading list for Unix.select. When the socket fires, I use Ssl.read to get the data.

4 services are working well. And with one I get Ssl.Read_error.Error_syscall: error:00000000:lib(0):func(0):reason(0) after receiving each websocket frame (size ~5-6Kb). By the way, frames here are much bigger than on other services, but I’m not sure it’s the reason.

I ignore syscall errors (and most probably loose some data) because frames continue to arrive. Then, always after one minute I get Ssl.Read_error.Error_zero_return: error:00000000:lib(0):func(0):reason(0), which means the peer closed SSL socket for writing and I have to restart the process because no new data will be received from this socket.

Problem is perfectly reproducible. At the same time examples for this service and my own test implementation with Node.JS receive the data for hours without any problems.

I assume I do something wrong or setup socket/SSL too straightforward (see below).

Any help or ideas would be strongly appreciated.

let sock = Unix.socket PF_INET SOCK_STREAM 0 in
let laddr = Unix.inet_addr_of_string p.interface in
Unix.bind sock (ADDR_INET (laddr,0));
Unix.connect sock addr;
let (sock, res) =
let req = Bytes.of_string http_request in
if ssl then begin
  Ssl.init ();
  let ctx = create_context TLSv1_2 Client_context in
  let sock = Ssl.embed_socket sock ctx in
  Ssl.connect sock;
  (SslSock sock, (write sock req 0 http_request_len))
end else
  (UnixSock sock, (Unix.write sock req 0 http_request_len))
```

答: WireShark did the trick: this “bad” service sends two websocket frames in one tcp packet where second frame has zero payload length. Naturally, my Websocket implementation improperly handled frames with zero payload which lead to missing of Ping frames and closing of TCP connection by remote server.</p>


问:
Iteration of Google Maps API Search - First does the search 'i' times, then call back 'i' times
I am trying to take an array of coordinates, do a Nearby Search (https://developers.google.com/maps/documentation/javascript/places) for each item in the array, and then add each set of results to a separate array of results (placesOfInterest).

Instead of doing:
Search -> Put results to array -> Search -> Push results to array, it seems to be doing Search -> Search -> Search -> Push results to array -> Push results to array but I can't figure out why.

I was originally trying to push the search results to the placesOfInterest array, but then changed to an async version because I thought the callback wasn't getting hit due to some time delay. I created superPush function, based on the 'appendOutput(item) I found on this guide https://codeburst.io/asynchronous-code-inside-an-array-loop-c5d704006c99 but this still didn't fix the problem.

HTML

```<code>...
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<APIKEY>k&libraries=places"></script>
...
</code>```

JS

```<code>var points = [[2.627365,49.215369],[2.760591, 49.647163],[2.952975, 50.057504],[3.344742, 50.280862],[3.768293, 50.451306],[4.21659, 50.534029]]

   for (point of points) {
      googlePlaces(point);
    }

function googlePlaces(point) {
  var latLng = new google.maps.LatLng(point[1],point[0])
  var request = {
    location: latLng,
    radius: '10000'
  };

  service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request, callback);  // hits this code [i] times first...
}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {

//results.forEach(result => placesOfInterest.push(result)) // originally tried this way

    results.forEach(result => superPush(result)) // ...then hits this code [i] times

   }
}

function superPush(result) {

  fetchData(result).then(function() {
    placesOfInterest.push(result);
  })
}

</code>```

What can I do? There's no way to not call the callback, but I can't think of a way to get around it.

答:
One option is to use function closure to give access to the index of the array that the results need to be saved at:

```<code>function googlePlaces(point, index) { // function closure on index
  var latLng = new google.maps.LatLng(point[1], point[0])
  var request = {
    location: latLng,
    radius: '10000'
  };

  service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request, function(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      resultsArray[index] = results;
    }
  })
}
</code>```

calling it like this:

```<code>var i = 0;
for (point of points) {
  googlePlaces(point, i);
  i++;
}
</code>```

proof of concept fiddle

code snippet:

// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// ```

Body:
I am trying to take an array of coordinates, do a Nearby Search (https://developers.google.com/maps/documentation/javascript/places) for each item in the array, and then add each set of results to a separate array of results (placesOfInterest).

Instead of doing:
Search -> Put results to array -> Search -> Push results to array, it seems to be doing Search -> Search -> Search -> Push results to array -> Push results to array but I can't figure out why.

I was originally trying to push the search results to the placesOfInterest array, but then changed to an async version because I thought the callback wasn't getting hit due to some time delay. I created superPush function, based on the 'appendOutput(item) I found on this guide https://codeburst.io/asynchronous-code-inside-an-array-loop-c5d704006c99 but this still didn't fix the problem.

HTML

...

...

JS

var points = [[2.627365,49.215369],[2.760591, 49.647163],[2.952975, 50.057504],[3.344742, 50.280862],[3.768293, 50.451306],[4.21659, 50.534029]]

   for (point of points) {
      googlePlaces(point);
    }

function googlePlaces(point) {
  var latLng = new google.maps.LatLng(point[1],point[0])
  var request = {
    location: latLng,
    radius: '10000'
  };

  service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request, callback);  // hits this code [i] times first...
}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {

//results.forEach(result => placesOfInterest.push(result)) // originally tried this way

    results.forEach(result => superPush(result)) // ...then hits this code [i] times

   }
}

function superPush(result) {

  fetchData(result).then(function() {
    placesOfInterest.push(result);
  })
}

What can I do? There's no way to not call the callback, but I can't think of a way to get around it.

Body:
One option is to use function closure to give access to the index of the array that the results need to be saved at:

function googlePlaces(point, index) { // function closure on index
  var latLng = new google.maps.LatLng(point[1], point[0])
  var request = {
    location: latLng,
    radius: '10000'
  };

  service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request, function(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      resultsArray[index] = results;
    }
  })
}

calling it like this:

var i = 0;
for (point of points) {
  googlePlaces(point, i);
  i++;
}

proof of concept fiddle

code snippet:

// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

var map;
var service;
var infowindow;
var resultsArray = [];
var bounds;

function initMap() {
  bounds = new google.maps.LatLngBounds();
  infowindow = new google.maps.InfoWindow();
  map = new google.maps.Map(
    document.getElementById('map'));

  var points = [
    [2.627365, 49.215369],
    [2.760591, 49.647163],
    [2.952975, 50.057504],
    [3.344742, 50.280862],
    [3.768293, 50.451306],
    [4.21659, 50.534029]
  ]
  var i = 0;
  for (point of points) {
    googlePlaces(point, i);
    i++;
  }
}

function googlePlaces(point, index) {
  var latLng = new google.maps.LatLng(point[1], point[0])
  var request = {
    location: latLng,
    radius: '10000'
  };

  service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request, function(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {

      resultsArray[index] = results; // ...then hits this code [i] times

      for (var i = 0; i < results.length; i++) {
        var marker = createMarker(results[i], "search " + index);
        bounds.extend(marker.getPosition());
      }
      map.fitBounds(bounds);
    }
  })
}

function createMarker(place, text) {
  var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location
  });

  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(text + "<br>" + place.name);
    infowindow.open(map, this);
  });
  return marker;
}

html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
}

<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initMap" async defer></script>


问:
Django - Using mysql.connector.django gives TypeError: not all arguments converted during string formatting
When using Django with mysql-connector-python and the Admin views, and trying to list data from one of the tables, the page fails with TypeError: not all arguments converted during string formatting. The Django Rest Framework APIs work and return data for the same table.

Has anyone seen this before? Any ideas to fix this?

Same code base works on a Postgres backend.

Versions:

```<code>django==2.0.13
djangorestframework==3.8.2
mysql-connector-python==8.0.5
</code>```

Stacktrace:

```<code>2019-05-23 15:06:08,121 CST [ERROR] [PID:99924] [TNAME:Thread-8] django.request| Internal Server Error: /admin/api/source/
Traceback (most recent call last):
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
    response = get_response(request)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 158, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 156, in _get_response
    response = response.render()
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/response.py", line 106, in render
    self.content = self.rendered_content
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/response.py", line 83, in rendered_content
    content = template.render(context, self._request)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 175, in render
    return self._render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 167, in _render
    return self.nodelist.render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 943, in render
    bit = node.render_annotated(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 910, in render_annotated
    return self.render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/loader_tags.py", line 155, in render
    return compiled_parent._render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 167, in _render
    return self.nodelist.render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 943, in render
    bit = node.render_annotated(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 910, in render_annotated
    return self.render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/loader_tags.py", line 155, in render
    return compiled_parent._render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 167, in _render
    return self.nodelist.render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 943, in render
    bit = node.render_annotated(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 910, in render_annotated
    return self.render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/loader_tags.py", line 67, in render
    result = block.nodelist.render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 943, in render
    bit = node.render_annotated(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 910, in render_annotated
    return self.render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/loader_tags.py", line 67, in render
    result = block.nodelist.render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 943, in render
    bit = node.render_annotated(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 910, in render_annotated
    return self.render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/library.py", line 214, in render
    _dict = self.func(*resolved_args, **resolved_kwargs)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/contrib/admin/templatetags/admin_list.py", line 379, in date_hierarchy
    } for day in days]
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/db/models/query.py", line 272, in __iter__
    self._fetch_all()
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/db/models/query.py", line 1182, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/db/models/query.py", line 178, in __iter__
    for row in compiler.results_iter(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size):
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1019, in results_iter
    results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1055, in execute_sql
    sql, params = self.as_sql()
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 461, in as_sql
    where, w_params = self.compile(self.where) if self.where is not None else ("", [])
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 393, in compile
    sql, params = node.as_sql(self, self.connection)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/db/models/sql/where.py", line 80, in as_sql
    sql, params = compiler.compile(child)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 393, in compile
    sql, params = node.as_sql(self, self.connection)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/db/models/lookups.py", line 160, in as_sql
    lhs_sql, params = self.process_lhs(compiler, connection)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/db/models/lookups.py", line 155, in process_lhs
    db_type, field_internal_type) % lhs_sql
TypeError: not all arguments converted during string formatting
</code>```

答:
You need to upgrade to the latest Connector/Python version (8.0.16 at this time).</p>

```<code>pip install --upgrade mysql-connector-python
</code>```

Body:
When using Django with mysql-connector-python and the Admin views, and trying to list data from one of the tables, the page fails with TypeError: not all arguments converted during string formatting. The Django Rest Framework APIs work and return data for the same table.

Has anyone seen this before? Any ideas to fix this?

Same code base works on a Postgres backend.

Versions:

django==2.0.13
djangorestframework==3.8.2
mysql-connector-python==8.0.5

Stacktrace:

2019-05-23 15:06:08,121 CST [ERROR] [PID:99924] [TNAME:Thread-8] django.request| Internal Server Error: /admin/api/source/
Traceback (most recent call last):
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
    response = get_response(request)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 158, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 156, in _get_response
    response = response.render()
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/response.py", line 106, in render
    self.content = self.rendered_content
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/response.py", line 83, in rendered_content
    content = template.render(context, self._request)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 175, in render
    return self._render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 167, in _render
    return self.nodelist.render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 943, in render
    bit = node.render_annotated(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 910, in render_annotated
    return self.render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/loader_tags.py", line 155, in render
    return compiled_parent._render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 167, in _render
    return self.nodelist.render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 943, in render
    bit = node.render_annotated(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 910, in render_annotated
    return self.render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/loader_tags.py", line 155, in render
    return compiled_parent._render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 167, in _render
    return self.nodelist.render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 943, in render
    bit = node.render_annotated(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 910, in render_annotated
    return self.render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/loader_tags.py", line 67, in render
    result = block.nodelist.render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 943, in render
    bit = node.render_annotated(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 910, in render_annotated
    return self.render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/loader_tags.py", line 67, in render
    result = block.nodelist.render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 943, in render
    bit = node.render_annotated(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 910, in render_annotated
    return self.render(context)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/library.py", line 214, in render
    _dict = self.func(*resolved_args, **resolved_kwargs)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/contrib/admin/templatetags/admin_list.py", line 379, in date_hierarchy
    } for day in days]
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/db/models/query.py", line 272, in __iter__
    self._fetch_all()
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/db/models/query.py", line 1182, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/db/models/query.py", line 178, in __iter__
    for row in compiler.results_iter(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size):
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1019, in results_iter
    results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1055, in execute_sql
    sql, params = self.as_sql()
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 461, in as_sql
    where, w_params = self.compile(self.where) if self.where is not None else ("", [])
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 393, in compile
    sql, params = node.as_sql(self, self.connection)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/db/models/sql/where.py", line 80, in as_sql
    sql, params = compiler.compile(child)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 393, in compile
    sql, params = node.as_sql(self, self.connection)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/db/models/lookups.py", line 160, in as_sql
    lhs_sql, params = self.process_lhs(compiler, connection)
  File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/db/models/lookups.py", line 155, in process_lhs
    db_type, field_internal_type) % lhs_sql
TypeError: not all arguments converted during string formatting

Body:
You need to upgrade to the latest Connector/Python version (8.0.16 at this time).

pip install --upgrade mysql-connector-python


问:
Login request with JWT response
I have a request '/login' which basically validates the USERNAME and PASSWORD and further on success, return token (JWT).

Now the question is my API is also returning USERNAME and PASSWORD in response with token. Is it the right way or should I remove USERNAME and PASSWORD from response.

REQUEST JSON

```<code>{
"USERNAME": "admin",
"PASSWORD": "123456"
}
</code>```

Response

```<code>{
    "token": "eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE1NTk1NTM4NjcsInVzZXJMb2dpbklkIjoiYWRtaW4ifQ.fxaENKTXxPG5wl8hp7_cSORfMzI38ODu_HgNRj3c7UZwohiFNFfZVpou8MYU4kkxEXV87-LP3upctjGCpGV6_Q",
    "PASSWORD": "123456",
    "USERNAME": "admin"
}
</code>```

答:
For security reasons, you should definitely remove the password from the response. I don't see why would you want it there.
Even the username as well, if you need any information, it should be inside the token itself.

Another good approach is, having a refreshToken together, so in case of token expire, you can use the refreshToken to get a new one, without asking the user to login again.

Also, avoid in the JWT to contain sensitive information, like email, password, full name, etc ...

As anyone can get it and post in the page: https://jwt.io/ to retrieve what is inside.

Title: Login request with JWT response

Body:
I have a request '/login' which basically validates the USERNAME and PASSWORD and further on success, return token (JWT).

Now the question is my API is also returning USERNAME and PASSWORD in response with token. Is it the right way or should I remove USERNAME and PASSWORD from response.

REQUEST JSON

{
"USERNAME": "admin",
"PASSWORD": "123456"
}

Response

{
    "token": "eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE1NTk1NTM4NjcsInVzZXJMb2dpbklkIjoiYWRtaW4ifQ.fxaENKTXxPG5wl8hp7_cSORfMzI38ODu_HgNRj3c7UZwohiFNFfZVpou8MYU4kkxEXV87-LP3upctjGCpGV6_Q",
    "PASSWORD": "123456",
    "USERNAME": "admin"
}


问:
Serialize child collections with interfaces
I have an interface like so

```<code>public interface IA{
    IEnumerable<IB> Items {get;set;}
}

public interface IB{
    int ID {get;set;}
}
</code>```

If I try to serialize the interface I get an error

```<code>Cannot serialize interface
</code>```

If I create a concrete version of the interface, I can't create a concrete version of the collection.

```<code>public class classA:IA{
   public IEnumerable<B> Items {get;set;}  //this doesn't match the interface
}
</code>```

but if I do the below we still have the serialization problem

```<code>public class classA:IA{
   public IEnumerable<IB> Items {get;set;}
}
</code>```

答: Are you sure you want an interface? A generic might help you with serializing IEnumerables of different types.</p>

Body:
I have an interface like so

public interface IA{
    IEnumerable<IB> Items {get;set;}
}

public interface IB{
    int ID {get;set;}
}

If I try to serialize the interface I get an error

Cannot serialize interface

If I create a concrete version of the interface, I can't create a concrete version of the collection.

public class classA:IA{
   public IEnumerable Items {get;set;}  //this doesn't match the interface
}

but if I do the below we still have the serialization problem

public class classA:IA{
   public IEnumerable<IB> Items {get;set;}
}


问:
populate select picker on live-search event
I am using a selectpicker (https://silviomoreto.github.io/bootstrap-select/examples/#live-search) that I populate from a rest API.

At this point, I have only 30 entries. however, this number will grow very soon.
I want to start with an empty selectpicker, then, when the user write some text in the live-search input, I populate the selectpicker only with the corresponding items.

for example, if the user writes "al", then I will populate my selectpicker with entries containing "al".
unfortunately, this class does not contain events on live search. Could you suggest another class??

Any input will help

Regards

答:
Since boostrap-select (or selectpicker) does not support this yet, I've found a workaround.

This is not the best practice, but it works.

```<code> $('#youselectpicker').on('loaded.bs.select', function (e, clickedIndex, isSelected, previousValue) {
        $(".youselectpicker .bs-searchbox input").on('keyup',function(){
            //place your code here
            //don't forget to refresh the select picker if you change the options
        })
      });
</code>```

Body:
Since boostrap-select (or selectpicker) does not support this yet, I've found a workaround.

This is not the best practice, but it works.

 $('#youselectpicker').on('loaded.bs.select', function (e, clickedIndex, isSelected, previousValue) {
        $(".youselectpicker .bs-searchbox input").on('keyup',function(){
            //place your code here
            //don't forget to refresh the select picker if you change the options
        })
      });


问:
xcode-select error while trying to install Homebrew on macOS Sierra
While trying to install Homebrew on macOS Sierra:</p>

```<code>xcode-select: error: invalid developer directory '/Library/Developer/CommandLineTools'
Failed during: /usr/bin/sudo /usr/bin/xcode-select --switch /Library/Developer/CommandLineTools
</code>```

答:
Yes , i have solved this error by using following steps.

In your terminal write command ::   xcode-select --install

after doing step no 1 you will get one popUp , so click on install

Body:
While trying to install Homebrew on macOS Sierra:

xcode-select: error: invalid developer directory '/Library/Developer/CommandLineTools'
Failed during: /usr/bin/sudo /usr/bin/xcode-select --switch /Library/Developer/CommandLineTools


问:
How to save each field in repeater field as model
There are 2 models: Form and Prog.

Form can have many unique Progs. It's not like movies and genres, it's like   user and his messages.

There is table for Forms, for Progs and cross reference table forms_progs (it has 2 columns - form_id and prog_id).

I added repeater field (Progs) to form of model Form. If I have, for example, 3 Progs how can I create models of them first and then connect their ids with id of the Form?

答:
This is kind of One-To-Many associations where a single model owns any amount of other models. You can do it in 2 tables.

For Form model:

```<code>class Form extends Model
{
    public function progs()
    {
        return $this->hasMany('App\Prog');
    }
}
</code>```

For Prog Model:

```<code>class Prog extends Model
{
    public function form()
    {
        return $this->belongsTo('App\Form');
    }
}
</code>```

Once the relationship has been defined, you can retrieve they "dynamic properties" in both direction.

```<code>// Get progs in form _id = 1
$progs = App\Form::find(1)->progs;

foreach ($progs as $prog) {
    //..
}

// Get Form Title in Prog _id = 1
$prog = App\Prog::find(1);

echo $prog->form->title;
</code>```

Body:
This is kind of One-To-Many associations where a single model owns any amount of other models. You can do it in 2 tables.

For Form model:

class Form extends Model
{
    public function progs()
    {
        return $this->hasMany('App\Prog');
    }
}

For Prog Model:

class Prog extends Model
{
    public function form()
    {
        return $this->belongsTo('App\Form');
    }
}

Once the relationship has been defined, you can retrieve they "dynamic properties" in both direction.

// Get progs in form _id = 1
$progs = App\Form::find(1)->progs;

foreach ($progs as $prog) {
    //..
}

// Get Form Title in Prog _id = 1
$prog = App\Prog::find(1);

echo $prog->form->title;


问:
How to make an ASP.Net page with a C# code behind that will work in Sharepoint
I need to develop a page for Sharepoint.

Basically it is a 3 step process that takes some inputs, gets some data and shows a preview of it, then allows the data to be sent off attached to an email.

I know ASP.Net and C#.Net, and the problem should be reasonably easy to solve with an ASP.Net page and a C# code behind.

However I've never had to work with Sharepoint before, and I don't know what is required to make the page 'work in Sharepoint'.

Is there anything special that needs to be done to make it work in Sharepoint? Is an ASPX page the right approach for this sort of problem?

(I'm developing on an XP machine using Visual Studio 2008.)

答: This is a very loaded question with a very long answer. Any short answer will probably just create more questions. You need to get a book like this one and read it cover to cover.</p>

OwnerDisplayName: Sophia

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Rex M