text:
Q: Is there a direct correlation between dll and pdb size? I'll start by saying that this isn't a problem, just curiosity.
I have some .NET dlls in my program, and I'm seeing a 200-500 % size increase for the pdb size.
From that, I'm trying to do a back of the envelope calculation for how much code is in a few of our third party libraries, because I have a suspicion that it's "way too much" (in terms of how much code I estimate it would take me to write the same thing). Reflector crashes on my machine when dealing with these dlls, but because this is curiosity it's not really a priority to figure out why.
(I know that conventional wisdom says "lines of code" isn't necessarily the greatest metric, but it can be useful: i.e. if a "Hello World" program takes 500 lines excluding framework, something is definitely wrong)

A: There is no direct correlation between DLL and PDB size, but there may be a correlation between number of IL instructions in DLL and PDB size. It's fair to expect that one 1 KB worth of ternary operators would produce larger PDB than 1 KB worth of code that writes formatted string to console.


text:
Q: Using OpenMP for the XCompressCU function from the project VVCSoftware_VTM I'm doing a college project that aims to reduce VTM encoder time. To do this, it has been decided to try to divide the loop into two threads in the XCompressCU function of the Jvet VTM encoder. VVCSoftware_VTM/source/Lib/EncoderLib/EncCu.cpp
The main will be in charge of managing most of the checking modes:
(ETM_HASH_INTER: Hash Inter mode
ETM_MERGE_SKIP: Merge Skip mode
ETM_INTER_ME: Inter Motion Estimation mode
ETM_AFFINE: Affine mode
ETM_MERGE_GEO: Merge Geometry mode
ETM_INTRA: Intra mode
ETM_PALETTE: Palette mode
ETM_SPLIT_BT_H: Split Binary Tree Horizontal mode
ETM_SPLIT_BT_V: Split Binary Tree Vertical mode
ETM_SPLIT_TT_H: Split Ternary Tree Horizontal mode
ETM_SPLIT_TT_V: Split Ternary Tree Vertical mode
ETM_POST_DONT_SPLIT: Dummy mode to collect data from unsplit coding
ETM_RECO_CACHED: Reuse Cached Results mode
ETM_TRIGGER_IMV_LIST: Trigger Inter-MV List mode
ETM_IBC: IBC mode
ETM_IBC_MERGE: IBC Merge mode
ETM_INVALID: Invalid mode)
And the secondary thread that will handle the mode: (ETM_SPLIT_QT: Split Quad Tree mode).
The OpenMP library is used to launch 2 threads within a block. But it has only been done in such a way that when a thread attends to a mode, the other thread blocks, and therefore there is no parallelization and blocks occur.
In my code I have decided to create copies of the variables and then launch the threads separately inside the loop each with a different copy. The original loop code has been moved to a function to make calling threads easier. And at the end of the calls the variables are unified. My code is the following:
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/\*
The EncTestModeType enumeration defines the different encoding test modes that can be used in the encoding process.
These modes are:
ETM_HASH_INTER: Hash Inter mode
ETM_MERGE_SKIP: Merge Skip mode
ETM_INTER_ME: Inter Motion Estimation mode
ETM_AFFINE: Affine mode
ETM_MERGE_GEO: Merge Geometry mode
ETM_INTRA: Intra mode
ETM_PALETTE: Palette mode
A-ETM_SPLIT_QT: Split Quad Tree mode
B-ETM_SPLIT_BT_H: Split Binary Tree Horizontal mode
C-ETM_SPLIT_BT_V: Split Binary Tree Vertical mode
D-ETM_SPLIT_TT_H: Split Ternary Tree Horizontal mode
E-ETM_SPLIT_TT_V: Split Ternary Tree Vertical mode
ETM_POST_DONT_SPLIT: Dummy mode to collect data from unsplit coding
ETM_RECO_CACHED: Reuse Cached Results mode
ETM_TRIGGER_IMV_LIST: Trigger Inter-MV List mode
ETM_IBC: IBC mode
ETM_IBC_MERGE: IBC Merge mode
ETM_INVALID: Invalid mode
\*/

std::cout \<\< "\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\> WHILE START " \<\< getpid() \<\< std::endl;
do
{
for (int i = compBegin; i \< (compBegin + numComp); i++)
{
ComponentID comID                 = jointPLT ? (ComponentID) compBegin : ((i \> 0) ? COMPONENT_Cb : COMPONENT_Y);
tempCS-\>prevPLT.curPLTSize\[comID\] = curLastPLTSize\[comID\];
memcpy(tempCS-\>prevPLT.curPLT\[i\], curLastPLT\[i\], curLastPLTSize\[comID\] \* sizeof(Pel));
}

    EncTestMode currTestMode    = m_modeCtrl->currTestMode();
    currTestMode.maxCostAllowed = maxCostAllowed;
    omp_set_nested(1);

    //ASIGNACIÓN VARIABLES DE THREAD
    ///////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////
    QTBTPartitioner* newPartitionerPointer = dynamic_cast<QTBTPartitioner*>(&partitioner);
    QTBTPartitioner* newPartitioner        = new QTBTPartitioner(*newPartitionerPointer);
    newPartitioner->copyState(partitioner);

    CodingStructure* newTempCS = new CodingStructure(*tempCS);
    newTempCS->copyStructure(*tempCS, newPartitioner->chType);

    //CodingStructure* newBestCS = new CodingStructure(*bestCS);
    //newBestCS->copyStructure(*bestCS, newPartitioner->chType);

    double newMaxCostAllowed = maxCostAllowed;
    EncTestMode *newCurrTestMode    = new EncTestMode(currTestMode);
    newCurrTestMode->maxCostAllowed = newMaxCostAllowed;

    const PPS& newPps             = *newTempCS->pps;
    Slice&     newSlice           = *newTempCS->slice;

    double newBestIntPelCost  = MAX_DOUBLE;

    double newSplitRdCostBest[NUM_PART_SPLIT];
    for (int i = 0; i < NUM_PART_SPLIT; i++)
    {
      newSplitRdCostBest[i] = splitRdCostBest[i];
    }

    SplitSeries* newSplitmodePointer = new SplitSeries(splitmode);
    SplitSeries  newSplitmode        = *newSplitmodePointer;

    uint32_t* newCompBeginPointer = new uint32_t(compBegin);
    uint32_t  newCompBegin        = *newCompBeginPointer;
    uint32_t* newNumCompPointer = new uint32_t(numComp);
    uint32_t  newNumComp          = *newNumCompPointer;
    bool     newJointPLT = jointPLT;

    uint8_t newBestLastPLTSize[MAX_NUM_CHANNEL_TYPE];
    for (int i = 0; i < MAX_NUM_CHANNEL_TYPE; i++)
    {
      uint8_t originalValue = bestLastPLTSize[i];
      uint8_t* copiaPointerNBLPS  = new uint8_t(originalValue);
      newBestLastPLTSize[i]  = *copiaPointerNBLPS;
      delete (copiaPointerNBLPS);
    }

    Pel  newBestLastPLT[MAX_NUM_COMPONENT][MAXPLTPREDSIZE];
    for (int i = 0; i < MAX_NUM_COMPONENT; i++)
    {
      for (int j = 0; j < MAXPLTPREDSIZE; j++)
      {
        Pel originalValue    = bestLastPLT[i][j];
        Pel* copiaPointerNBLP    = new Pel(originalValue);
        newBestLastPLT[i][j] = *copiaPointerNBLP;
        delete (copiaPointerNBLP);
      }
    }
    ///////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////
    bool main_has_work = false;
    bool thread_has_work = false;

    #pragma omp parallel num_threads(2)
    {
      std::cout << "Threads number = " << omp_get_thread_num() + 1 << "/" << omp_get_num_threads() << std::endl;
      // THREAD
      if (omp_get_thread_num() == SECONDARY_PROCESS && newCurrTestMode->type == ETM_SPLIT_QT)
      {

           thread_has_work = true;
           std::cout << "---Thread working..." << ", mode = " << newCurrTestMode->type << ", line = " << __LINE__ << std::endl;
           xCalcBestCost_ThreadFunction(newTempCS, bestCS, *newPartitioner, *newCurrTestMode, newPps, newSlice, newBestIntPelCost, newSplitRdCostBest, newSplitmode, newPartitioner->modeType,
                                         newPartitioner->treeType, newPartitioner->chType, newNumComp, newJointPLT, newCompBegin, newBestLastPLTSize, newBestLastPLT, newMaxCostAllowed);
           std::cout << "-----------------Thread returning..." << ", mode = " << newCurrTestMode->type << ", line = " << __LINE__ << std::endl;
      }

      // MAIN
      if (omp_get_thread_num() == MAIN_PROCESS && currTestMode.type != ETM_SPLIT_QT)
      {

          main_has_work = true;
          std::cout << "---Main working..."
                         << ", mode = " << currTestMode.type << ", line = " << __LINE__ << std::endl;
            xCalcBestCost_ThreadFunction(tempCS, bestCS, partitioner, currTestMode, pps, slice, bestIntPelCost, splitRdCostBest, splitmode,
                                       modeTypeParent, treeTypeParent, chTypeParent, numComp, jointPLT, compBegin, bestLastPLTSize, bestLastPLT, maxCostAllowed);
            std::cout << "-----------------Main returning..." << ", mode = " << currTestMode.type << ", line = " << __LINE__ << std::endl;

      }
      std::cout << "---Synchronize barrier point waiting process---- " << omp_get_thread_num() + 1 << std::endl;
      #pragma omp barrier
    }
    if (thread_has_work)
    {
      std::cout << "----------------------------------------------------------------------------------------------Updating CodingStructures--- " << omp_get_thread_num() + 1 << std::endl;
      //////////////////////////////////////////////////////////////////////////////////////////////////
      //////////////////////////////////////////////////////////////////////////////////////////////////
      tempCS = new CodingStructure(*newTempCS);
      tempCS->copyStructure(*newTempCS, newPartitioner->chType);

      //bestCS = new CodingStructure(*newBestCS);
      //bestCS->copyStructure(*newTempCS, newPartitioner->chType);

      partitioner.copyState(*newPartitioner);

      maxCostAllowed                  = newMaxCostAllowed;
      EncTestMode* currTestModeReturn = new EncTestMode(*newCurrTestMode);
      currTestMode                    = *currTestModeReturn;
      currTestMode.maxCostAllowed     = newMaxCostAllowed;

      tempCS->pps = new PPS(newPps);
      tempCS->slice = new Slice(newSlice);

      bestIntPelCost = newBestIntPelCost;

      for (int i = 0; i < NUM_PART_SPLIT; i++)
      {
        splitRdCostBest[i] = newSplitRdCostBest[i];
      }

      splitmode = *newSplitmodePointer;

      numComp = *newNumCompPointer;
      jointPLT = newJointPLT;
      compBegin = *newCompBeginPointer;

      for (int i = 0; i < MAX_NUM_CHANNEL_TYPE; i++)
      {
        uint8_t  copiaValue = newBestLastPLTSize[i];
        uint8_t* originalPointerBLPS  = new uint8_t(copiaValue);
        newBestLastPLTSize[i]  = *originalPointerBLPS;
        delete (originalPointerBLPS);
      }

      for (int i = 0; i < MAX_NUM_COMPONENT; i++)
      {
        for (int j = 0; j < MAXPLTPREDSIZE; j++)
        {
          Pel  copiaValue    = bestLastPLT[i][j];
          Pel* originalPointerNBLP = new Pel(copiaValue);
          newBestLastPLT[i][j]  = *originalPointerNBLP;
          delete (originalPointerNBLP);
        }
      }
      //////////////////////////////////////////////////////////////////////////////////////////////////
      //////////////////////////////////////////////////////////////////////////////////////////////////
    }
    std::cout << "---Synchronize barrier point passed process---- " << omp_get_thread_num() + 1 << std::endl;

} while(m_modeCtrl-\>nextMode( \*tempCS, partitioner ));

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::cout \<\< "\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\<\< WHILE END " \<\< getpid() \<\< std::endl;

The original code that can be seen in the previous link is:
 do
  {
    for (int i = compBegin; i < (compBegin + numComp); i++)
    {
      ComponentID comID = jointPLT ? (ComponentID)compBegin : ((i > 0) ? COMPONENT_Cb : COMPONENT_Y);
      tempCS->prevPLT.curPLTSize[comID] = curLastPLTSize[comID];
      memcpy(tempCS->prevPLT.curPLT[i], curLastPLT[i], curLastPLTSize[comID] * sizeof(Pel));
    }
    EncTestMode currTestMode = m_modeCtrl->currTestMode();
    currTestMode.maxCostAllowed = maxCostAllowed;

    if (pps.getUseDQP() && partitioner.isSepTree(*tempCS) && isChroma( partitioner.chType ))
    {
      const Position chromaCentral(tempCS->area.Cb().chromaPos().offset(tempCS->area.Cb().chromaSize().width >> 1, tempCS->area.Cb().chromaSize().height >> 1));
      const Position lumaRefPos(chromaCentral.x << getComponentScaleX(COMPONENT_Cb, tempCS->area.chromaFormat), chromaCentral.y << getComponentScaleY(COMPONENT_Cb, tempCS->area.chromaFormat));
      const CodingStructure* baseCS = bestCS->picture->cs;
      const CodingUnit* colLumaCu = baseCS->getCU(lumaRefPos, CHANNEL_TYPE_LUMA);

      if (colLumaCu)
      {
        currTestMode.qp = colLumaCu->qp;
      }
    }

#if SHARP_LUMA_DELTA_QP || ENABLE_QPA_SUB_CTU
    if (partitioner.currQgEnable() && (
#if SHARP_LUMA_DELTA_QP
        (m_pcEncCfg->getLumaLevelToDeltaQPMapping().isEnabled()) ||
#endif
#if ENABLE_QPA_SUB_CTU
        (m_pcEncCfg->getUsePerceptQPA() && !m_pcEncCfg->getUseRateCtrl() && pps.getUseDQP())
#else
        false
#endif
      ))
    {
#if ENABLE_SPLIT_PARALLELISM
      CHECK( tempCS->picture->scheduler.getSplitJobId() > 0, "Changing lambda is only allowed in the master thread!" );
#endif
      if (currTestMode.qp >= 0)
      {
        updateLambda (&slice, currTestMode.qp,
 #if WCG_EXT && ER_CHROMA_QP_WCG_PPS
                      m_pcEncCfg->getWCGChromaQPControl().isEnabled(),
 #endif
                      CS::isDualITree (*tempCS) || (partitioner.currDepth == 0));
      }
    }
#endif

    if( currTestMode.type == ETM_INTER_ME )
    {
      if( ( currTestMode.opts & ETO_IMV ) != 0 )
      {
        const bool skipAltHpelIF = ( int( ( currTestMode.opts & ETO_IMV ) >> ETO_IMV_SHIFT ) == 4 ) && ( bestIntPelCost > 1.25 * bestCS->cost );
        if (!skipAltHpelIF)
        {
          tempCS->bestCS = bestCS;
          xCheckRDCostInterIMV(tempCS, bestCS, partitioner, currTestMode, bestIntPelCost);
          tempCS->bestCS = nullptr;
        }
      }
      else
      {
        tempCS->bestCS = bestCS;
        xCheckRDCostInter( tempCS, bestCS, partitioner, currTestMode );
        tempCS->bestCS = nullptr;
      }

    }
    else if (currTestMode.type == ETM_HASH_INTER)
    {
      xCheckRDCostHashInter( tempCS, bestCS, partitioner, currTestMode );
    }
    else if( currTestMode.type == ETM_AFFINE )
    {
      xCheckRDCostAffineMerge2Nx2N( tempCS, bestCS, partitioner, currTestMode );
    }
#if REUSE_CU_RESULTS
    else if( currTestMode.type == ETM_RECO_CACHED )
    {
      xReuseCachedResult( tempCS, bestCS, partitioner );
    }
#endif
    else if( currTestMode.type == ETM_MERGE_SKIP )
    {
      xCheckRDCostMerge2Nx2N( tempCS, bestCS, partitioner, currTestMode );
      CodingUnit* cu = bestCS->getCU(partitioner.chType);
      if (cu)
      cu->mmvdSkip = cu->skip == false ? false : cu->mmvdSkip;
    }
    else if( currTestMode.type == ETM_MERGE_GEO )
    {
      xCheckRDCostMergeGeo2Nx2N( tempCS, bestCS, partitioner, currTestMode );
    }
    else if( currTestMode.type == ETM_INTRA )
    {
      if (slice.getSPS()->getUseColorTrans() && !CS::isDualITree(*tempCS))
      {
        bool skipSecColorSpace = false;
        skipSecColorSpace = xCheckRDCostIntra(tempCS, bestCS, partitioner, currTestMode, (m_pcEncCfg->getRGBFormatFlag() ? true : false));
        if ((m_pcEncCfg->getCostMode() == COST_LOSSLESS_CODING && slice.isLossless()) && !m_pcEncCfg->getRGBFormatFlag())
        {
          skipSecColorSpace = true;
        }
        if (!skipSecColorSpace && !tempCS->firstColorSpaceTestOnly)
        {
          xCheckRDCostIntra(tempCS, bestCS, partitioner, currTestMode, (m_pcEncCfg->getRGBFormatFlag() ? false : true));
        }

        if (!tempCS->firstColorSpaceTestOnly)
        {
          if (tempCS->tmpColorSpaceIntraCost[0] != MAX_DOUBLE && tempCS->tmpColorSpaceIntraCost[1] != MAX_DOUBLE)
          {
            double skipCostRatio = m_pcEncCfg->getRGBFormatFlag() ? 1.1 : 1.0;
            if (tempCS->tmpColorSpaceIntraCost[1] > (skipCostRatio*tempCS->tmpColorSpaceIntraCost[0]))
            {
              tempCS->firstColorSpaceTestOnly = bestCS->firstColorSpaceTestOnly = true;
            }
          }
        }
        else
        {
          CHECK(tempCS->tmpColorSpaceIntraCost[1] != MAX_DOUBLE, "the RD test of the second color space should be skipped");
        }
      }
      else
      {
        xCheckRDCostIntra(tempCS, bestCS, partitioner, currTestMode, false);
      }
    }
    else if (currTestMode.type == ETM_PALETTE)
    {
      xCheckPLT( tempCS, bestCS, partitioner, currTestMode );
    }
    else if (currTestMode.type == ETM_IBC)
    {
      xCheckRDCostIBCMode(tempCS, bestCS, partitioner, currTestMode);
    }
    else if (currTestMode.type == ETM_IBC_MERGE)
    {
      xCheckRDCostIBCModeMerge2Nx2N(tempCS, bestCS, partitioner, currTestMode);
    }
    else if( isModeSplit( currTestMode ) )
    {
      if (bestCS->cus.size() != 0)
      {
        splitmode = bestCS->cus[0]->splitSeries;
      }
      assert( partitioner.modeType == tempCS->modeType );
      int signalModeConsVal = tempCS->signalModeCons( getPartSplit( currTestMode ), partitioner, modeTypeParent );
      int numRoundRdo = signalModeConsVal == LDT_MODE_TYPE_SIGNAL ? 2 : 1;
      bool skipInterPass = false;
      for( int i = 0; i < numRoundRdo; i++ )
      {
        //change cons modes
        if( signalModeConsVal == LDT_MODE_TYPE_SIGNAL )
        {
          CHECK( numRoundRdo != 2, "numRoundRdo shall be 2 - [LDT_MODE_TYPE_SIGNAL]" );
          tempCS->modeType = partitioner.modeType = (i == 0) ? MODE_TYPE_INTER : MODE_TYPE_INTRA;
        }
        else if( signalModeConsVal == LDT_MODE_TYPE_INFER )
        {
          CHECK( numRoundRdo != 1, "numRoundRdo shall be 1 - [LDT_MODE_TYPE_INFER]" );
          tempCS->modeType = partitioner.modeType = MODE_TYPE_INTRA;
        }
        else if( signalModeConsVal == LDT_MODE_TYPE_INHERIT )
        {
          CHECK( numRoundRdo != 1, "numRoundRdo shall be 1 - [LDT_MODE_TYPE_INHERIT]" );
          tempCS->modeType = partitioner.modeType = modeTypeParent;
        }

        //for lite intra encoding fast algorithm, set the status to save inter coding info
        if( modeTypeParent == MODE_TYPE_ALL && tempCS->modeType == MODE_TYPE_INTER )
        {
          m_pcIntraSearch->setSaveCuCostInSCIPU( true );
          m_pcIntraSearch->setNumCuInSCIPU( 0 );
        }
        else if( modeTypeParent == MODE_TYPE_ALL && tempCS->modeType != MODE_TYPE_INTER )
        {
          m_pcIntraSearch->setSaveCuCostInSCIPU( false );
          if( tempCS->modeType == MODE_TYPE_ALL )
          {
            m_pcIntraSearch->setNumCuInSCIPU( 0 );
          }
        }

        xCheckModeSplit( tempCS, bestCS, partitioner, currTestMode, modeTypeParent, skipInterPass );
        //recover cons modes
        tempCS->modeType = partitioner.modeType = modeTypeParent;
        tempCS->treeType = partitioner.treeType = treeTypeParent;
        partitioner.chType = chTypeParent;
        if( modeTypeParent == MODE_TYPE_ALL )
        {
          m_pcIntraSearch->setSaveCuCostInSCIPU( false );
          if( numRoundRdo == 2 && tempCS->modeType == MODE_TYPE_INTRA )
          {
            m_pcIntraSearch->initCuAreaCostInSCIPU();
          }
        }
        if( skipInterPass )
        {
          break;
        }
      }
      if (splitmode != bestCS->cus[0]->splitSeries)
      {
        splitmode = bestCS->cus[0]->splitSeries;
        const CodingUnit&     cu = *bestCS->cus.front();
        cu.cs->prevPLT = bestCS->prevPLT;
        for (int i = compBegin; i < (compBegin + numComp); i++)
        {
          ComponentID comID = jointPLT ? (ComponentID)compBegin : ((i > 0) ? COMPONENT_Cb : COMPONENT_Y);
          bestLastPLTSize[comID] = bestCS->cus[0]->cs->prevPLT.curPLTSize[comID];
          memcpy(bestLastPLT[i], bestCS->cus[0]->cs->prevPLT.curPLT[i], bestCS->cus[0]->cs->prevPLT.curPLTSize[comID] * sizeof(Pel));
        }
      }
    }
    else
    {
      THROW( "Don't know how to handle mode: type = " << currTestMode.type << ", options = " << currTestMode.opts );
    }
  } while( m_modeCtrl->nextMode( *tempCS, partitioner ) );

redpajama_set_name: RedPajamaStackExchange


text:
Q: In $\mathbb{R}^n$ with the usual metric, is the closure of an open ball equal to the closed ball? I read here : When is the closure of an open ball equal to the closed ball? and here : closed ball in euclidean space that in $(\mathbb{R}^n, d)$, which is Euclidean Space with the standard metric, the closure of an open ball is equal to the closed ball.
But pick a point $x \in \mathbb{R}^n$, and consider the open ball around $x$ of radius $0$, that is $\Phi = B_{(\mathbb{R}^n, d)}(x, 0) = \{y \in \mathbb{R}^n \ | \ d(x, y) < 0\} = \emptyset$. Now compare that to the closed ball around $x$ of radius $0$, which is $\Gamma = B_{(\mathbb{R}^n, d)}(x, 0) = \{y \in \mathbb{R}^n \ | \ d(x, y) \leq 0\} = \{x\}$.
Based on the answers in the questions above, we should have $\overline{\Phi} = \Gamma$ however we have $\overline{\Phi} =\Phi = \emptyset \neq \Gamma = \{x\}$, contradicting the answers above, so what am I missing here?

A: You should exclude $0$ as a radius. Defining $B(x,r) =\{y: d(x,y) < r\}$ and $D(x,r) = \{y: d(x,y) \le r\}$ for $r>0$, in any metric space, we can easily prove that for all $r>0$:
$$\overline{B(x,r)} \subseteq D(x,r)$$
with equality holding in e.g. all metrics derived from norms in a vector space, of which the Euclidean distance is an example. In general metric spaces the inclusion can be proper, and if we do allow $r=0$, it's always proper for that "radius".


text:
Q: Trying to see if there's a better way to structure this query with joins So far this is the best way I've come up with do do this query in mySQL but I just wanna make sure there's not a more efficient way to do this with joins, or if this is more or less not gunna kill preformance.
SELECT r.CAMPAIGN_ID as ID, ref.VALUE as VALUE, SUM(CLICKS_IN) as cin, SUM(CLICKS_OUT) as cout, SUM(SALES) as sin
FROM (
    SELECT CAMPAIGN_ID, COUNT(DISTINCT BIN_IP) AS CLICKS_IN, 0 AS CLICKS_OUT, 0 AS SALES FROM CLICKS_IN WHERE LANDER = ? AND TIME BETWEEN ? AND ? GROUP BY CAMPAIGN_ID
    UNION
    SELECT CAMPAIGN_ID, 0 AS CLICKS_IN, COUNT(DISTINCT BIN_IP) AS CLICKS_OUT, 0 AS SALES FROM CLICKS_OUT WHERE LANDER = ? AND TIME BETWEEN ? AND ? GROUP BY CAMPAIGN_ID
    UNION
    SELECT CAMPAIGN_ID, 0 AS CLICKS_IN, 0 AS CLICKS_OUT, SUM(REVENUE) AS SALES FROM CONVERSIONS WHERE LANDER = ? AND TIME BETWEEN ? AND ? GROUP BY CAMPAIGN_ID ) as r
INNER JOIN
    CLICKS_CAMPAIGN as ref ON ref.ID = r.CAMPAIGN_ID
GROUP BY ID, VALUE

Most of the join options I've tried lose cases where there's clicks and no sales, sales and no clicks etc, and this is the only way I've figured out that doesn't lose any cases without using sub-queries.

A: When you need aggregate values from multiple one-to-many relations at once, each aggregation needs to performed in a subquery (or it can be done in a UNION like your original query; as Barmar pointed out, your query is actually a fairly common form for a query retrieving this kind of data)
SELECT cc.ID, cc.VALUE, cIn.CLICKS_IN, cOut.CLICKS_OUT, cSales.SALES
FROM CLICKS_CAMPAIGN AS cc
LEFT JOIN (SELECT CAMPAIGN_ID, COUNT(DISTINCT BIN_IP) AS CLICKS_IN
           FROM CLICKS_IN
           WHERE LANDER = ? AND TIME BETWEEN ? AND ?
           GROUP BY CAMPAIGN_ID
          ) AS cIn ON cIn.CAMPAIGN_ID = cc.ID
LEFT JOIN (SELECT CAMPAIGN_ID, COUNT(DISTINCT BIN_IP) AS CLICKS_OUT
           FROM CLICKS_OUT
           WHERE LANDER = ? AND TIME BETWEEN ? AND ?
           GROUP BY CAMPAIGN_ID
          ) AS cOut ON cOut.CAMPAIGN_ID = cc.ID
LEFT JOIN (SELECT CAMPAIGN_ID, SUM(REVENUE) AS SALES
           FROM CONVERSIONS
           WHERE LANDER = ? AND TIME BETWEEN ? AND ?
           GROUP BY CAMPAIGN_ID
          ) AS cSales ON cSales.CAMPAIGN_ID = cc.ID
GROUP BY cc.ID, cc.VALUE
;

This is not exactly the same as your original query, as you will get all "campaigns", even ones without "clicks" or sales; but if that is important; you can add a WHERE or HAVING with
cIn.CLICKS_IN IS NOT NULL OR cOut.CLICKS_OUT IS NOT NULL OR cSales.SALES IS NOT NULL


text:
Q: I can't run facebook js api from local file? I've created a HTML5 app that is not running on any webserver. It's just html and javascript, and I want to make my users login so they could save their score with their id.
I've added the Facebook javascript and it's running, however I get this error:
Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings.  It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.

What does this mean? Must my HTML5 app be running on a webserver with a domain? IE: http://foo.com/mygame.html? I was hoping to create my game and test in Chrome during development, and then push it to devices such as Android and Windows Phone. But I'm now unsure if even that works as the devices don't run a webserver.
So the question is, is it possible to do it with "pure" HTML5 for the ultimate portablility or do I have to involve Phonegap (for instance) and implement their per device implementation of the Facebook API when I'm targeting mobile devices?

A: You can also use "localhost" as your App Domain in the App Settings, during development.
More threads about this:
Facebook development in localhost
What am I doing wrong in localhost Facebook app development?
How can I add localhost:3000 to Facebook App for development


text:
Q: What does this C code do? I need to know the output of the following c function
bool GC_search_memaddr (void* high_add, void* low_add, void* search_add)
{
    void ** gc_ptr_to_ptr;
    void * gc_temp;
    gc_temp = high_add;
    while( gc_temp > low_add )
    {
        gc_temp = gc_temp - 1;
        gc_ptr_to_ptr = (void**)gc_temp;
        if ((*gc_ptr_to_ptr) == search_add)
            return True;
    }
    return False;
}

In this all 3 of the input functions are pointers. I thought that this was just a simple increment based search function but the problem is that if you change all of them to int the output of the function changes sometimes.
Can anybody tell what exactly is happening here ...

A: Pointer arithmetic is likely your problem.  The line:
gc_temp = gc_temp - 1;

is going to change the value of gc_temp by whatever your compiler decides sizeof(void) is.  If you change the parameters and local variables to int, they will iterate by exactly 1.  Break out your debugger and see what's going on.

A: The variables low_add and high_add contain the start and end addresses of a region of memory. The function searches that region of memory for a pointer that contains the same value that's in search_add. From the function name I'm assuming it's part of some garbage collector.

A: As blastfurnace says, it's searching byte-by-byte for a supplied pointer value.  The int equivalent would be:
bool GC_search_memaddr (void* high_add, void* low_add, int search_add)
{
    int * gc_ptr_to_int;
    void * gc_temp;
    gc_temp = high_add;
    while( gc_temp > low_add )
    {
        gc_temp = gc_temp - 1;
        gc_ptr_to_int = (int *)gc_temp;
        if ((*gc_ptr_to_int) == search_add)
            return True;
    }
    return False;
}

Though, gc_temp should actually be of type char *, and it should be using memcpy() to account for endianness issues, so it should really look like:
bool GC_search_memaddr (void* high_add, void* low_add, void *search_add)
{
    void *gc_ptr;
    char *gc_temp = high_add;

    while (gc_temp > low_add)
    {
        gc_temp--;
        memcpy(&gc_ptr, gc_temp, sizeof gc_ptr);
        if (gc_ptr == search_add)
            return True;
    }
    return False;
}

A: The function seems to determine if the address search_add is between the addresses high_add and low_add. Why this isn't done with pointer subtraction and why there is the ugly cast to void** just to dereference it on the next possible occasion is beyond me.


text:
Q: Routing issues with pgrouting I was using the pgrouting plugin to display the shortestpath. I used the plugin as suggested by underdark to display the shortest path in qgis.
My source node is 283 and my target node is 172. When I used the pgrouting plugin to give me the shortest path I got one as attached in the screenshot.

However, when I queried the database of the graph which was generated by the tool osm2po. I found only one edge which was connected to node 283.
The result of the query is given in the figure below

My question is if you look at the results of the query, the edge is from node 279-283 and is one way as well with 283 being the target. Now since I used qgis to show the shortest path from 283-172. There is no starting from 283 as source. So my assumption was it shouldn't have shown any path. So I was wondering if there are some issues with the pgrouting plugin.
How come it gave me the shortest path when there is no edge with 283 as source? As I have explained there is only one edge connected to 283, but 283 is target and also the edge is one way from source to target.

A: I guess that if only one way(but high reverse_cost value(1000000)) exists,
shortest path(dijkstra) function use the way although it has high reverse cost.
Could you execute following query on phppgadmin for confirmation?.
SELECT route.vertex_id, route.cost AS route_cost, m_2po_4pgr.*
FROM m_2po_4pgr
JOIN (SELECT * FROM shortest_path(
 'SELECT id AS id, source::int4 AS source, target::int4 AS target,
  cost::float8 AS cost ,reverse_cost::float8 AS reverse_cost
  FROM m_2po_4pgr ', 283,172, True, True)) AS route
ON m_2po_4pgr.id= route.edge_id

A: There might be an ambiguity issue with [has_reverse_cost] and [directed] because a directed graph does not need a reverse_cost attribute.


text:
Q: How to make GridLayout responsive? I have a form that I want to be responsive with regard to the width of the window in the following way:

*

*when the width of the window is less than a certain maximumWidth, say 1000px, the form should take up the whole available width.

*when the window is made wider than the maximumWidth, the form should be centered horizontlly with a fixed width of say 900px.
Here is my code:
main.qml
import QtQuick 2.9
import QtQuick.Controls 2.2
import QtQuick.Layouts 1.3

ApplicationWindow {
    id: window
    visible: true
    width: 800 // 1100
    title: "Stack"

    ScrollView {
        anchors.fill: parent

        GridLayout {
            columns: 2

            CVerticalLabel {
                text: "Miscellaneous"
                background: "blue"
                Layout.fillHeight: true
            }

            GridLayout {
                columns: 2

                Text {
                    text: "Company Name"
                    color: "red"
                    font.bold: true
                    font.pointSize: 16
                }

                TextField  {
                    objectName: "company_name"
                    font.bold: true
                    Layout.fillWidth: true
                    implicitHeight: 30
                    implicitWidth: 1000
                }
            }
        }
    }
}

CVerticalLabel.qml
import QtQuick 2.9

Item {
    id: control
    property string text
    property color color: "red"
    property color background: "blue"
    property real bgOpacity: 0.6

    width: 15 * 1.6

    Rectangle {
        anchors.fill: control
        color: control.background
        opacity: control.bgOpacity
    }

    Text {
        color: control.color
        text: control.text
        font.bold: true
        font.pointSize: 10
        width: control.height
        height: control.width
        verticalAlignment: Text.AlignVCenter
        horizontalAlignment: Text.AlignHCenter
        rotation: 90
        y: -height
        transformOrigin: Item.BottomLeft
    }
}

The code produces the following result:

The problem is, that the form is aligned to the left and its size is always fixed, i.e. it does not take into account the different window widths. So the second column is not stretched to fill the rest of the available width.
How to achieve the desired result?

A: Solution
In order to make the GridLayout centered on the page with a maximum width of 900px when the window width exceeds 1000px I would suggest you the following solution:

*

*Add a Page as a parent of your ScrollView:
Page {
    id: page
    anchors.fill: parent

    ScrollView {
        ...
    }
}

*Make the left anchor margin of the GridLayout dynamic by taking into account the width of the bounding rectangle of its children, as well as the width of the Page:
anchors.leftMargin: (page.width - childrenRect.width)/2

Note: This solution is similar to the way Flow is being centered, as discussed here.
Example
Here is an example I have created for you of how your code could be changed in order to implement the proposed solution:
ApplicationWindow {
    id: window
    title: "Stack"
    visible: true
    width: 1400

    Page {
        id: page
        anchors.fill: parent
        property int responsiveWidth: 1000
        property int maximumWidth: 900

        ScrollView {
            anchors.fill: parent

            GridLayout {
                columns: 2

                width: page.width > page.responsiveWidth ? page.maximumWidth : page.width
                anchors.top: parent.top
                anchors.left: parent.left
                anchors.leftMargin: (page.width - childrenRect.width)/2

                CVerticalLabel {
                    text: "Miscellaneous"
                    background: "blue"
                    Layout.fillHeight: true
                }

                GridLayout {
                    columns: 2

                    CTextLabel {
                        text: "Company Name"
                        color: "red"
                    }

                    PanelTextField  {
                        objectName: "company_name"
                        font.bold: true
                        Layout.fillWidth: true
                    }
                }
            }
        }
    }
}

Result
The provided example produces the following results:

*

*for window width @800px

*

*for window width @1100px


text:
Q: How to find all cyclic shifted strings in a given input? This is a coding exercise. Suppose I have to decide if one string is created by a cyclic shift of another. For example: cab is a cyclic shift of abc but cba is not.
Given two strings s1 and s2 we can do that as follows:

if (s1.length != s2.length)
  return false
for(int i = 0; i < s1.length(); i++)
  if ((s1.substring(i) + s1.substring(0, i)).equals(s2))
    return true
return false
Now what if I have an array of strings and want to find all strings that are cyclic shift of one another? For example: ["abc", "xyz", "yzx", "cab", "xxx"] -> ["abc", "cab"], ["xyz", "yzx"], ["xxx"]
It looks like I have to check all pairs of the strings. Is there a "better" (more efficient) way to do that?

A: As a start, you can know if a string s1 is a rotation of a string s2 with a single call to contains(), like this:
public boolean isRotation(String s1, String s2){
    String s2twice = s2+s2;
    return s2twice.contains(s1);
}

Namely, if s1 is "rotation" and s2 is "otationr", the concat gives you "otationrotationr", which contains s1 indeed.
Now, even if we assume this is linear, or close to it (which is not impossible using Rabin-Karp, for instance), you are still left with O(n^2) pair comparisons, which may be too much.
What you could do is build an hashtable where the sorted word is the key, and the posting list contains all the words from your list that, if sorted, give the key (ie. key("bca") and key("cab") both should return "abc"):
private Map<String, List<String>> index;
    /* ... */
public void buildIndex(String[] words){
    for(String word : words){
        String sortedWord = sortWord(word);
        if(!index.containsKey(sortedWord)){
            index.put(sortedWord, new ArrayList<String>());
        }
        index.get(sortedWord).add(word);
    }
}

CAVEAT: The hashtable will contain, for each key, all the words that have exactly the same letters occurring the same amount of times (not just the rotations, ie. "abba" and "baba" will have the same key but isRotation("abba", "baba") will return false).
But once you have built this index, you can significantly reduce the number of pairs you need to consider: if you want all the rotations for "bca" you just need to sort("bca"), look it up in the hashtable, and check (using the isRotation method above, if you want) if the words in the posting list are the result of a rotation or not.

A: If strings are short compared to the number of strings in the list, you can do significantly better by rotating all strings to some normal form (lexicographic minimum, for example). Then sort lexicographically and find runs of the same string. That's O(n log n), I think... neglecting string lengths. Something to try, maybe.

A: Concerning the way to find the pairs in the table, there could be many better way, but what I came up as a first thought is to sort the table and apply the check per adjacent pair.
This is much better and simpler that checking every string with every other string in the table

A: Consider building an automaton for each string against which you wish to test.
Each automaton should have one entry point for each possible character in the string, and transitions for each character, plus an extra transition from the end to the start.
You could improve performance even further if you amalgated the automata.

A: I think a combination of the answers by Patrick87 and savinos would make a fair amount of sense. Specifically, in a Java-esque pseudo-code:
List<String> inputs = ["abc", "xyz", "yzx", "cab", "xxx"];
Map<String,List<String>> uniques = new Map<String,List<String>>();
for(String value : inputs) {
    String normalized = normalize(value);
    if(!uniques.contains(normalized)) {
        unqiues.put(normalized, new List<String>());
    }
    uniques.get(normalized).add(value);
}
// you now have a Map of normalized strings to every string in the input
// that is "equal to" that normalized version

Normalizing the string, as stated by Patrick87 might be best done by picking the rotation of the string that results in the lowest lexographic ordering.
It's worth noting, however, that the "best" algorithm probably relies heavily on the inputs... the number of strings, the length of those string, how many duplicates there are, etc.

A: You can rotate all the strings to a normalized form using Booth's algorithm (https://en.wikipedia.org/wiki/Lexicographically_minimal_string_rotation) in O(s) time, where s is the length of the string.
You can then use the normalized form as a key in a HashMap (where the value is the set of rotations seen in the input). You can populate this HashMap in a single pass over the data. i.e., for each string

*

*calculate the normalized form

*check if the HashMap contains the normalized form as a key - if not insert the empty Set at this key

*add the string to the Set in the HashMap

You then just need to output the values of the HashMap. This makes the total runtime of the algorithm O(n * s) - where n is the number of words and s is the average word length. The total space usage is also O(n * s).


text:
Q: Exercise about finding an orthonormal basis
Consider the vector space $P=\mathbb{R}[x]_{\le3}$ with $*:P\times P \to \mathbb{R}$ defined by $f*g=\int_{-1}^{1}f(t)g(t)dt$.

*

*Prove that * is a symmetric bilinear form positive definite.

*Find an orthonormal basis of (P,*).

I have no problem with the first part, but I'd like to verify if what I did in point 2 is correct.
Consider $B=\{1,x,x^2,x^3\}$, the canonical basis of P, using Gram-Schmidt we find the orthogonal basis $\{1,x, x^2-1/3, x(x^2-3/5)\}$. Hence the orthonormal basis $B'=\{1/\sqrt(2),x\sqrt{3/2}, (x^2-1/3)\sqrt{45/8}, x(x^2-3/5)\sqrt{175/8}\}$.
Is it correct? Thanks in advance


text:
Q: Vue Router push Error: Avoided redundant navigation to current location Is there a way to avoid Error: Avoided redundant navigation to current location. I need to do a pagination, this is the method:
handlePageChange(page: number): void {
  const query = {
    ...this.$route.query,
    page: page.toString(),
  };
  this.$router.push({ name: 'PageName', query });
}

and I keep getting error in the console:
Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "/page-path?page=2".

I tried doing a catch with the router but that does not work. Can someone help me shed some light what am i doing wrong here? :/

A: If it's safe to ignore, and you are using vue-router ^3.4.0, you can do:
import VueRouter from 'vue-router'

const { isNavigationFailure, NavigationFailureType } = VueRouter
...
this.$router.push(fullPath).catch(error => {
  if (!isNavigationFailure(error, NavigationFailureType.duplicated)) {
    throw Error(error)
  }
})

For more details, please refer to Navigation Failures.

A: You can globally handle this problem.
Open your router's index file (index.js) and use this code inside it-
import VueRouter from "vue-router";
Vue.use(VueRouter);

// Handle navigation duplication for router push (Globally)

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((error) => {
  });
};

Try this example - here
Cheers!

A: This is a bit dated, but merging both existing answers for a cleaner, global handling:
import VueRouter from "vue-router";
Vue.use(VueRouter);
const { isNavigationFailure, NavigationFailureType } = VueRouter;

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
    original_push.call(this, location).catch(error => {
        if(!isNavigationFailure(error, NavigationFailureType.duplicated)) {
            throw Error(error)
        }
    })
};


text:
Q: Multivariable Linear Regression using tensorflow I reused TensorFlow code for multivariable linear regression and tried to reduce the cost but the problem is that after some iterations, the cost as well as the values of W and b becomes inf and quickly nan. Can someone please tell me where the problem is.
I have about 100,000 values. I have trimmed it to 10,000 values for testing.
The dataset is here
Here is the code
import numpy as np
import tensorflow as tf

def computeX():

    all_xs = np.loadtxt("test.csv", delimiter=',', skiprows=1, usecols=range(4,260)) #reads the columns except first one

    timestamps = np.loadtxt("test.csv", delimiter=',', skiprows=1, usecols=(0),dtype =str)
    symbols = np.loadtxt("test.csv", delimiter=',', skiprows=1, usecols=(1),dtype =float)
    categories = np.loadtxt("test.csv", delimiter=',', skiprows=1, usecols=(2),dtype =str)

    tempList = []
    BOW = {"M1": 1.0, "M5": 2.0, "M15": 3.0, "M30": 4.0, "H1": 5.0, "H4": 6.0, "D1": 7.0}

    #explode dates and make them features.. 2016/11/1 01:54 becomes [2016, 11, 1, 01, 54]
    for i, v in enumerate(timestamps):
        splitted = v.split()
        dateVal = splitted[0]
        timeVal = splitted[1]
        ar = dateVal.split("/")
        splittedTime = timeVal.split(":")

        ar = ar + splittedTime

        Features = np.asarray(ar)
        Features = Features.astype(float)

        # append symbols

        Features = np.append(Features,symbols[i])

        #append categories from BOW

        Features = np.append(Features, BOW[categories[i]] )
        row = np.append(Features,all_xs[i])
        row = row.tolist()
        tempList.append(row)

    all_xs = np.array(tempList)
    del tempList[:]
    return all_xs

if __name__ == "__main__":
    print ("Starting....")

    learn_rate = 0.5

    all_ys = np.loadtxt("test.csv", delimiter=',', skiprows=1, usecols=3)
#reads only first column

    all_xs = computeX()

    datapoint_size= int(all_xs.shape[0])

    print(datapoint_size)
    x = tf.placeholder(tf.float32, [None, 263], name="x")
    W = tf.Variable(tf.ones([263,1]), name="W")
    b = tf.Variable(tf.ones([1]), name="b")

    product = tf.matmul(x,W)
    y = product + b

    y_ = tf.placeholder(tf.float32, [datapoint_size])

    cost = tf.reduce_mean(tf.square(y_-y))/ (2*datapoint_size)

    train_step = tf.train.GradientDescentOptimizer(learn_rate).minimize(cost)

    sess = tf.Session()

    init = tf.global_variables_initializer()
    sess.run(init)

    batch_size = 10000
    steps =10
    for i in range(steps):
      print("Entering Loop")
      if datapoint_size == batch_size:
         batch_start_idx = 0
      elif datapoint_size < batch_size:
         raise ValueError("datapoint_size: %d, must be greater than batch_size: %d" % (datapoint_size, batch_size))
      else:
         batch_start_idx = (i * batch_size) % (datapoint_size - batch_size)
      batch_end_idx = batch_start_idx + batch_size
      batch_xs = all_xs[batch_start_idx:batch_end_idx]
      batch_ys = all_ys[batch_start_idx:batch_end_idx]
      xs = np.array(batch_xs)
      ys = np.array(batch_ys)

      feed = { x: xs, y_: ys }

      sess.run(train_step, feed_dict=feed)
      print("W: %s" % sess.run(W))
      print("b: %f" % sess.run(b))
      print("cost: %f" % sess.run(cost, feed_dict=feed))

A: Take a look at your data:
id8         id9         id10    id11    id12
1451865600  1451865600  -19.8   87.1    0.5701
1451865600  1451865600  -1.6    3.6     0.57192
1451865600  1451865600  -5.3    23.9    0.57155

You also initialize your weights to one, if you multiply all you input data with one, and add them up, all the 'heavy' columns (id8, id9, etc, columns with large numbers) will push away the data from the smaller columns). Also you have columns which are filled with zeros:
id236   id237   id238   id239   id240
0       0       0       0       0
0       0       0       0       0
0       0       0       0       0

These are all thing which do not play nice together. The large values will result in very high predictions, these will cause the loss to explode and to overflow. Even scaling your learning rate down by a factor of a billion does barely have any effect.
Hence suggestions:

*

*Inspect your data, get rid of all nonsense data (columns filled with zeros)

*Normalize your input data

*Examine at that point the magnitude or the loss function and then try playing with the learning rate.


text:
Q: Is using Kafka as an input source for Flink a performance bottleneck? Flink allows to read from a Kafka topic, is that a performance bottleneck making Flink slower overall?

A: Kafka partitions can scale horizontally to accomodate for higher thoughput.
One Flink consumer thread can only be assigned to one Kafka partition.
So, if you have only 1 Kafka partition, and N+1 Flink executors, then you will have N idle tasks, which could be a bottleneck, sure, but that is a tradeoff of having total-ordering within a Kafka topic, not necessarily a Flink problem.
Otherwise, you would create your Kafka topics with ten to hundreds of partitions, and Flink would be fine to consume it.

A: It depends. If, for example, you have a slow network connection between your Kafka cluster and your Flink cluster, then that will become a performance bottleneck.


text:
Q: #include errors detected based on information provided by the configurationProvider setting I keep getting three errors when I try including a header file that looks like this:
#include <iostream>
#include <"maximum.h"> // *** Header file that is getting the three errors ***

These are the errors I am getting:
#include errors detected. based on information provided by the configurationProvider setting.
cannot open source file ""maximum.h""
'"maximum.h"' file not found

Here, is a link to a solution I tried out. That didn't solve the problem for me. Could anyone help me out? Thanks.

A: You are trying to find file .../"maximum.h" which obviously in not existing.
Use either <maximum.h> which first will search your file inside compiler directories or "maximum.h" which first will search near your current file.


text:
Q: how should I draw Custom button on Navigation Bar I want to draw custom button on Navigation bar.
Can anybody help me.

A: simple
[[UIBarButtonItem alloc] initWithCustomView: customButton];

will work
so something like that:
UIButton *button = [UIButton buttonWithType: UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@"animage.png"]];
[button addTarget:self action:@selector(onClick:) forControlEvents: UIControlEventTouchUpInside];
UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView: button];
[self.navigationItem setLeftBarButtonItem:customItem];

Cheers,
Krzysztof Zabłocki

A: UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithTitle:@"DontWorryAboutThis" style:UIBarButtonItemStylePlain target:self action:@selector(method:)];
[barButton setImage:[UIImage imageNamed:@"animage.png"]];
[self.navigationItem setLeftBarButtonItem:barButton];

A:       UIBarButtonItem *btn=[[UIBarButtonItem alloc] initWithTitle:@"Button" style:UIBarButtonItemStylePlain target:self action:@selector(btnPressed)];
      [self.navigationItem setRightBarButtonItem:btn];


text:
Q: MysQL : How to set default value for empty row? I have 4 tables.
1. Course 2. Semester 3. AssignTeacher 4. Teacher.

 Course has id, name, code.
 Semester has id, name, course_id.
 AssignTeacher has id,course_id,teacher_id.
 Teacher has id, name.

Now I want to find courses.code, courses.name, semesters.name and teachers.name
from the above tables. where teachers.name should come with those teachers who has id in AssignTeacher table. Now with the course table when there is no teacher id with that course instead of showing null value can i set some default value like 'None' in the Query?
Here is Query I have written till now though i wasn't getting what i expected:
SELECT courses.code, courses.name, semesters.name,teachers.name
FROM semesters
JOIN courses on courses.semester_id = semesters.id
JOIN assign_teachers on assign_teachers.course_id=courses.id
JOIN teachers on assign_teachers.id=teachers.id

A: if i understood correctly, change in select list to
COALESCE(teachers.name, 'None')

A: Of course, you should use COALESCE() which replace null's with wanted value :
SELECT courses.code, courses.name, semesters.name,COALESCE(teachers.name,'None') as teacher_name
from semesters join courses on  courses.semester_id = semesters.id
  join assign_teachers on assign_teachers.course_id=courses.id
   join teachers on assign_teachers.id=teachers.id

But that seems weird that you get null values, when there is no teacher.id this record should be filtered since you are using normal joins. I think you should use LEFT join instead :
SELECT courses.code, courses.name, semesters.name,COALESCE(teachers.name,'None') as teacher_name
from semesters join courses on  courses.semester_id = semesters.id
  left join assign_teachers on assign_teachers.course_id=courses.id
   left join teachers on assign_teachers.id=teachers.id


text:
Q: Delphi - Comparing two pathnames when one is UNC and one is drive letter-specified I have a situation where a user can specify two separate pathnames, and I need to check whether one pathname is "inside" the other one.  I can do this if both pathnames are UNC, or both are drive-letter-based, but what if they are mixed?
Can you "normalise" a path such as "C:\Program Files" to "\\[this computer name]\C\Program Files"?  Obviously, I can't go the other way, as a network folder in UNC format may not have a corresponding drive letter mapped to it.

A: Have a look at ExpandUNCFileName function.


text:
Q: How to correctly handle Byte values greater than 127 in Kotlin? Imagine I have a Kotlin program with a variable b of type Byte, into which an external system writes values greater than 127. "External" means that I cannot change the type of the value it returns.
val a:Int = 128
val b:Byte = a.toByte()
Both a.toByte() and b.toInt() return -128.
Imagine I want to get the correct value (128) from the variable b. How can I do it?
In other words: What implementation of magicallyExtractRightValue would make the following test run?
@Test
fun testByteConversion() {
    val a:Int = 128
    val b:Byte = a.toByte()

    System.out.println(a.toByte())
    System.out.println(b.toInt())

    val c:Int = magicallyExtractRightValue(b)

    Assertions.assertThat(c).isEqualTo(128)
}

private fun magicallyExtractRightValue(b: Byte): Int {
    throw UnsupportedOperationException("not implemented")
}

Update 1: This solution suggested by Thilo seems to work.
private fun magicallyExtractRightValue(o: Byte): Int = when {
    (o.toInt() < 0) -> 255 + o.toInt() + 1
    else -> o.toInt()
}

A: With Kotlin 1.3+ you can use unsigned types. e.g. toUByte (Kotlin Playground):
private fun magicallyExtractRightValue(b: Byte): Int {
    return b.toUByte().toInt()
}

or even require using UByte directly instead of Byte (Kotlin Playground):
private fun magicallyExtractRightValue(b: UByte): Int {
    return b.toInt()
}

For releases prior to Kotlin 1.3, I recommend creating an extension function to do this using and:
fun Byte.toPositiveInt() = toInt() and 0xFF

Example usage:
val a: List<Int> = listOf(0, 1, 63, 127, 128, 244, 255)
println("from ints: $a")
val b: List<Byte> = a.map(Int::toByte)
println("to bytes: $b")
val c: List<Int> = b.map(Byte::toPositiveInt)
println("to positive ints: $c")

Example output:
from ints: [0, 1, 63, 127, 128, 244, 255]
to bytes: [0, 1, 63, 127, -128, -12, -1]
to positive ints: [0, 1, 63, 127, 128, 244, 255]

A: Good old printf does what we want:
java.lang.String.format("%02x", byte)


text:
Q: Material UI next simple dialog add new contact I am using the material-ui next branch and using the following example as reference for building a dialog.
https://material-ui-next.com/demos/dialogs/
https://codesandbox.io/s/7rq8nl11x
I wanted to know the best way to let the user enter a new contact as per material guidelines ie how to handle the UI for click of add contact button present in the bottom of the dialog. Would it be to hide this dialog and show a new dialog instead which shows a form letting the user enter a new contact.
I'm mostly looking for suggestions on design.

A: There's a lot of good information on the material design guidelines and best practices for managing components in React.
With that said, a good solution for your situation is to handle all the account management within the one modal. Here's an idea for a structure that's very similar to what Google does:
DialogContainer as the parent component to handle logic and contain the next two components.
AccountList to render each user as well as the 'add account' button.
AccountCreation component that renders the input to add another account.


text:
Q: coldfusion weird extra space I have a function to convert string to number
<cffunction name="convertToNumber" returntype="numeric">
    <cfargument name="separator" required="Yes" type="string" />
    <cfargument name="number" required="Yes" type="string" />

    <cfset LOCAL.arrSeparator = ["comma", "period", "lakh_crore"] />

    <cfif ARGUMENTS.separator eq "comma" or ARGUMENTS.separator eq "lakh_crore">
        <cfif ListLen(ARGUMENTS.number, ".") eq 2>
            <cfset LOCAL.integral = ListFirst(ARGUMENTS.number, ".") />
            <cfset LOCAL.fractional = ListLast(ARGUMENTS.number, ".") />
        <cfelse>
            <cfset LOCAL.integral = ARGUMENTS.number />
            <cfset LOCAL.fractional = "" />
        </cfif>

        <cfset LOCAL.integral = Replace(LOCAL.integral, ",", "", "ALL") />
        <cfset LOCAL.returnValue = LOCAL.integral />

        <cfif Len(Trim(LOCAL.fractional))>
            <cfset LOCAL.returnValue &= "." & LOCAL.fractional />
        </cfif>
    </cfif>

    <cfif ARGUMENTS.separator eq "period">
        <cfif ListLen(ARGUMENTS.number, ",") eq 2>
            <cfset LOCAL.integral = ListFirst(ARGUMENTS.number, ",") />
            <cfset LOCAL.fractional = ListLast(ARGUMENTS.number, ",") />
        <cfelse>
            <cfset LOCAL.integral = ARGUMENTS.number />
            <cfset LOCAL.fractional = "" />
        </cfif>

        <cfset LOCAL.integral = Replace(LOCAL.integral, ".", "", "ALL") />
        <cfset LOCAL.returnValue = LOCAL.integral />

        <cfif Len(Trim(LOCAL.fractional))>
            <cfset LOCAL.returnValue &= "." & LOCAL.fractional />
        </cfif>
    </cfif>

    <cfreturn LOCAL.returnValue />

</cffunction>

<cfset separatorNumber = StructNew() />
<cfset separatorNumber.comma = "1,234,567,890.123456">
<cfset separatorNumber.period = "1.234.567.890,123456">
<cfset separatorNumber.lakh_crore = "1,23,45,67,890.123456">

<cfloop collection="#separatorNumber#" item="separator">

        #separator# :
        <input type="Text" value="#convertToNumber(separator, separatorNumber[separator])#">
        Length : #Len(convertToNumber(separator, separatorNumber[separator]))#

</cfloop>

the length is 17, but in the input text it add extra white space at first char. I really don't know how to remove the extra white space, and when I add ToString(Trim())
<input type="Text" value="#ToString(Trim(convertToNumber(separator, separatorNumber[separator])))#">

it still have extra white space
thank you

A: Have you tried to added output="false" to your function tag?
<cffunction name="convertToNumber" returntype="numeric" output="false">...</cffunction>

Hope that helps.

A: I ran into a similar problem, and what worked for me was putting the value returned from the method into a variable and then outputting the variable instead of the return from the method. I didn't format it at all, but somehow that helped.

A: It's very simple. Put <cfsilent> in your <cffunction>. Need to put <cfsilent> after <cfargument>.
I've wrote about extra space within cffunction in my blog.
<cffunction name="convertToNumber" returntype="numeric">
    <cfargument name="separator" required="Yes" type="string" />
    <cfargument name="number" required="Yes" type="string" />
    <cfsilent>
        <cfset LOCAL.arrSeparator = ["comma", "period", "lakh_crore"] />
        <cfif ARGUMENTS.separator eq "comma" or ARGUMENTS.separator eq "lakh_crore">
            <cfif ListLen(ARGUMENTS.number, ".") eq 2>
                <cfset LOCAL.integral = ListFirst(ARGUMENTS.number, ".") />
                <cfset LOCAL.fractional = ListLast(ARGUMENTS.number, ".") />
            <cfelse>
                <cfset LOCAL.integral = ARGUMENTS.number />
                <cfset LOCAL.fractional = "" />
            </cfif>
            <cfset LOCAL.integral = Replace(LOCAL.integral, ",", "", "ALL") />
            <cfset LOCAL.returnValue = LOCAL.integral />
            <cfif Len(Trim(LOCAL.fractional))>
                <cfset LOCAL.returnValue &= "." & LOCAL.fractional />
            </cfif>
        </cfif>
        <cfif ARGUMENTS.separator eq "period">
            <cfif ListLen(ARGUMENTS.number, ",") eq 2>
                <cfset LOCAL.integral = ListFirst(ARGUMENTS.number, ",") />
                <cfset LOCAL.fractional = ListLast(ARGUMENTS.number, ",") />
            <cfelse>
                <cfset LOCAL.integral = ARGUMENTS.number />
                <cfset LOCAL.fractional = "" />
            </cfif>
            <cfset LOCAL.integral = Replace(LOCAL.integral, ".", "", "ALL") />
            <cfset LOCAL.returnValue = LOCAL.integral />
            <cfif Len(Trim(LOCAL.fractional))>
                <cfset LOCAL.returnValue &= "." & LOCAL.fractional />
            </cfif>
        </cfif>
        <cfreturn LOCAL.returnValue />
    </cfsilent>
</cffunction>

<cfset separatorNumber = StructNew() />
<cfset separatorNumber.comma = "1,234,567,890.123456" />
<cfset separatorNumber.period = "1.234.567.890,123456" />
<cfset separatorNumber.lakh_crore = "1,23,45,67,890.123456" />
<cfoutput>
    <cfloop collection="#separatorNumber#" item="separator">

            #separator# :
            <input type="Text" value="#convertToNumber(separator, separatorNumber[separator])#">
            Length : #Len(convertToNumber(separator, separatorNumber[separator]))#

    </cfloop>
</cfoutput>


text:
Q: Random min 'minValue' can not be greater then 'maxValue' I'm trying to make a small program that will select a random line form a richtextbox and print it out on a label.
I have also tried to make a timer that will display random lines on the label before it stops.
but when I run the program it gives me this error message:

Random min 'minValue'  can not be greater then 'maxValue'

This is my code:
public partial class Form1 : Form
{

    private int ran;
    private int ranP;
    private int max;
    Random rnd = new Random();
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click_1(object sender, EventArgs e)
    {

        int max = richTextBox1.Lines.Count();
        int ranP = rnd.Next(1, max);
        int ran = 0;
        timer1.Enabled = true;
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        label2.Text = "The Winner is: " + richTextBox1.Lines[ranP];
        ran = rnd.Next(1, 11);
        ranP = rnd.Next(1, max);
        if(ran == 11){
            timer1.Enabled = false;
        }
    }
}

The error come on this line in my timer:

ranP = rnd.Next(1, max);

Does anyone know why this happens?

A: In your button1_Click_1 you declare a local variable max which shadows your instance variable this.max. When you use max in the timer1_Tick method it refers to that instance variable which is never assigned to.
Changing the assignment in the button1_Click_1 to
max = richTextBox1.Lines.Count();

should help.


text:
Q: How to delete a rows with list of primary keys in sqlite In SQL:
delete from table where (pk1,pk2) IN (('1',2),('2',3))

What would be the similar syntax in sqlite ?

A: Since Sqlite does not seem to support IN queries with pairs, the most straight forward and readable query you can do is probably (brackets added for readability);
DELETE FROM table WHERE (pk1='1' AND pk2=2) OR (pk1='2' AND pk2=3)

A: One possiblity is to use correlated query:
WITH cte(p1, p2) AS(
  VALUES ('1',2)
  UNION ALL VALUES ('2', 3))         -- add more pairs if needed
DELETE FROM tab
WHERE EXISTS (SELECT 1 FROM cte WHERE pk1 = p1 AND pk2 = p2);

SqlFiddleDemo


text:
Q: C# webservice losing data on return I am programming a client program that calls a webmethod but when I get the return data there are  missing values on some of the fields and objects.
The webmethod in turn is calling a WCF method and in the WCF method the return data is fine. But when it is passing to the webservice the return data is missing.
Is there any way to fix this problem?

This is my client code calling the webservice:
    ReLocationDoc query = new ReLocationDoc();

    query.PerformerSiteId = 1;
    query.PerformerUserId = 1;
    query.FromStatus = 10;
    query.ToStatus = 200;

    ReLocationDoc doc = new ReLocationDoc();

    ServiceReference1.QPSoapClient service = new QPSoapClient();
    try {
        service.GetRelocationAssignment(query, out doc);

        string test = doc.Assignment.Id.ToString();

    } catch(Exception ex) {

        MessageBox.Show(ex.Message);
    }

The webmethod code is here:
        [WebMethod]
        return m_reLocationClient.GetRelocationAssignment(query, out reLocationDoc);
    }

And at last the WCF code:
    public ReLocationResult GetRelocationAssignment(ReLocationDoc query, out ReLocationDoc reLocationDoc) {
        try {
            LOGGER.Trace("Enter GetRelocationAssignment().");

            ReLocationResult result = reLocationCompactServiceClient.GetRelocationAssignment(out reLocationDoc, query);

            if(reLocationDoc.Assignment == null || reLocationDoc.Assignment.CurrentStatus == STATUS_FINISHED) {
                ReLocationDoc newQuery = new ReLocationDoc();
                newQuery.Assignment = new AssignmentDoc();
                newQuery.Assignment.EAN = DateTime.Today.ToString();
                newQuery.PerformerSiteId = QPSITE;
                newQuery.PerformerUserId = QPUSER;
                reLocationDoc.AssignmentStatus = m_settings.ReadyStatus; ;
                result = reLocationCompactServiceClient.CreateReLocationAssignment(out reLocationDoc, newQuery);
            }

            return result;

        } finally {
            LOGGER.Trace("Exit GetRelocationAssignment().");
        }
    }

The GetRelocationAssignment:
    public ReLocationResult GetRelocationAssignment(ReLocationDoc query, out ReLocationDoc reLocationDoc) {
        try {
            LOGGER.Trace("Enter GetRelocationAssignment().");

            ReLocationDoc doc = new ReLocationDoc();
            ReLocationResult result = new ReLocationResult();

            new Database(Connection).Execute(delegate(DBDataContext db) {

                User user = GetVerifiedUser(db, query, MODULE_ID);
                SiteModule siteModule = SiteModule.Get(db, query.PerformerSiteId, MODULE_ID);

                Status status = Status.Get(db, query.FromStatus, query.ToStatus, 0);
                Status startStatus = Status.Get(db, query.FromStatus, 0);
                Status endStatus = Status.Get(db, query.ToStatus, 0);

                IQueryable<Assignment> assignments = Assignment.GetAssignmentsWithEndStatus(db, siteModule, endStatus);
                assignments = Assignment.FilterAssignmentStartStatus(assignments, startStatus);

                foreach(Assignment assignment in assignments) {

                    LOGGER.Debug("Handling assignment: " + assignment.Id);

                    result.Status = true;
                    AssignmentDoc assignmentDoc = FillAssignmentDoc(assignment);
                    //ReLocationDoc doc = new ReLocationDoc();

                    AssignmentStatus sts = assignment.AssignmentStatus.OrderByDescending(ass => ass.Id).First();
                    assignmentDoc.CurrentStatus = sts.Status.Zone;

                    Status currentStatus = sts.Status;

                    IList<Item> items = assignment.Items.ToList();
                    IList<ItemDoc> itemDocs = new List<ItemDoc>();
                    foreach(Item item in items) {

                        ItemDoc itemDoc = FillItemDoc(item);

                        ItemDetail itemDetail;
                        if(ItemDetail.TryGet(db, item.Id, out itemDetail)) {
                            ItemDetailDoc itemDetailDoc = FillItemDetailDoc(itemDetail);
                            itemDoc.Details = new ItemDetailDoc[1];

                            Event eEvent = null;
                            if(Event.GetEvent(db, itemDetail, currentStatus, out eEvent)) {
                                EventDoc eventDoc = FillEventDoc(eEvent);
                                itemDetailDoc.Events = new EventDoc[1];

                                if(eEvent.LocationId.HasValue) {
                                    Location location = null;
                                    if(Location.TryGet(db, eEvent.LocationId.Value, out location)) {
                                        eventDoc.Location = new LocationDoc();
                                        eventDoc.Location = FillLocationDoc(location, db);
                                    }
                                }
                                itemDetailDoc.Events[0] = eventDoc;
                            }
                            itemDoc.Details[0] = itemDetailDoc;
                        }
                        itemDocs.Add(itemDoc);
                    }
                    assignmentDoc.Items = itemDocs.ToArray();
                    doc.Assignment = assignmentDoc;
                }

            }, delegate(Exception e) {
                result.Message = e.Message;
            });

            reLocationDoc = doc;
            return result;

        } finally {
            LOGGER.Trace("Exit GetRelocationAssignment().");
        }
    }

In all this code the return data is fine. It is loosing data only when passing to the webmetod.
Enter code here.

A: Make surethe XML tags are being accessed with the same casing at either end.  if the casing is not the same then the value won't be read.

A: Also, the ordering of the XML tags in the message makes difference - I had a similar problem about maybe two years ago, and in that case parameter values were dissappearing during transmission because the sending part ordered the tags differently than what was defined in the schema.

A: You should check it all message are sending back from your webservice. Call your webservice manually and check its response.

*

*If all data is there, probably your webservice reference is outdated; update it by right-clicking your webservice reference and choose "Update"

*If your data don't came back, your problem is probably related to webservice code. You should check your serialization code (if any) again, and make sure all returned types are [Serializable]. You should check if all return types are public as it's mandatory for serialization.

As noted per John Saunders, [Serializable] isn't used by XmlSerializer.


text:
Q: How to get the interval of a geolocation (lat long) ? I am developing an android application, and in my database of dadaos are registered specific points using geo location, as the scope of the application is global, in some time it will become unviable to load so much information of the cell phone, I would only load the geolocation interval, For example, just load the range of the city where the user is, how could this be done? I thought about doing a WHERE with the location range, but I do not think that's possible.
Has anyone ever had a similar situation that could share the solution?


text:
Q: How to create a gridview with 4 level grouping In my sharepoint application, i must to create a view with 4 level grouping in a page
+- Level 1
  +- Level 2
    +- Level 3
       +- Level 4

Help me. Can i use SPGridview or ASP Gridview.

A: *

*If the 4 levels are fixed you can create a nested gridview control. Editable nested gridview (All in one)

*You would just drop gridviews inside gridviews on a template field column

*Then, just use FindControl on RowDataBoundEvent of your parent gridview, find the nested gridview control if true, then DataBind it with your datasource

*If you are talking about N-levels this may help you further


text:
Q: MYSQL - Generate Report with Filled Gaps How would I generate a report with filled gaps that shows zero results for date as well as time slots?
Here's what I have so far that works for DATE :
MYSQL
SELECT calendar.datefield AS DATE,
       IFNULL(COUNT(digital_lead.id),0) AS leads
FROM digital_lead RIGHT JOIN calendar ON (DATE(digital_lead.received) = calendar.datefield)
WHERE (calendar.datefield BETWEEN (SELECT MIN(DATE('2014-09-01')) FROM digital_lead) AND (SELECT MAX(DATE(received)) FROM digital_lead))
GROUP BY DATE

Which produces the following table:
 DATE         LEADS
'2014-11-08', '0'
'2014-11-09', '0'
'2014-11-10', '0'
'2014-11-11', '0'
'2014-11-12', '524'
'2014-11-13', '934'
'2014-11-14', '524'

So this produces results for every day even those that are not accounted for by the TIMESTAMP field received.
The received field is a TIMESTAMP field in the format of 'YYYY-MM-DD HH:MM:SS'.
I would like to be able to generate a similar report showing the breakdown by DATE and TIME - showing the zero results for both DATE and TIME slots.
I have created a utility table named clockcontaining all of the hours of the day.
See SQL fiddle for scehema details:
SQL FIDDLE
I was thinking I could join the clock table onto digital_lead as I have done with calendar, however, this produces a single row with one time and date 2014-11-13 00:00:00.
Can anybody provide a solution?
EDIT
Just to clarify I would like to JOIN the clock table to the MYSQL statment given above and create the following output :
     DATE           HOURS   LEADS
    2014-11-06      00:00:00    0'
                    01:00:00    0'
                    02:00:00    0'
                    03:00:00    4

    2014-11-07      00:00:00    0'
                    01:00:00    2
                    02:00:00    1

The dates for the calendar table are generated using the following PROCEDURE:
DELIMITER |
CREATE PROCEDURE fill_calendar(start_date DATE, end_date DATE)
BEGIN
  DECLARE crt_date DATE;
  SET crt_date=start_date;
  WHILE crt_date < end_date DO
    INSERT INTO calendar VALUES(crt_date);
    SET crt_date = ADDDATE(crt_date, INTERVAL 1 DAY);
  END WHILE;
END |
DELIMITER ;

Which is called as follows CALL fill_calendar('2008-01-01', '2011-12-31');


text:
Q: Rename the files' names I'd like to change the files whose extension are '.test.txt' into '.txt'.
As my codes as below, it cannot work cause invalid syntax happened to the place of 'if'.
Could you please figure out it?
Thank you so much.
import sys
import os

path = "Dir"
for(dirpath,dirnames,files)in os.walk(path):
   for filename in files:
           filepath = os.path.join(dirpath,filename)
    if '.test.txt' in filename:
           newfilename = filename.replace('.test.txt','.txt')
           os.rename(filename,newfilename)

A: this should work...
import sys
import os

path = r"Dir"
for dirpath,dirnames,files in os.walk(path):
    for filename in files:
        filepath = os.path.join(dirpath,filename)
        if '.test.txt' in filename:
            newfilename = filename.replace('.test.txt','.txt')
            newfilepath = os.path.join(dirpath, newfilename)
            os.rename(filepath, newfilepath)

you did not define the new file path, in renaming action you have to supply the full file path, os.rename(src_path, dest_path)


text:
Q: How to import ssl wildcard cert from Apache to Tomcat I currently have a wildcard certificate from Comodo that is currently used for Apache. I need to use this for Confluence, running on Tomcat. I tried following their instructions, but realized that I need to import the current cert using the keytool command to get it to the right format.
I currently have the following files from Comodo:
filename.ca-bundle
filename.crt
filename.key

Has anyone been able to convert the certificate to work on Tomcat and if so, can you point to the documentation used? Thanks!

A: I figured it out. Need to convert to PKCS12, then to JKS.
To convert to PKCS12:
openssl pkcs12 -export -in <filename.crt> -inkey <filename.key> -out <filename.pkcs12> -name tomcat -CAfile <filename.ca-bundle> -caname root

Make note of the password entered as you will need it for the next step.
To convert from PKCS12 to JKS:
./keytool -importkeystore -deststorepass <some_password> -destkeypass <some_password> -destkeystore <filename.jks> -srckeystore <filename.pkcs12> -srcstoretype PKCS12 -srcstorepass <password_entered_previously> -alias tomcat


text:
Q: Is it possible to change the Column Heading of the 'Note Text' field in a grid My client wants to see the Notes in a Grid column.
I can add the Note Text field of a record to a data grid - but our customer wants the column heading to read 'Internal Comment' instead of 'Note Text'
I have tried a DAC Extension on the PX.Data.Note but this does not work.
I am not sure how to use cache attached for this- because the Note_Text field seems to be added by the PXNoteAttribute ??
I have also tried this in the RowSelected event of the grid view - but it does not work:
PXUIFieldAttribute.SetDisplayName<Note.noteText>(this.Caches[typeof(Note)], Messages.InternalComment);
Any help appreciated


text:
Q: Testflight : "You are currently not testing any apps" error I have submitted my apps to test flight and able to download it using testflightapp.com. However, when I access it through the testflight app itself, it says "You are currently not testing any app"?
I have checked the following link but it's not helpful
http://help.testflightapp.com/customer/portal/articles/829653-i-don-t-see-any-apps-after-connecting-my-device-to-my-account-

A: I guess you donwloaded the Apple Testfligt App. It's different than the system you are using. You need to access the testflightapp-website with your Ipad/Iphone. Have a look in your emails. There should be a Testflight link. Open it with your iOS device and it should work. It will reate an icon on your home-screen which looks like an App but is just the link to testflightapp.com

A: Other tip, always open your TestFlight emails with the mail default app from the iPad/iPhone or Safari.
I was using gmail app to open the mail but it was failing


text:
Q: mysql auto adjusting max connections values I have set max connections to around 2000 in my.cnf file.
max_connections=2048

I have upgraded to 5.5.20 and now I see the following line in the error log.
120201 19:40:24 [Warning] Changed limits: max_open_files: 1024  max_connections: 214  table_cache: 400

Why does mysql changed the max connections value to 214 ?
# mysqladmin variables | grep max_connections
| max_connections | 214

Soft and hard open files restricted by OS is 1024
# ulimit -Sa | grep "open files"
open files                      (-n) 1024

# ulimit -Ha | grep "open files"
open files                      (-n) 1024

The number of actually used max connections:
# mysql -e"show status like '%used_connections%'"
+----------------------+-------+
| Variable_name        | Value |
+----------------------+-------+
| Max_used_connections | 95     |
+----------------------+-------+

A: It seems OK to me. You cannot have max_connections larger than that, because you open_files_limit is too low. For every connection MySQL opens several files. Take a look here.
So, you will have to increase open files limit on your OS, and afterwards, you can put higher max_connections value.

A: This seems to be the same problem that I answered in stackoverflow here, although I was using CentOS 7 & MySQL 5.6.26
You need to up your open files limit both for the mysql user (in limits.conf) and for the mysql service (in the mysql.service file)
append these two lines to /etc/security/limits.conf
mysql hard nofile 65535
mysql soft nofile 65535

append this line to /usr/lib/systemd/system/mysqld.service (in the [service] section)
LimitNOFILE=65535

then finally reboot and check that those error messages have disappeared from your mysql error log.

A: This appears to be some bug in the new mysqld. I had the same problem. Setting max_connections to 700 worked, but if I set it to 900, it was reset to 214 during startup. If this was a purposeful change, then it would have lowered it to 700 or something similar, the value 214 doesn't make sense.
Anyway, upping the descriptor limit with ulimit -n fixes the problem.


text:
Q: Xcode 4: setting NSZombieEnabled environment variable for all projects? Setting NSZombieEnabled = YES in the Environment variables is very useful to debug BAD MEMORY ACCESS issues.
However I need to set it for all projects. I was wondering if I can just set it in Xcode preferences. (xCode 4)
thanks

A: Have a look at following uris:
Setting environment variables for user processes: http://developer.apple.com/library/mac/#qa/qa1067/_index.html
Runtime Configuration Guide#Environment Variables: http://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/EnvironmentVars.html
Note: you need to logout/login to make it effective.


text:
Q: Freeing memory allocated to a 2-dimensional vector I have the following 2 dimension vector:
std::vector<std::vector<int>> m_scoreVector;

I try the following code to free the allocated memory. But, it does not work. Just a small portion of memory will be releases:
for (int k = 0; k < m_scoreVector.size(); ++k){
    std::vector<int>().swap(m_scoreVector[k]);
    m_scoreVector[k].shrink_to_fit();
    m_scoreVector[k].clear();
}

std::vector<std::vector<int>>().swap(m_scoreVector);
m_scoreVector.shrink_to_fit();
m_scoreVector.clear();

I am new to memory management. Please let me know how should I free the allocated memory for this vector.
Thanks.

A: Vectors manage the memory for you. They will free the memory when they go out of scope. In general, if you don't allocate memory with new or malloc, you don't need to worry about freeing it either.

A: swap() and shrink_to_fit() are two ways to free vector memory,you can not use it together
try this code:
for (int k = 0; k < m_scoreVector.size(); ++k){
    m_scoreVector[k].clear();
    m_scoreVector[k].shrink_to_fit();
}
m_scoreVector.clear();
m_scoreVector.shrink_to_fit();


text:
Q: Disabling "MyApp has stopped working" dialog When an application crashes on Windows Server 2008 SP1, I get this message box:

MyApp has stopped working
Windows is searching for a solution...

How can I prevent this message box from appearing?
Update: What I really need is to make no dialog appear. I have formulated my real intent in another question.

A: To completely disable this message box, set the registry value (HKLM or HKCU)\Software\Microsoft\Windows\Windows Error Reporting\DontShowUI to 1.
http://msdn.microsoft.com/en-us/library/bb513638%28VS.85%29.aspx

A: Do you mean how can you stop the application from crashing or how can you stop the message from displaying when it does?
If the former, then without any information about the application we're not going to be able to help.  The latter I believe can only be dealt withby gracefully handling the error within the application code AFAIK.

A: I think this is controlled by "windows error reporting service", at least, in Vista. It might be called something else in 2008


text:
Q: Mongo count query taking long time though index is being used The following count query is taking lot more time than expected though index is being used and keysExamined , docsExamined are also less
query = {'indxed_field': 'x',
 'a': 'test',
 'b': {'$ne': True},
 'c': {'$gte': 100},
 'd': 2}

the query time is varying from 10-30 secs for different values mentioned there.Following is the explain output of same query with find (to get explain)
    {u'$clusterTime': {u'clusterTime': Timestamp(1554365186, 14),
      u'signature': {u'hash': Binary('xxxxxxxxxxxxxx', 0),
       u'keyId': 0L}},
     u'executionStats': {u'allPlansExecution': [],
      u'executionStages': {u'advanced': 16917,
       u'alreadyHasObj': 0,
       u'docsExamined': 26218,
       u'executionTimeMillisEstimate': 11263,
       u'filter': {u'$and': [{u'a': {u'$eq': u'test'}},
         {u'b': {u'$eq': 2}},
         {u'c': {u'$gte': 100}},
         {u'$nor': [{u'd': {u'$eq': True}}]}]},
       u'inputStage': {u'advanced': 26218,
        u'direction': u'forward',
        u'dupsDropped': 0,
        u'dupsTested': 0,
        u'executionTimeMillisEstimate': 40,
        u'indexBounds': {u'indxed_field': [u'["x", "y"]']},
        u'indexName': u'indxed_field_1',
        u'indexVersion': 1,
        u'invalidates': 0,
        u'isEOF': 1,
        u'isMultiKey': False,
        u'isPartial': False,
        u'isSparse': False,
        u'isUnique': False,
        u'keyPattern': {u'indxed_field': 1},
        u'keysExamined': 26218,
        u'multiKeyPaths': {u'indxed_field': []},
        u'nReturned': 26218,
        u'needTime': 0,
        u'needYield': 0,
        u'restoreState': 567,
        u'saveState': 567,
        u'seeks': 1,
        u'seenInvalidated': 0,
        u'stage': u'IXSCAN',
        u'works': 26219},
       u'invalidates': 0,
       u'isEOF': 1,
       u'nReturned': 16917,
       u'needTime': 9301,
       u'needYield': 0,
       u'restoreState': 567,
       u'saveState': 567,
       u'stage': u'FETCH',
       u'works': 26219},
      u'executionSuccess': True,
      u'executionTimeMillis': 11271,
      u'nReturned': 16917,
      u'totalDocsExamined': 26218,
      u'totalKeysExamined': 26218},
     u'ok': 1.0,
     u'operationTime': Timestamp(1554365186, 14),
     u'queryPlanner': {u'indexFilterSet': False,
      u'namespace': u'xxxxxxxxxxxx',
      u'parsedQuery': {u'$and': [{u'indxed_field': {u'$eq': u'x'}},
        {u'a': {u'$eq': u'test'}},
        {u'b': {u'$eq': 2}},
        {u'c': {u'$gte': 100}},
        {u'$nor': [{u'd': {u'$eq': True}}]}]},
      u'plannerVersion': 1,
      u'rejectedPlans': [],
      u'winningPlan': {u'filter': {u'$and': [{u'a': {u'$eq': u'test'}},
         {u'b': {u'$eq': 2}},
         {u'c': {u'$gte': 100}},
         {u'$nor': [{u'd': {u'$eq': True}}]}]},
       u'inputStage': {u'direction': u'forward',
        u'indexBounds': {u'indxed_field': [u'["x", "y"]']},
        u'indexName': u'indxed_field_1',
        u'indexVersion': 1,
        u'isMultiKey': False,
        u'isPartial':

 False,
    u'isSparse': False,
    u'isUnique': False,
    u'keyPattern': {u'indxed_field': 1},
    u'multiKeyPaths': {u'indxed_field': []},
    u'stage': u'IXSCAN'},
   u'stage': u'FETCH'}},
 u'serverInfo': {u'gitVersion': u'xxxxxxxxxxxxxxxxxxxxxxxx',
  u'host': u'xxxxxxxxxxxxxxxxxxxxx',
  u'port': 27017,
  u'version': u'x.x.x'}}

And I did a count query in one shell and collected the db.currentOp() output in another shell, that is mentioned below
{
    "inprog" : [
        {
            "host" : "xxxxxxxxxx",
            "desc" : "conn69767",
            "connectionId" : 69767,
            "client" : "127.0.0.1:34876",
            "appName" : "MongoDB Shell",
            "clientMetadata" : {
                "application" : {
                    "name" : "MongoDB Shell"
                },
                "driver" : {
                    "name" : "MongoDB Internal Client",
                    "version" : "4.0.2"
                },
                "os" : {
                    "type" : "Linux",
                    "name" : "Ubuntu",
                    "architecture" : "x86_64",
                    "version" : "16.04"
                }
            },
            "active" : true,
            "currentOpTime" : "2019-04-05T11:56:58.102+0000",
            "opid" : 13776192,
            "lsid" : {
                "id" : UUID("xxxxxxxxxxxx"),
                "uid" : BinData(0,"xxxxxxxxx")
            },
            "secs_running" : NumberLong(5),
            "microsecs_running" : NumberLong(5141567),
            "op" : "command",
            "ns" : "my_collection",
            "command" : {
                "count" : "my_collection",
                "query" : {
                    "indxed_field" : "x",
                    "a" : "test",
                    "b" : {
                        "$ne" : true
                    },
                    "c" : {
                        "$gte" : 190
                    },
                    "d" : 2,
                    "is_deleted" : {
                        "$ne" : true
                    }
                },
                "fields" : {

                },
                "lsid" : {
                    "id" : UUID("xxxxxxxxxxx")
                },
                "$clusterTime" : {
                    "clusterTime" : Timestamp(1554465406, 5),
                    "signature" : {
                        "hash" : BinData(0,"xxxxxxxxx"),
                        "keyId" : NumberLong(0)
                    }
                },
                "$readPreference" : {
                    "mode" : "secondaryPreferred"
                },
                "$db" : "mydb"
            },
            "planSummary" : "IXSCAN { indxed_field: 1 }",
            "numYields" : 260,
            "locks" : {
                "Global" : "r",
                "Database" : "r",
                "Collection" : "r"
            },
            "waitingForLock" : false,
            "lockStats" : {
                "Global" : {
                    "acquireCount" : {
                        "r" : NumberLong(261)
                    }
                },
                "Database" : {
                    "acquireCount" : {
                        "r" : NumberLong(261)
                    }
                },
                "Collection" : {
                    "acquireCount" : {
                        "r" : NumberLong(261)
                    }
                }
            }
        }
    ],
    "ok" : 1,
    "operationTime" : Timestamp(1554465418, 1),
    "$clusterTime" : {
        "clusterTime" : Timestamp(1554465418, 1),
        "signature" : {
            "hash" : BinData(0,"xxxxxxxx"),
            "keyId" : NumberLong(0)
        }
    }
}

I was bit unclear at lockStats section. Any Ideas why the query is taking more time.

A:
Mongo count query taking long time though index is being used

As per MongoDB documentation here To return information on query plans and execution statistics of the query plans, MongoDB provides:

*

*the db.collection.explain()
method,

*the
cursor.explain() method, and

*the
explain command.

The explain results present the query plans as a tree of stages.
"winningPlan" : {
   "stage" : <STAGE1>,
   ...
   "inputStage" : {
      "stage" : <STAGE2>,
      ...
      "inputStage" : {
         "stage" : <STAGE3>,
         ...
      }
   }
},

Each stage passes its results (i.e. documents or index keys) to the parent node. The leaf nodes access the collection or the indices. The internal nodes manipulate the documents or the index keys that result from the child nodes. The root node is the final stage from which MongoDB derives the result set.
Stages are descriptive of the operation; e.g.

*

*COLLSCAN for a collection scan

*IXSCAN for scanning index keys

*FETCH for retrieving documents

*SHARD_MERGE for merging results from shards

*SHARDING_FILTER for filtering out orphan documents from shards

explain.executionStats.executionStages.inputStage.keysExamined
For query execution stages that scan an index (e.g. IXSCAN), keysExamined is the total number of in-bounds and out-of-bounds keys that are examined in the process of the index scan. If the index scan consists of a single contiguous range of keys, only in-bounds keys need to be examined. If the index bounds consists of several key ranges, the index scan execution process may examine out-of-bounds keys in order to skip from the end of one range to the beginning of the next.
Consider the following example, where there is an index of field x and the collection contains 100 documents with x values 1 through 100:
db.keys.find( { x : { $in : [ 3, 4, 50, 74, 75, 90 ] } } ).explain( "executionStats" )

The query will scan keys 3 and 4. It will then scan the key 5, detect that it is out-of-bounds, and skip to the next key 50.
Continuing this process, the query scans keys 3, 4, 5, 50, 51, 74, 75, 76, 90, and 91. Keys 5, 51, 76, and 91 are out-of-bounds keys that are still examined. The value of keysExamined is 10.
Note: New in version 3.4: For index scan (IXSCAN) stages only. The number of times that we had to seek the index cursor to a new position in order to complete the index scan.
executionStats
The returned executionStats information details the execution of the winning plan. In order to include executionStats in the results, you must run the explain in either:

*

*executionStats
or

*allPlansExecution
verbosity mode. Use allPlansExecution mode to include partial
execution data captured during plan
selection.

For unsharded collections, explain returns the following executionStats information:
"executionStats" : {
   "executionSuccess" : <boolean>,
   "nReturned" : <int>,
   "executionTimeMillis" : <int>,
   "totalKeysExamined" : <int>,
   "totalDocsExamined" : <int>,
   "executionStages" : {
      "stage" : <STAGE1>
      "nReturned" : <int>,
      "executionTimeMillisEstimate" : <int>,
      "works" : <int>,
      "advanced" : <int>,
      "needTime" : <int>,
      "needYield" : <int>,
      "saveState" : <int>,
      "restoreState" : <int>,
      "isEOF" : <boolean>,
      ...
      "inputStage" : {
         "stage" : <STAGE2>,
         "nReturned" : <int>,
         "executionTimeMillisEstimate" : <int>,
         ...
         "inputStage" : {
            ...
         }
      }
   },
   "allPlansExecution" : [
      {
         "nReturned" : <int>,
         "executionTimeMillisEstimate" : <int>,
         "totalKeysExamined" : <int>,
         "totalDocsExamined" :<int>,
         "executionStages" : {
            "stage" : <STAGEA>,
            "nReturned" : <int>,
            "executionTimeMillisEstimate" : <int>,
            ...
            "inputStage" : {
               "stage" : <STAGEB>,
               ...
               "inputStage" : {
                 ...
               }
            }
         }
      },
      ...
   ]
}

When an index covers a query, MongoDB can both match the query conditions and return the results using only the index keys; i.e. MongoDB does not need to examine documents from the collection to return the results.
When an index covers a query, the explain result has an IXSCAN stage that is not a descendant of a FETCH stage, and in the  executionStats, the totalDocsExamined is 0.

A: 'nReturned': 16917
'totalDocsExamined': 26218
'totalKeysExamined': 26218

26218 records are filtered using the index key, but the final result returns only 16917. In this case, add few more fields to your index as shown below
{ indxed_field_1 : 1, 'a' : 1, 'b' : 1, 'd': 1, c: 1 } --> This will really improve your performance.

Also, instead of using 'b': {'$ne': True}, use 'b': Fasle. $ne is always is resource consuming operation.
So your final query will look like below.
query = {'indxed_field': 'x',
 'a': 'test',
 'b': False,
 'c': {'$gte': 100},
 'd': 2}

Additional Notes:
If you feel you don't want to include all the fields in the index, the below combination also may improve performance.
{ indxed_field_1 : 1, c: 1 }


text: Q: Interactive PDF using iText doesn't work on mobile browsers I have created a Interactive PDF using iText libraries in Java. The PDF uses TextFields, DataGrids, buttons, etc. The PDF works fine on Windows 7, Chrome, Safari but doesn't work on mobile browser or other PDF readers on mobile. Is there any alternative i can do this?


text:
Q: SVR's Predict method in scikit-learn predicting only one number for the test set I am new to the world of machine learning in python and I have currently a lot of questions regarding the algorithms itself and the code.
So I have developed a python script that takes in time series data of a stock (timestamps and the Adj. Close). I pre-processed it by taking the log of the Adj. Close and normalize it using the min max approach and split the timestamps and Adj. Close into train and test set (90/10 split going forward). The data I am using is of 891 trading days.
I then apply grid search technique on the SVR to fit the train data of timestamps and Adj. Close.
svr = SVR(kernel='rbf', tol=0.001, C=1.0, shrinking=True, cache_size=200, verbose=False, max_iter=-1)

then the parameters to hunt for is gamma and epsilon.
grs = GridSearchCV(svr, param_grid , n_jobs=1, iid=False, cv=StratifiedKFold(train_y, shuffle=False), verbose=0)

fit_results = grs.fit(train_X, train_y)

par_found = fit_results.best_params_

svr = SVR(kernel='rbf', gamma = par_found['gamma'], tol=0.001, C=1.0, epsilon = par_found['epsilon'], shrinking=True, cache_size=200, verbose=False, max_iter=-1)

final_fit = svr.fit(train_X, train_y)

pred = svr.predict(test_X)

but when I print pred, I get an array where all the elements are a single number with an array length equal to the length of the test_X.
I feel like regression engine is over fitting the data but I am not sure. Also, what feature is best suited to use as X_data? I think that using timestamps is not a best way of doing things.
Also, Is there any good literature on understanding the concept and math behind Support vector regression on financial time series?
Is there any better regression technique than SVR for regressing time series?
Thanks. Your help will be greatly appreciated.


text:
Q: Input of in-memory geometry object to Dissolve tool in ArcPy script throws Error 000732? In an arcpy script, I run a Union on a list of geometry objects.  The output is set to an empty geometry object.  The Union runs fine.  What I am trying to do is then feed that output into the Dissolve tool.  No matter how I format the input, I get the following error:
Parameters are not valid.
ERROR 000732: Input Features: Dataset in_memory\f8537CACB_AB51_4BDC_B8E7_0895F11E6AF0 does not exist or is not supported
ESRI help files indicate that tools set to output to an empty geometry object return a list of geometry objects.  The output from the Union tool gives <Geometry object at 0x26d25910[0x27397068]> when queried with repr().  I have tried putting the Union result directly into the Dissolve tool and likewise the 0 index item from the result, seeing as it supposed to be a list.  Both result in an error, the latter saying that a geometry object is not indexable.  Here is a code snippet:
if len(lstHSGeoms) > 1:
            #Union geometries into one geometry
            lstHSUnionGeom = arcpy.Geometry()
            arcpy.Union_analysis(lstHSGeoms, lstHSUnionGeom, "ONLY_FID")
            arcpy.AddMessage('          lstHSUnionGeom:  %s' % repr(lstHSUnionGeom))
            lstHSOneGeom = arcpy.Geometry()
            arcpy.Dissolve_management(lstHSUnionGeom,lstHSOneGeom, None, None, "SINGLE_PART")
            hsOneGeom = lstHSOneGeom[0]

The list lstHSGeoms is a Python list of polygon geometries, which have checked out as valid.  The Union runs, but the Dissovle doesn't.  I'm stymied.  BTW, I tried using an empty string for the fourth parameter of Dissolve (seeing that it is supposed to be a string type), but it didn't make a difference.

A: Setting the output of a geoprocessing tool to an emtpy arcpy.geometry object is not the standard method for using in-memory workspaces. Instead, you want to set the output of the Union to a string variable that references the "file name" of the in-memory feature dataset, almost exactly as if you were using a shapefile. The only difference is that instead of setting your variable to C:\temp\lstHSUnionGeom.shp you would use in_memory\lstHSUnionGeom. Here's the updated code:
if len(lstHSGeoms) > 1:
            #Union geometries into one geometry
            lstHSUnionGeom = "in_memory\\lstHSUnionGeom" #Two slashes required due to escape character
            arcpy.Union_analysis(lstHSGeoms, lstHSUnionGeom, "ONLY_FID")
            arcpy.AddMessage('          lstHSUnionGeom:  %s' % repr(lstHSUnionGeom))
            lstHSOneGeom = "in_memory\\lstHSOneGeom" #Two slashes required due to escape character
            arcpy.Dissolve_management(lstHSUnionGeom,lstHSOneGeom, None, None, "SINGLE_PART")