Q: How to empty/flush Windows READ disk cache in C#? If I am trying to determine the read speed of a drive, I can code a routine to write files to a filesystem and then read those files back. Unfortunately, this doesn't give an accurate read speed because Windows does disk read caching.
Is there a way to flush the disk read cache of a drive in C# / .Net (or perhaps with Win32 API calls) so that I can read the files directly from the drive without them being cached?

A: Why DIY?
If you only need to determine drive speed and not really interested in learning how to flush I/O buffers from .NET, you may just use DiskSpd utility from http://research.microsoft.com/barc/Sequential_IO/. It has random/sequential modes with and without buffer flushing.
The page also has some I/O related research reports you might find useful.

A: const int FILE_FLAG_NO_BUFFERING = 0x20000000;
return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,64 * 1024,
(FileOptions)FILE_FLAG_NO_BUFFERING | FileOptions.Asynchronous
& FileOptions.SequentialScan);

A: Constantin: Thanks! That link has a command-line EXE which does the testing I was looking for.
I also found a link off that page to a more interesting article (in Word and PDF) on this page: Sequential File Programming Patterns and Performance with .NET
In this article, it talks about Un-buffered File Performance (iow, no read/write caching -- just raw disk performance.)
Quoted directly from the article:

There is no simple way to disable
  FileStream buffering in the V2 .NET
  framework. One must invoke the Windows
  file system directly to obtain an
  un-buffered file handle and then
  ‘wrap’ the result in a FileStream as
  follows in C#:

    [DllImport("kernel32", SetLastError=true)]
    static extern unsafe SafeFileHandle CreateFile(
        string FileName,           // file name
        uint DesiredAccess,        // access mode
        uint ShareMode,            // share mode
        IntPtr SecurityAttributes, // Security Attr
        uint CreationDisposition,  // how to create
        uint FlagsAndAttributes,   // file attributes
        SafeFileHandle  hTemplate // template file
        );

    SafeFileHandle handle = CreateFile(FileName,
                            FileAccess.Read,
                            FileShare.None,
                            IntPtr.Zero,
                            FileMode.Open,
                             FILE_FLAG_NO_BUFFERING,
                            null);

    FileStream stream = new FileStream(handle,
                    FileAccess.Read,
                    true,
                    4096);

Calling CreateFile() with the
  FILE_FLAG_NO_BUFFERING flag tells the
  file system to bypass all software
  memory caching for the file. The
  ‘true’ value passed as the third
  argument to the FileStream constructor
  indicates that the stream should take
  ownership of the file handle, meaning
  that the file handle will
  automatically be closed when the
  stream is closed.  After this
  hocus-pocus, the un-buffered file
  stream is read and written in the same
  way as any other.

A: Response of Fix was almost right and better than PInvoke.
But it has bugs and doesn't works...
To open up File w/o caching one needs to do following:
const FileOptions FileFlagNoBuffering = (FileOptions)0x20000000;

FileStream file = new FileStream(fileName, fileMode, fileAccess, fileShare, blockSize,
    FileFlagNoBuffering | FileOptions.WriteThrough | fileOptions);

Few rules:

*

*blockSize must be hard drive cluster size aligned (4096 most of the time)

*file position change must be cluster size aligned

*you can't read/write less than blockSize or block not aligned to it's size

And don't forget - there is also HDD Cache (which slower and smaller than OS cache) which you can't turn off by that (but sometimes FileOptions.WriteThrough helps for not caching writes). With those options you have no reason for flushing, but make sure you've properly tested that this approach won't slow things down in case your implementation of cache is slower.

A: I found this article and it seems that this is a complicated program because you also have to flush other caches.


Q: Digit sum of digit sum of $2020^{2021}$ Let $S(n)$ be the sum of the digits of a non-negative integer $n$. What is $S\left(S\left(2020^{2021}\right)\right)$?
Other than seeing that this is $7 \pmod 9$ (since every non-negative integer is congruent to its digit sum $\mod 9$), I'm not sure what else can be done.

A: When reading carefully the problem in the pdf you linked, one realizes that it asks for $S\left(S\left(S\left(2020^{2021}\right)\right)\right)$ rather than for $S\left(S\left(2020^{2021}\right)\right)$. I do not think that there is a reasonable method to evaluate the latter without a computer; notwithstanding, the actual answer is doable.
Observe, first of all, that $2020^{2021}$ has $\lceil 2021\cdot \log_{10}(2020)\rceil=6681$ digits; the last $2021$ are, of course, zeroes, since $10\mid 2020$. Thus $$S\left(2020^{2021}\right)\leqslant (6681-2021)\cdot 9=41940$$ We similarly obtain $$S\left(S\left(2020^{2021}\right)\right)\leqslant 4+4\cdot 9=40$$ At the same time, since $S(x)\equiv x\bmod 9$, we have $$S\left(S\left(2020^{2021}\right)\right)\equiv 2020^{2021}\equiv 4^{2021}\equiv 4^{336\cdot 6+5}\equiv 4^5\equiv 7\mod 9$$ Where I used that $\varphi(9)=6$. Hence $$S\left(S\left(2020^{2021}\right)\right)\in\{7, 16, 25, 34\}$$ Therefore, $S\left(S\left(S\left(2020^{2021}\right)\right)\right)=7.$


Q: Why does electricity flow into a capacitor (charged the other way round) but not into into a diode in this circuit? I'm trying to understand the workings of the following circuit that I've both emulated and built physically so I know it does work (I did it in a different simulator, but I've redrawn it here for your convenience - animated gifs from the simulator will follow):

simulate this circuit – Schematic created using CircuitLab
I understand the way NPN and PNP transistor work there with the 10uF capacitor C1 draining the current away from the base of the NPN transistor until the capacitor charges, upon which the current is applied to the NPN transistor base and it allows electricity to flow through it, which in turn "opens" the PNP transistor.
What I fail to understand is what happens with the capacitor and resistor under the emitter of the NPN transistor - the current seems to drawn upwards through the 100 uF capacitor C2. The capacitor is charged through the emitter at the beginning of the simulation, so it's indeed blocking the current from going downwards from the NPN emitter, but why would it take up the current the opposite way?
This gets even more mysterious if I replace it with a diode that goes the same way - it should have almost 0 resistance so if the current was drawn upwards through the capacitor, it should also be drawn through the diode.
Specifically, what I see in the simulator:

Now if I replace it with a diode it doesn't flow upwards at all, and I'd expect this to happen if an inversely charged capacitor causes it:

And if I replace it with another resistor it obviously flows downwards as expected through it:

Can you explain to me what is exactly happening here?
Here is the link to this circuit made in the original circuit simulator I've been using:
Circuit in the original online simulator
ADDITION: Indeed I see now on the circuit simulation reworked by Tony Stewart EE75 that the capacitor does get in fact discharged and then charged again.
One thing that still somewhat puzzles me - on the simulator it still shows that the current is flowing from a lower voltage (grey) to higher voltage (green) through the capacitor, which is normally not the case - even next to it we see the current flowing from high (green) voltage to low (grey). Is this a glitch of the simulator rendering the colours or something? Here's what I'm referring to (animated GIF from Tony Stewart EE75's circuit):

A: There is a lot to say about each component changes I made to improve this design.  But Rather than explain how your circuit works and why it overstresses an LED and why the frequency control of the pot is suboptimal, allow me to show a better solution with slight changes in values to reduce base drive currents and LED output powers from 10W pulses to 50 mW pulses suitable for small LED's .
Generally LEDs are not made for high current pulses ( e.g. typically <2x the DC rated , because the gold wire bond to Anode in LEDs with lens to be less visible and with excess current pulses becomes a fuse.
But the fundamentals are in the diode clamp position, just a linear current amplifier but lacking the necessary current limiting resistor values on the base or better on the LED to limit the current drive .
The right side  switch position is your fundamental BJT Relaxation Oscillator except using a PNP instead of an NPN with diodes for positive feedback thru two inverting transistors NPN+PNP.
It is better you ask questions on the purpose of each part in doubt.


Q: Python - huge memory consumption while parsing folder of CSV files I have several folders, each of them contains many CSV files. I need to parse them to make some plots etc.
The problem is, that memory consumption is huge and after while it skyrockets to cca 3.4GB. I have no idea what's the cause of this behavior, I've never met a memory-related problem with Python before.
I've found memory profiler, which gives me this output:
Filename: /home/martin/PycharmProjects/readex-radar/fooVisualizer.py

Line #    Mem usage    Increment   Line Contents
================================================
   560  293.340 MiB    0.000 MiB   @profile
   561                             def getAllDataClassifiedFromFolder(measuredFuncFolderArg,
   562                                                                yLabelArg,
   563                                                                filenameArgs,
   564                                                                slideshowCreator,
   565                                                                samplesArgs=None):
   566
   567  293.340 MiB    0.000 MiB       sampleSourcesInds = {}
   568  293.340 MiB    0.000 MiB       summarySourcesAvg = {}
   569  293.340 MiB    0.000 MiB       summarySourcesAvgInds = {}
   570  293.340 MiB    0.000 MiB       summarySourcesFull = {}
   571
   572 3342.426 MiB 3049.086 MiB       for dirpath, dirnames, filenames in os.walk(measuredFuncFolderArg, topdown=True):
   573                                     # Ignorovat skryte slozky kvuli GITu atd.
   574                                     # TODO mozna nebude treba
   575  293.340 MiB -3049.086 MiB           filenames = [f for f in filenames if not f[0] == '.']
   576  293.340 MiB    0.000 MiB           dirnames[:] = [d for d in dirnames if not d[0] == '.']
   577
   578                                     ##########################
   579                                     # Parsovani jedne slozky #
   580                                     ##########################
   581
   582                                     # Vsechna data z jedne slozky (funkce na urcitem radku)
   583  293.340 MiB    0.000 MiB           folderData = []
   584
   585                                     # Nacitam parametry dane v nazvu CSV souboru
   586  293.340 MiB    0.000 MiB           funcLabelArg = filenameArgs.getFuncLabel()
   587  293.340 MiB    0.000 MiB           xLabelArg = filenameArgs.getXLabel()
   588  293.340 MiB    0.000 MiB           otherUserArgs = filenameArgs.getConfigLst()
   589
   590                                     # 'Rozlozim' config argument na jednotlive hodnoty
   591  293.340 MiB    0.000 MiB           keyLst = filenameArgs.getLstOfParams()
   592
   593 3382.207 MiB 3088.867 MiB           for filename in filenames:
   594                                         # Nactu data
   595 3382.207 MiB    0.000 MiB               p = LabeledCSVParser('{}/{}'.format(dirpath, filename))
   596 3382.207 MiB    0.000 MiB               p.parse()
   597 3382.207 MiB    0.000 MiB               data = p.getDicData()
   598
   599                                         # Vytvorit a zapsat 'samples', pokud jsou zadany
   600                                         # parametrem 'samplesArgs'

We can see, that in lines 572 and 593 memory consumption rises dramatically. Do you have any idea why? I suppose it's something with os.walk...
So, have you ever seen this before? And if you have, could you, please, tell me, how to deal with this?

I've tried to add an explicit destructor to the LabeledCSVParser object, but it has a very little effect on memory. In addition, it appears, that there's no significant memory consumption in parse() function.
So, I'll try to inspect iterating through files a little more.
Edit 1
Filename: /home/martin/PycharmProjects/readex-radar/fooVisualizer.py

Line #    Mem usage    Increment   Line Contents
================================================
   100 3271.395 MiB    0.000 MiB       @profile
   101                                 def parse(self):
   102                                     """
   103                                     Funkce pro parsovani 'ostitkovaneho' CSV.
   104
   105                                     Predpoklada CSV ve tvaru:
   106
   107                                         # Label 1
   108                                         data1, data2
   109                                         data3, data4
   110
   111                                         # Label 2
   112                                         data5, data6
   113                                         data7, data8
   114                                         ...
   115
   116                                     Labely se mohou opakovat, ziskane hodnoty
   117                                     se ulozi do ruznych listu ve slovniku __dicData,
   118                                     kde jejich spolecnym klicem bude label.
   119                                     """
   120
   121 3271.395 MiB    0.000 MiB           currentLabel = self.__parsedFile.readline().split('#')[1].strip()
   122 3271.395 MiB    0.000 MiB           dataBlock = list()
   123 3271.395 MiB    0.000 MiB           self.__dicData[currentLabel] = list()
   124
   125                                     # Ulozim soucasny dataBlock do __dicData pod klic currentLabel
   126                                     # - hodnoty se do tohoto dataBlocku zapisuji pozdeji diky
   127                                     #   referenci
   128 3271.395 MiB    0.000 MiB           self.__dicData[currentLabel].append(dataBlock)
   129
   130 3272.949 MiB    1.555 MiB           for row in self.__parsedFile:
   131                                         # Kontrola, jestli se jedna o label nebo radek s daty
   132 3272.949 MiB    0.000 MiB               if row.__contains__('#'):
   133
   134                                             # Vytvorim novy dataBlock
   135 3271.395 MiB   -1.555 MiB                   dataBlock = list()
   136
   137                                             # Zisk nazvu labelu z radku
   138 3271.395 MiB    0.000 MiB                   tmpLabel = row.split('#')[1].strip()
   139
   140                                             # Label se stane 'aktualnim' -  nasledujici
   141                                             # data se budou zapisovat k nemu
   142 3271.395 MiB    0.000 MiB                   currentLabel = tmpLabel
   143
   144                                             # Pokud neni label 'zaevidovany', pridam
   145                                             # jej do __dicData jako klic
   146 3271.395 MiB    0.000 MiB                   if currentLabel not in self.__dicData.keys():
   147 3271.395 MiB    0.000 MiB                       self.__dicData[currentLabel] = list()
   148
   149 3271.395 MiB    0.000 MiB                   self.__dicData[currentLabel].append(dataBlock)
   150                                         else:
   151                                             # Pridam rozparsovany radek do aktualniho
   152                                             # bloku dat jako n-tici
   153 3272.949 MiB    1.555 MiB                   dataBlock.append(tuple(row.strip().split(',')))

Filename: /home/martin/PycharmProjects/readex-radar/fooVisualizer.py

Line #    Mem usage    Increment   Line Contents
================================================
   558  293.543 MiB    0.000 MiB   @profile
   559                             def getAllDataClassifiedFromFolder(measuredFuncFolderArg,
   560                                                                yLabelArg,
   561                                                                filenameArgs,
   562                                                                slideshowCreator,
   563                                                                samplesArgs=None):
   564
   565  293.543 MiB    0.000 MiB       sampleSourcesInds = {}
   566  293.543 MiB    0.000 MiB       summarySourcesAvg = {}
   567  293.543 MiB    0.000 MiB       summarySourcesAvgInds = {}
   568  293.543 MiB    0.000 MiB       summarySourcesFull = {}
   569
   570 2746.160 MiB 2452.617 MiB       for dirpath, dirnames, filenames in os.walk(measuredFuncFolderArg, topdown=True):
   571                                     # Ignorovat skryte slozky kvuli GITu atd.
   572                                     # TODO mozna nebude treba
   573                                     #filenames = [f for f in filenames if not f[0] == '.']
   574                                     #dirnames[:] = [d for d in dirnames if not d[0] == '.']
   575
   576                                     ##########################
   577                                     # Parsovani jedne slozky #
   578                                     ##########################
   579
   580                                     # Vsechna data z jedne slozky (funkce na urcitem radku)
   581  293.543 MiB -2452.617 MiB           folderData = []
   582
   583                                     # Nacitam parametry dane v nazvu CSV souboru
   584  293.543 MiB    0.000 MiB           funcLabelArg = filenameArgs.getFuncLabel()
   585  293.543 MiB    0.000 MiB           xLabelArg = filenameArgs.getXLabel()
   586  293.543 MiB    0.000 MiB           otherUserArgs = filenameArgs.getConfigLst()
   587
   588                                     # 'Rozlozim' config argument na jednotlive hodnoty
   589  293.543 MiB    0.000 MiB           keyLst = filenameArgs.getLstOfParams()
   590
   591  293.543 MiB    0.000 MiB           print('nacitam data')
   592 3271.395 MiB 2977.852 MiB           for filename in filenames:
   593                                         # Nactu data
   594 3271.395 MiB    0.000 MiB               p = LabeledCSVParser('{}/{}'.format(dirpath, filename))
   595 3271.395 MiB    0.000 MiB               p.parse()
   596 3271.395 MiB    0.000 MiB               data = p.getDicData()
   597
   598 3271.395 MiB    0.000 MiB               print('zapisuji samples')
   599                                         # Vytvorit a zapsat 'samples', pokud jsou zadany
   600                                         # parametrem 'samplesArgs'
   601 3271.395 MiB    0.000 MiB               if samplesArgs:
   602                                             sampleSourcesInds[filename] = {}
   603                                             for sampleArg in samplesArgs:
   604                                                 prevNumOfSources = slideshowCreator.getNumOfDataSources()
   605                                                 slideshowCreator.createAndAddDataSource(data[sampleArg], 100, True, 0, 2)
   606                                                 sampleSourcesInds[filename][sampleArg] = list(range(prevNumOfSources,
   607                                                                                slideshowCreator.getNumOfDataSources()))
   608
   609                                         # Ziskam nazvy parametru z nazvu souboru
   610 3271.395 MiB    0.000 MiB               args = filename[0:filename.rfind('.')].split('_')
   611
   612 3271.395 MiB    0.000 MiB               print('tvorim slovnik')
   613                                         # Priradim konkretni hodnoty z nazvu CSV souboru
   614                                         # k zadanym parametrum filenameArgs
   615 3271.395 MiB    0.000 MiB               d = {key: (args[i] if i < len(args) else '') for i, key in enumerate(keyLst)}
   616
   617                                         # Pridam do slovniku nactena data ze souboru
   618 3271.395 MiB    0.000 MiB               d['Data'] = data
   619
   620 3271.395 MiB    0.000 MiB               print('pridavam slovnik do folderData')
   621 3271.395 MiB    0.000 MiB               folderData.append(d)
   622
   623                                     ###############################################################
   624                                     # Rozdelim nactena data ze slozky do skupin podle volitelnych #
   625                                     # argumentu (preconditioner, schur complement...)             #
   626                                     ###############################################################
   627 2742.480 MiB -528.914 MiB           print('rozdeluji data do kategorii')
   628                                     # Ulozene prumerne hodnoty yLabel za vsechna
   629                                     # volani funkce
   630 2742.480 MiB    0.000 MiB           folderDataGroupsAvg = {}
   631
   632                                     # Ulozene hodnoty yLabel ze vsech volani fce
   633                                     #
   634                                     # TODO mozna bude treba zapsat jako zdroj pro
   635                                     # graf jednotlivych iteraci solveru
   636 2742.480 MiB    0.000 MiB           folderDataGroupsFull = {}
   637
   638 2745.746 MiB    3.266 MiB           for i, val in enumerate(folderData):
   639                                         # Ziskam hodnoty konfiguracnich argumentu
   640                                         # a ulozim je jako n-tici
   641 2745.746 MiB    0.000 MiB               optArgsTup = tuple([str(val[arg]) for arg in otherUserArgs])
   642
   643                                         # Pokud jeste neni, pridam n-tici s konfiguracnimi
   644                                         # parametry jako klic pro slovnik s prumernymi
   645                                         # hodnotami spotreby
   646 2745.746 MiB    0.000 MiB               if optArgsTup not in folderDataGroupsAvg:
   647 2743.320 MiB   -2.426 MiB                   folderDataGroupsAvg[optArgsTup] = {}
   648 2743.320 MiB    0.000 MiB                   folderDataGroupsFull[optArgsTup] = {}
   649
   650 2745.746 MiB    2.426 MiB               if folderData[i][funcLabelArg] not in folderDataGroupsAvg[optArgsTup]:
   651 2744.539 MiB   -1.207 MiB                   folderDataGroupsAvg[optArgsTup][folderData[i][funcLabelArg]] = []
   652 2744.539 MiB    0.000 MiB                   folderDataGroupsFull[optArgsTup][folderData[i][funcLabelArg]] = []
   653
   654                                         # Fce pro ziskani hodnot z Blade summary,
   655                                         # ktere slouzi jako yLabelArg.
   656                                         # Nepsano jako lambda kvuli fyz. delce kodu funkce.
   657 2745.746 MiB    1.207 MiB               def getYLabelVals(ind):
   658 2745.746 MiB    0.000 MiB                   retLst = []
   659 2745.746 MiB    0.000 MiB                   for subLst in folderData[ind]['Data']['Blade summary']:
   660 2745.746 MiB    0.000 MiB                       for item in subLst:
   661 2745.746 MiB    0.000 MiB                           if item[0] == yLabelArg:
   662 2745.746 MiB    0.000 MiB                               retLst.append(float(item[1]))
   663 2745.746 MiB    0.000 MiB                   return retLst
   664
   665                                         # Zapisu hodnoty ze vsech volani fce pro jedno nastaveni
   666                                         # do folderDataGroupsFull
   667 2745.746 MiB    0.000 MiB               folderDataGroupsFull[optArgsTup][folderData[i][funcLabelArg]] \
   668 2745.746 MiB    0.000 MiB                   .append((folderData[i][xLabelArg], getYLabelVals(i)))
   669
   670                                         # Ziskam prumernou spotrebu ze vsech volani fce pro jedno
   671                                         # nastaveni (Prec, Schur) a jeden popisek funkce
   672                                         # (pocet jader...).
   673                                         #
   674                                         # TYTO UDAJE PRIDAM do folderDataGroupsAvg.
   675 2745.746 MiB    0.000 MiB               folderDataGroupsAvg[optArgsTup][folderData[i][funcLabelArg]] \
   676 2745.746 MiB    0.000 MiB                   .append((folderData[i][xLabelArg], numpy.mean(getYLabelVals(i))))
   677
   678 2745.746 MiB    0.000 MiB           print('zapidu folderDataGroupsAvg jako zdroj')
   679                                     # Ziskani dat z folderDataGroupsAvg a jejich zapis jako zdroje
   680 2746.160 MiB    0.414 MiB           for key, vals in sorted(folderDataGroupsAvg.items()):
   681 2746.160 MiB    0.000 MiB               summarySourcesAvg[key] = {}
   682
   683                                         # TODO promyslet, jestli nebude lepsi sloucit summarySourcesAvg a summarySourcesAvgInds
   684                                         # do jednoho slovniku
   685 2746.160 MiB    0.000 MiB               summarySourcesAvgInds[key] = {}
   686
   687 2746.160 MiB    0.000 MiB               for subKey, val in sorted(vals.items()):
   688                                             # Zapisu do listu zdroje pro danou konfiguraci - pro vypocty procent atd.
   689 2746.160 MiB    0.000 MiB                   summarySourcesAvg[key][subKey] = val
   690
   691                                             # Zapisu data do zdroju pro vykreslovani grafu
   692 2746.160 MiB    0.000 MiB                   summarySourcesAvgInds[key][subKey] = slideshowCreator.getNumOfDataSources()
   693 2746.160 MiB    0.000 MiB                   slideshowCreator.createAndAddDataSourcesTexCode([sorted(val)], 0, False, 0, 1)
   694
   695 2746.160 MiB    0.000 MiB           print('ziskam data z folderDataGroupsFull')
   696                                     # Ziskani dat z folderDataGroupsFull
   697                                     #
   698                                     # TODO mozna bude potreba i zapis zdroju pro
   699                                     # grafy jednotlivych iteraci
   700 2746.160 MiB    0.000 MiB           for key, vals in sorted(folderDataGroupsFull.items()):
   701 2746.160 MiB    0.000 MiB               summarySourcesFull[key] = {}
   702
   703 2746.160 MiB    0.000 MiB               for subKey, val in sorted(vals.items()):
   704                                             # Zapisu do listu zdroje pro danou konfiguraci - pro vypocty procent atd.
   705 2746.160 MiB    0.000 MiB                   summarySourcesFull[key][subKey] = val
   706
   707 2746.160 MiB    0.000 MiB       return summarySourcesAvg, sampleSourcesInds, summarySourcesAvgInds, summarySourcesFull


Q: How to get clean website url with php? I'm using $wsurl as my websites clean url $wsurl = 'http://'. $_SERVER['HTTP_HOST'] . '/'; But recently when I want to echo it from websites admin panel it gave me result:
http://localhost/admin/>http://localhost/?page=166
instead of
http://localhost/?page=166
More Detailed
What i use: <?=$wsurl?>?page=<?=$new_id?>">Link
What i get as html output localhost/?page=170">Link
But when i click it from admin panel, it opens page localhost/admin>http://localhost/?page=170 (instead of http://localhost/?page=170) which doesn't exist at all
How to deal with that problem?
I want to get websites main url from everywhere within ws.
For ex, if i'm in admin panel http://localhost/admin/index.php the $wsurl will be http://localhost/
If my admin panels url looks like http://mydomain.com/admin/index.php the $wsurl will be http://mydomain.com/

A: If you are facing issues like that then you can try this :
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo 'http://'.parse_url($url, PHP_URL_HOST) . '/';


Q: Display Product Sku in Child Products - Magento 2.2.3 On our Magento site, we have it so it displays the SKU under the main product title, but if there are child listings, possibly for different configurations of the product' the sku isn't appearing.
I cant seem to find any layout file associated with that child list, can anyone point me in the right direction to add the SKU to this Child Product List,
An example of what I mean can be found here: https://i.imgur.com/uo11tYi.png

A: Copy the below file:

vendor/magento/module-grouped-product/view/frontend/templates/product/view/type/grouped.phtml

to your theme location like below:

app/design/frontend/Vendor/theme/Magento_GroupedProduct/templates/product/view/type/grouped.phtml

And find the below section in your grouped.phtml:
<td data-th="<?= $block->escapeHtml(__('Product Name')) ?>" class="col item">
    <?= $block->escapeHtml($_item->getName()) ?>
    <?php if ($block->getCanShowProductPrice($_product)): ?>
        <?php if ($block->getCanShowProductPrice($_item)): ?>
            <?= /* @escapeNotVerified */ $block->getProductPrice($_item) ?>
        <?php endif; ?>
     <?php endif; ?>

and replace with below code:
<td data-th="<?= $block->escapeHtml(__('Product Name')) ?>" class="col item">
    <?= $block->escapeHtml($_item->getName()) ?>

<?= $_item->getSku() ?>

    <?php if ($block->getCanShowProductPrice($_product)): ?>
        <?php if ($block->getCanShowProductPrice($_item)): ?>
            <?= /* @escapeNotVerified */ $block->getProductPrice($_item) ?>
        <?php endif; ?>
     <?php endif; ?>

Flush the cache and check.


Q: CreateChooser is not working in Android v5.1 I am using intent to share pdf files. I am restricting apps when share file. I want to share the file to Good document, Kindle and drop box alone. I am using the below code to achieve this.But the below code is not working in android v5.1. The device have the required app to share. But it is showing "No apps can perform this action" when share. Can you anyone suggest your ideas to resolve this?
var pathFile = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            var m_documentMobiNames = shortName + "." + fileType;
            var mobileFileName = Path.Combine(pathFile, m_documentMobiNames);
            var shareIntentsLists = new List<Intent>();
            Intent sendIntent = new Intent();
            sendIntent.SetAction(Intent.ActionSend);
            sendIntent.SetType("application/pdf");
            var resInfos = context.PackageManager.QueryIntentActivities(sendIntent, 0);
            if (resInfos.Count > 0)
            {
                foreach (var resInfo in resInfos)
                {
                    string packageName = resInfo.ActivityInfo.PackageName;
                    if (packageName.Contains("com.google.android.apps.docs") || packageName.Contains("com.dropbox.android") || packageName.Contains("com.amazon.kindle"))
                    {
                        Intent intent = new Intent();
                        intent.SetComponent(new ComponentName(packageName, resInfo.ActivityInfo.Name));
                        intent.SetAction(Intent.ActionSend);
                        intent.SetType("application/pdf");
                        intent.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse("file://" + mobileFileName));
                        intent.SetPackage(packageName);
                        shareIntentsLists.Add(intent);
                    }
                }
            }

            if (shareIntentsLists.Count > 0)
            {

                chooserIntent = Intent.CreateChooser(new Intent(), "Share with");
                chooserIntent.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse(mobileFileName));
                chooserIntent.PutExtra(Intent.ExtraInitialIntents, shareIntentsLists.ToArray());
                chooserIntent.SetFlags(ActivityFlags.ClearTop);
                chooserIntent.SetFlags(ActivityFlags.NewTask);
                context.StartActivity(chooserIntent);
                await Task.FromResult(true);

            }


Q: Axios delete is ignoring the second argument This is my createAsyncThunk
export const removePlayer = createAsyncThunk(
    'player/removePlayer',
    async (playerId: any, thunkAPI) => {
        try {
            await axios.delete(URL, playerId)
        } catch (error) {
            return thunkAPI.rejectWithValue(error)
        }
    }
)

And this is the function that dispatches the action
<Button variant='outlined' onClick={() => {
     dispatch(removePlayer(player._id))
}}><DeleteIcon /></Button>

I have used createAsyncThunk for other CRUD operations like Read, Create and Update and they all work just fine. Am I using axios.delete wrong? This is what I feel. As you can see, all I want to do is pass in the player ID, then delete it, simple as that. I used very similar logic for axios.put, axios.get and axios.post and they all work fine
EDIT I can solve this by adding a id parameter to the route like so
router.delete('/:id', deletePlayer)

But im just curious if there is another alternative, because with axios post get and put, I can do it without using any params

A:
But im just curious if there is another alternative

Typically DELETE requests do not have a request body though that doesn't mean you cannot use one.
From the client side, something like this...
axios.delete("/url/for/delete", {
  data: { playerId }
});

will send an application/json request with body {"playerId":"some-id-value"}.
On the server side, with Express you would use this
router.delete("/url/for/delete", async (req, res, next) => {
  const { playerId } = req.body;

  try {
    // do something with the ID...

    res.sendStatus(204);
  } catch (err) {
    next(err.toJSON());
  }
});

To handle JSON payloads you should have registered the appropriate middleware
app.use(express.json());


Q: automatically detect an apache server running on a specific vm and zone in Google Cloud Platform Note: This is a self-answered question, which is allowed here.  If you have better solutions go ahead and post them.
Hypothetical automation for a web-based cloud school needs to test if students have some minimal competence before proceeding.  Students must be able to start a Google Cloud VM, install apache on it, and expose port 80 to the public internet, before proceeding to the next task.
The question is not about how to set up apache.  That's obvious.
The question is how to test if its been done.
So the first step is to detect the VM.  We tell the students to call it something and we tell them the zone to use.
An early draft of an apache install detector -- executed on another VM inaccessible to the student but within the student's GCP project context -- could start like this:
#!/bin/bash
NAME="required-vm-name"
ZONE="us-central1-a"
IP=$(gcloud compute instances describe ${NAME} --zone ${ZONE} --format json | jq ".networkInterfaces[0].accessConfigs[0].natIP")
echo $IP
curl -v "http://${IP}"

but this produces the output
"1.2.3.4"
* Rebuilt URL to: http://"1.2.3.4"/
* Could not resolve host: "1.2.3.4"
* Closing connection 0 curl: (6) Could not resolve host: "1.2.3.4"

where I've redacted the address to 1.2.3.4 but kept all other output formatting.
Given the IP address is correct, and the debian apache2 test page displays properly at this address, why can't curl detect it? what's wrong? The correct IP works fine in Chrome.

A: curl isn't playing well with that double quoted string in the URL.
Add the -r option to the jq command to return a raw string and not a JSON-formatted string.  Otherwise jq will output JSON-format by default, which for string results is going to be double-quoted.
#!/bin/bash
NAME="required-vm-name"
ZONE="us-central1-a"
IP=$(gcloud compute instances describe ${NAME} --zone ${ZONE} --format json | jq -r ".networkInterfaces[0].accessConfigs[0].natIP")
echo $IP
curl -v "http://${IP}"

The output is now better. Note the lack of quotes around the extracted public IP address.
1.2.3.4
* Rebuilt URL to: http://1.2.3.4/
*   Trying 1.2.3.4...
* TCP_NODELAY set
* Connected to 1.2.3.4 (1.2.3.4) port 80 (#0)
> GET / HTTP/1.1
> Host: 1.2.3.4
> User-Agent: curl/7.52.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Sun, 24 Feb 2019 11:46:54 GMT
< Server: Apache/2.4.25 (Debian)
< Last-Modified: Sun, 24 Feb 2019 11:21:58 GMT
< ETag: "c-582a20841f053"
< Accept-Ranges: bytes
< Content-Length: 12
< Content-Type: text/html
<
Hello World
* Curl_http_done: called premature == 0
* Connection #0 to host 1.2.3.4 left intact


Q: Is there a simple way to use OpenSSL BIO objects in Java or are there any alternatives? Could anyone tell me is there any way to use OpenSSL's BIO objects from Java?
I'm working on a project, which is intended to provide support for handling of PEAP (https://en.wikipedia.org/wiki/Protected_Extensible_Authentication_Protocol) packets by TinyRadius.
I have tried to search any existing PEAP implementations in Java, but, it seems, there is no one.
Successfully, I have found an implementation, written in Python, which uses pyOpenSSL to decrypt and encrypt data within PEAP sessions. But the problem is that the code uses several OpenSSL features, which are not provided by javax.net.ssl like reading and writing into BIO objects of a SSL session or getting a master key and secure random, generated by the client from a session.
Here is an example of code, which I'm trying to port:
def get_keys(self):
    self.master_key = self.ssl_connection.master_key()
    self.server_sec_random = self.ssl_connection.server_random()
    self.client_sec_random = self.ssl_connection.client_random()
...
def write(self, data):
    self.ssl_connection.bio_write(data)
...
def read(self):
    return self.ssl_connection.bio_read(4096)

I have studied pyOpenSSL and found that all these calls are just wrappers for OpenSSL library functions through libffi (http://sourceware.org/libffi), but I have no idea of how implement the same functionality in Java.
As far as I understand the only way for me is use JNI (or JNA) to call OpenSSL functions. Also, I need to implement the code for managing lifetime of objects, created during OpenSSL access but I do not know how to do that, because I do not have any prior experience with native code from Java.
If anyone knows other ways to utilize OpenSSL from Java or maybe some ready-to-use implementations or ports of OpenSSL, please tell me - all answers are highly appreciated.
Thanks!

A: After numerous searches for ways to utilize OpenSSL from Java I have ended up with JNA wrapper implementation, which, suprisingly, appeared to be pretty simple.
Fortunately, OpenSSL is designed in such way that in vast majority of use-cases we do not need to exactly know the type of the value, returned from the call to OpenSSL function (e.g. OpenSSL does not require to call any methods from structures or work with structure fields directly) so there is no need in huge and complex wrappings for OpenSSL's data types.
Most of OpenSSL's functions operate with pointers, which may be wrapped into an instance of com.sun.jna.Pointer class, which is equivalent to casting to void* in terms of C, and the callee will determine the correct type and de-reference the given pointer correctly.
Here is a small code example of how to load ssleay32.dll, initialize the library and create a context:
1) Define the interface to ssleay32.dll library (functions list may be obtained from OpenSSL GitHub repo or by studying the export section of the dll):
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Pointer;

public interface OpenSSLLib extends Library {
  public OpenSSLLib INSTANCE = (OpenSSLLib) Native.loadLibrary("ssleay32",
                               OpenSSLLib.class);
  // Non-re-enterable! Should be called once per a thread (process).
  public void SSL_library_init();
  public void SSL_load_error_strings();

  // Supported context methods.
  public Pointer TLSv1_method();

  ...

  // Context-related methods.
  public Pointer SSL_CTX_new(Pointer method);
  public void SSL_CTX_free(Pointer context);
  public int SSL_CTX_use_PrivateKey_file(Pointer context, String filePath, int type);
  public int SSL_CTX_use_certificate_file(Pointer context, String filePath, int type);
  public int SSL_CTX_check_private_key(Pointer context);
  public int SSL_CTX_ctrl(Pointer context, int cmd, int larg, Pointer arg);
  public void SSL_CTX_set_verify(Pointer context, int mode, Pointer verifyCallback);
  public int SSL_CTX_set_cipher_list(Pointer context, String cipherList);

  public Pointer SSL_new(Pointer context);
  public void SSL_free(Pointer ssl);

  ...
}

2) Initialize the library:
...
public static OpenSSLLib libSSL;
public static LibEayLib  libEay;
...

static {
    libSSL = OpenSSLLib.INSTANCE;
    libEay = LibEayLib.INSTANCE;
    libSSL.SSL_library_init();
    libEay.OPENSSL_add_all_algorithms_conf(); // This function is called from
                                              // libeay32.dll via another JNA interface.
    libSSL.SSL_load_error_strings();
}

...
3) Create and initialize SSL_CTX and SSL objects:
public class SSLEndpoint {
  public Pointer context; // SSL_CTX*
  public Pointer ssl;     // SSL*
  ...
}

...

SSLEndpoint endpoint = new SSLEndpoint();

...

// Use one of supported SSL/TLS methods; here is the example for TLSv1 Method
endpoint.context = libSSL.SSL_CTX_new(libSSL.TLSv1_method());

if(endpoint.context.equals(Pointer.NULL)) {
  throw new SSLGeneralException("Failed to create SSL Context!");
}

int res = libSSL.SSL_CTX_set_cipher_list(endpoint.context, OpenSSLLib.DEFAULT_CIPHER_LIST);
if(res != 1) {
  throw new SSLGeneralException("Failed to set the default cipher list!");
}

libSSL.SSL_CTX_set_verify(endpoint.context, OpenSSLLib.SSL_VERIFY_NONE, Pointer.NULL);

// pathToCert is a String object, which defines a path to a cerificate
// in PEM format.
res = libSSL.SSL_CTX_use_certificate_file(endpoint.context, pathToCert, certKeyTypeToX509Const(certType));
if(res != 1) {
  throw new SSLGeneralException("Failed to load the cert file " + pathToCert);
}

// pathToKey is a String object, which defines a path to a priv. key
// in PEM format.
res = libSSL.SSL_CTX_use_PrivateKey_file(endpoint.context, pathToKey, certKeyTypeToX509Const(keyType));
if(res != 1) {
  throw new SSLGeneralException("Failed to load the private key file " + pathToKey);
}

res = libSSL.SSL_CTX_check_private_key(endpoint.context);
if(res != 1) {
  throw new SSLGeneralException("Given key " + pathToKey + " seems to be not valid.");
}

SSLGeneralException is the custom exception, simply inherited from RuntimeException.
...
// Create and init SSL object with given SSL_CTX
endpoint.ssl = libSSL.SSL_new(endpoint.context);
...

Next steps may be creating of BIO objects and linking them to the SSL object.
Regarding to the original question, client/server secure randoms and the master key may be obtained via such methods:
public int SSL_get_client_random(Pointer ssl, byte[] out, int outLen);
public int SSL_get_server_random(Pointer ssl, byte[] out, int outLen);
public int SSL_SESSION_get_master_key(Pointer session, byte[] out, int outLen);

Please, note, that JNA will search dlls to load looking into jna.library.path parameter. So, if the dlls are located, for example in directory D:\dlls, you must specify such VM option:
-Djna.library.path="D:/dll"
Also, JNA requires 32-bit JRE for 32-bit dlls (probably, libffi constraint?). If you try to load a 32-bit dll using 64-bit JRE, you'll get an exception.


Q: downgrade laravel project 5.5 to 5.0.* First of all sorry about my English! I'm in situation where I need to downgrade my Laravel project because some history about php version running on installation server (php 5.4). After I set my composer.json and run update,
I get this error

composer update --no-interaction --ansi
 C:\composer\composer.bat update --no-interaction --ansi
 Loading composer repositories with package information
 Updating dependencies (including require-dev)
 Package operations: 46 installs, 0 updates, 0 removals
   - Installing psy/psysh (v0.4.4): Downloading (connecting...)
 Downloading (failed)
 Downloading (connecting...)
 Downloading (failed)
 Downloading (connecting...)
 Downloading (failed)    Failed to download psy/psysh from dist: The "https://api.github.com/repos/bobthecow/psysh/zipball/489816db71649bd95b416e3ed9062d40528ab0ac" file could not be downloaded: SSL operation failed with code 1. OpenSSL Error messages:
 error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version
 Failed to enable crypto
 failed to open stream: operation failed
     Now trying to download from source
   - Installing psy/psysh (v0.4.4): Cloning 489816db71 from cache
     489816db71649bd95b416e3ed9062d40528ab0ac is gone (history was rewritten?)

   [RuntimeException]
   Failed to execute git checkout "489816db71649bd95b416e3ed9062d40528ab0ac" -
   - && git reset --hard "489816db71649bd95b416e3ed9062d40528ab0ac" --

   fatal: reference is not a tree: 489816db71649bd95b416e3ed9062d40528ab0ac

 update [--prefer-source] [--prefer-dist] [--dry-run] [--dev] [--no-dev] [--lock] [--no-custom-installers] [--no-autoloader] [--no-scripts] [--no-progress] [--no-suggest] [--with-dependencies] [--with-all-dependencies] [-v|vv|vvv|--verbose] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [-i|--interactive] [--root-reqs] [--] [<packages>]...

 Failed to update packages for  ./composer.json.

could someone help me to fix this error?!


Q: Issue with ComboBox - DropDownStyles + Disable Text Edit So i've looked at a few stackoverflow posts and nothing seems to be solving my issue.
Tried:
How to show text in combobox when no item selected?
And some others, can't find link now.
Application:
http://puu.sh/5mQtX.png
So for the drop down menu at the bottom, I was trying to make the text display "Select Email Use" but whenever adding the text using the DropDownList in the DropDownStyle menu, the text disappears. But I want to make it so the user cannot just edit the text.
Don't have any code exactly for the program right now.
From the SOF post I linked above, I tried everything in that post to fix the issue but nothing exactly helps.
i am using Visual C# 2010 Windows Form Application

A: You can use Text Property of ComboBox Control to show Default Text
Try:
ComboBox1.Text="Select Email Use";

It will be shown ByDefault

A: I think you have to draw the string yourself, here is the working code for you, there is a small issue with the flicker, the string is a little flickering when the mouse is hovered on the combobox, even enabling the DoubleBuffered doesn't help, however it's acceptable I think:
public partial class Form1 : Form {
   public Form1(){
      InitializeComponent();
      comboBox1.HandleCreated += (s,e) => {
         new NativeComboBox{StaticText = "Select Email Use"}
                           .AssignHandle(comboBox1.Handle);
      };
   }
   public class NativeComboBox : NativeWindow {
        public string StaticText { get; set; }

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            if (m.Msg == 0xf)//WM_PAINT = 0xf
            {
                var combo = Control.FromHandle(Handle) as ComboBox;
                if (combo != null && combo.SelectedIndex == -1)
                {
                    using (Graphics g = combo.CreateGraphics())
                    using (StringFormat sf = new StringFormat { LineAlignment = StringAlignment.Center })
                    using (Brush brush = new SolidBrush(combo.ForeColor))
                    {
                        g.DrawString(StaticText, combo.Font, brush, combo.ClientRectangle, sf);
                    }
                }
            }
        }
    }
}


Q: Is it possible to integrate Google Play Games Services Realtime Multiplayer into LibGDX for both Android and iOS? I have integrated real-time multiplayer in LibGDX for Android. Now I am wondering how to implement it also for iOS. I have a few questions:
Is this possible?
Can Android and iOS players play together?
What are the possible ways to implement?

A: It is possible, of course. Have a look at interfacing. For the iOS app I would use the Multi-OS engine. Use the normal gdx-setup jar file to create moe module.


Q: Retrieve the formated URL from open_id form I just added OpenID to my website using the PHP janrain libraries, and I got everything working but I have a question about how to do something.
After receiving the openid_url from the user, I pass it to the openid lib, which then processes the url and gets it ready to send to the OP.  How can I retrieve that URL?
Why I ask is because my script currently sees http://mysite.com and mysite.com as different URLs.  I know the library normalizes the URL, I just don't know how to extract it.
I hope I made sense, and thank you for helping.

A: You get the final URL you want to use for tracking purposes back with a Auth_OpenID_SuccessResponse object, in the claimed_id attribute.  (The getDisplayIdentifier() method outputs a version more intended for human consumption, which may or may not be different.)


Q: how to fix 'shopify.api_version.VersionNotFoundError' I am building a simple “Hello World” using Python, Flask and the Shopify Embedded SDK. Following this tutorial----> https://medium.com/@dernis/shopify-embedded-sdk-with-python-flask-6af197e88c63.
After doing all the work when I go to the link ' https://localhost:5000/shopify/install?shop=khawaja-kaleem-com.myshopify.com '   to install the application to test store it gives me this error. Need to fix it.
shopify.api_version.VersionNotFoundError.

TRACEBACK (MOST RECENT CALL LAST)
File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\92344\Anaconda3\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\92344\Anaconda3\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\92344\Downloads\HelloShopify-master\helloshopify\shopify_bp\views.py", line 36, in install
session = shopify.Session(shop_url)
File "C:\Users\92344\Anaconda3\lib\site-packages\shopify\session.py", line 47, in __init__
self.version = ApiVersion.coerce_to_version(version)
File "C:\Users\92344\Anaconda3\lib\site-packages\shopify\api_version.py", line 18, in coerce_to_version
raise VersionNotFoundError
shopify.api_version.VersionNotFoundError

A: You need to specify the API version you wish to use. Set the version before you make any calls. 2020-10 is the default for now.
See the documentation, it explains everything to you.
https://help.shopify.com/en/api/versioning

A: The ShopifyAPI package specifies the allowed versions in the 'shopify/api_version.py' file. In my case the Shopify platform latest API version is '2022-10' but the latest version allowed by the ShopifyAPI package is '2022-07'.
It seems that the ShopifyAPI package is not always updated quickly after the release of a new API version on the Shopify platform. Try aligning the API version to one of the versions allowed to work around this error.


Q: Where can i see the log written by uisng Gauge.writemessage()? Just now i am started switching from testNg to Gauge framework for many reasons, now my question is where i can find the log which was written by using Gauge.writemessage inbuilt method. Or else is there any way to customize the location for the sam.?

A: That message will be in the Gauge report under the step it was executed in.
I personally look at the html reports, but I would assume it is in the xml option as well.
If you want something instantaneous you can write to the console where real time messages are output.  This also helps if some sort of bug in the code prevents the reports from being written (like an infinite loop that keeps the report from being written at the end of the full execution).
Here is what it would look like. The gray box is the GaugeMessage.

A: Gauge.writeMessage api allows you to push messages to the reports at logical points.
For example, the step implementation below
    @Step("Vowels in English language are <vowelString>.")
    public void setLanguageVowels(String vowelString) {
    Gauge.writeMessage("Setting vowels to " + vowelString);
        vowels = new HashSet<>();
        for (char ch : vowelString.toCharArray()) {
            vowels.add(ch);
        }
    }

yields this html report:


Q: How can I replace Fragment inside Dialog inside a DialogFragment? I'm trying to use https://github.com/rockerhieu/emojicon library in order to produce an EmojiKeyboard over the softkeyboard just like WhatsApp and Telegram does.
After some research, I figure that the way they do is by creating a Dialog over the soft keyboard. The library is a fragment that needs to replace some element of the layout in execution time. The replacement happens int this class:
/**
 * Class responsible for managin user's interaction with the Emoji Keyboard
 */
public class EmojiKeyboardManager {

    public static final String TAG = "EmojiKeyboardManager";

    private AppCompatActivity mActivity;

    private FrameLayout mEmojiconContainer;
    private EmojiconEditText mEditEmojicon;
    private LinearLayout mEmojiconButton;
    private ImageView mEmojiconButtonImg;

    // CONSTRUCTOR
    public EmojiKeyboardManager(AppCompatActivity activity) {
        this.mActivity = activity;
        this.implementEmojiconButton();
        this.implementInputTextListener();
        //this.initEmojiconFragment(Boolean.FALSE);
    }

    // INITIALIZATIONS
    private void implementEmojiconButton() {
        this.mEmojiconButtonImg = (ImageView) this.mActivity.findViewById(R.id.emojiButton);
        this.mEmojiconButton = (LinearLayout) this.mActivity.findViewById(R.id.emojiButtonWrapper);
        EmojiKeyboardManager.this.mEmojiconButtonImg.setSelected(Boolean.FALSE);
        this.mEmojiconButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (EmojiKeyboardManager.this.mEmojiconButtonImg.isSelected()) {
                    EmojiKeyboardManager.this.hideEmojiconKeyboard(Boolean.TRUE);
                } else {
                    EmojiKeyboardManager.this.showEmojiconKeyboard();
                }
            }
        });
    }

    public void showEmojiconKeyboard() {
        LayoutUtil.dismissSoftKeyboard(this.mEditEmojicon);
        EmojiKeyboardManager.this.mEmojiconButtonImg.setImageResource(R.drawable.ic_keyboard_black_36dp);

        DialogFragment newFragment = SampleDialogFragment.newInstance();
        newFragment.show(this.mActivity.getSupportFragmentManager(), "dialog");

        //this.mEmojiconContainer.setVisibility(FrameLayout.VISIBLE);
        EmojiKeyboardManager.this.mEmojiconButtonImg.setSelected(Boolean.TRUE);
    }

    public void hideEmojiconKeyboard(Boolean showSoftkeyboard) {
        EmojiKeyboardManager.this.mEmojiconButtonImg.setImageResource(R.drawable.input_emoji);
        LayoutUtil.dismissSoftKeyboard(EmojiKeyboardManager.this.mEditEmojicon);
        //this.mEmojiconContainer.setVisibility(FrameLayout.GONE);
        EmojiKeyboardManager.this.mEmojiconButtonImg.setSelected(Boolean.FALSE);
        if (showSoftkeyboard) {
            EmojiKeyboardManager.this.mEditEmojicon.requestFocus();
            LayoutUtil.showSoftKeyboard(EmojiKeyboardManager.this.mEditEmojicon);
        }
    }

    private void implementInputTextListener() {
        this.mEditEmojicon = (EmojiconEditText) this.mActivity.findViewById(R.id.message);
        this.mEditEmojicon.clearFocus();
    }

    // GETTERS AND SETTERS
    public EmojiconEditText getmEditEmojicon() {
        return this.mEditEmojicon;
    }

    public Boolean isEmojikeyboardAttached() {
        return EmojiKeyboardManager.this.mEmojiconButtonImg.isSelected();
    }

}

In order to achieve what I need I'm using a subclass of DialogFragment that creates a Dialog like that:
public class SampleDialogFragment extends DialogFragment {

    private Dialog dialog;

    static SampleDialogFragment newInstance() {
        SampleDialogFragment f = new SampleDialogFragment();
        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        this.dialog = new Dialog(this.getActivity(), android.R.style.Theme_NoTitleBar);

        this.dialog.setContentView(R.layout.rsc_emoji_keyboard);
        this.dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
        this.dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
        this.dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        this.dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

        WindowManager.LayoutParams lp = this.dialog.getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = (int) App.context().getResources().getDimension(R.dimen.soft_keyboard_min_height);
        lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
        lp.dimAmount = 0;

        return this.dialog;
    }
}

And I display the Dialog like that:
DialogFragment newFragment = SampleDialogFragment.newInstance();
.show(this.mActivity.getSupportFragmentManager(), "dialog");

The layout of the Dialog looks like that:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <FrameLayout
        android:id="@+id/emoji_keyboard"
        android:layout_width="match_parent"
        android:layout_height="@dimen/soft_keyboard_min_height"/>
</LinearLayout>

Where the FrameLayout should be replaced by the Library Fragment. I've tried to use the replace Fragment code after creating the Dialog in the Parent Activity and also overriding the show() method of the DialogFragment but I always get a view not found exception. How can I replace the framelayout in by the library fragment?
EDIT:
Follow it is the stack trace
02-13 22:47:50.613 25553-25606/br.com.instachat.demo D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-13 22:47:50.725 25553-25606/br.com.instachat.demo I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build: Nondeterministic_AU_msm8974_LA.BF.1.1.3_RB1__release_AU (I3193f6e94a)
                                                                   OpenGL ES Shader Compiler Version: E031.28.00.02
                                                                   Build Date: 10/09/15 Fri
                                                                   Local Branch: mybranch15039904
                                                                   Remote Branch: quic/LA.BF.1.1.3_rb1.2
                                                                   Local Patches: NONE
                                                                   Reconstruct Branch: NOTHING
02-13 22:47:50.727 25553-25606/br.com.instachat.demo I/OpenGLRenderer: Initialized EGL, version 1.4
02-13 22:47:50.757 25553-25553/br.com.instachat.demo E/RecyclerView: No adapter attached; skipping layout
02-13 22:47:50.791 25553-25623/br.com.instachat.demo I/RegIntentService: br.com.instachat.demo:string/token_received_successfully
02-13 22:47:50.796 25553-25553/br.com.instachat.demo E/RecyclerView: No adapter attached; skipping layout
02-13 22:47:51.395 25553-25553/br.com.instachat.demo I/RegIntentService: br.com.instachat.demo:string/token_sent_to_app_server_successfully
02-13 22:47:51.410 25553-25553/br.com.instachat.demo I/FragmentContacts: br.com.instachat.demo:string/contact_sync_success
02-13 22:47:53.010 25553-25553/br.com.instachat.demo I/FragmentContacts: br.com.instachat.demo:string/get_chatroomid_success
02-13 22:47:53.011 25553-25553/br.com.instachat.demo I/FragmentContacts:  chatroom retrieved (via request) has title: Hall 9000
02-13 22:47:53.066 25553-25553/br.com.instachat.demo I/AppCompatViewInflater: app:theme is now deprecated. Please move to using android:theme instead.
02-13 22:47:53.440 25553-25606/br.com.instachat.demo D/OpenGLRenderer: endAllActiveAnimators on 0xb82bf2a0 (LinearLayout) with handle 0xb83b6700
02-13 22:47:53.952 25553-25553/br.com.instachat.demo E/FragmentManager: No view found for id 0x7f0d00e3 (br.com.instachat.demo:id/emoji_keyboard) for fragment EmojiconsFragment{d8f31ba #1 id=0x7f0d00e3}
02-13 22:47:53.952 25553-25553/br.com.instachat.demo E/FragmentManager: Activity state:
02-13 22:47:53.953 25553-25553/br.com.instachat.demo D/FragmentManager:   Local FragmentActivity a698ff2 State:
02-13 22:47:53.957 25553-25553/br.com.instachat.demo D/FragmentManager:     mCreated=truemResumed=true mStopped=false mReallyStopped=false
02-13 22:47:53.957 25553-25553/br.com.instachat.demo D/FragmentManager:     mLoadersStarted=true
02-13 22:47:53.957 25553-25553/br.com.instachat.demo D/FragmentManager:   Active Fragments in 6fb086b:
02-13 22:47:53.957 25553-25553/br.com.instachat.demo D/FragmentManager:     #0: SampleDialogFragment{3355fc8 #0 dialog}
02-13 22:47:53.957 25553-25553/br.com.instachat.demo D/FragmentManager:       mFragmentId=#0 mContainerId=#0 mTag=dialog
02-13 22:47:53.957 25553-25553/br.com.instachat.demo D/FragmentManager:       mState=5 mIndex=0 mWho=android:fragment:0 mBackStackNesting=0
02-13 22:47:53.957 25553-25553/br.com.instachat.demo D/FragmentManager:       mAdded=true mRemoving=false mResumed=true mFromLayout=false mInLayout=false
02-13 22:47:53.957 25553-25553/br.com.instachat.demo D/FragmentManager:       mHidden=false mDetached=false mMenuVisible=true mHasMenu=false
02-13 22:47:53.957 25553-25553/br.com.instachat.demo D/FragmentManager:       mRetainInstance=false mRetaining=false mUserVisibleHint=true
02-13 22:47:53.957 25553-25553/br.com.instachat.demo D/FragmentManager:       mFragmentManager=FragmentManager{6fb086b in HostCallbacks{d98e861}}
02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager:       mHost=android.support.v4.app.FragmentActivity$HostCallbacks@d98e861
02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager:     #1: EmojiconsFragment{d8f31ba #1 id=0x7f0d00e3}
02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager:       mFragmentId=#7f0d00e3 mContainerId=#7f0d00e3 mTag=null
02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager:       mState=0 mIndex=1 mWho=android:fragment:1 mBackStackNesting=0
02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager:       mAdded=true mRemoving=false mResumed=false mFromLayout=false mInLayout=false
02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager:       mHidden=false mDetached=false mMenuVisible=true mHasMenu=false
02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager:       mRetainInstance=false mRetaining=false mUserVisibleHint=true
02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager:       mFragmentManager=FragmentManager{6fb086b in HostCallbacks{d98e861}}
02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager:       mHost=android.support.v4.app.FragmentActivity$HostCallbacks@d98e861
02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager:       mArguments=Bundle[{useSystemDefaults=false}]
02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager:   Added Fragments:
02-13 22:47:53.958 25553-25553/br.com.instachat.demo D/FragmentManager:     #0: SampleDialogFragment{3355fc8 #0 dialog}
02-13 22:47:53.959 25553-25553/br.com.instachat.demo D/FragmentManager:     #1: EmojiconsFragment{d8f31ba #1 id=0x7f0d00e3}
02-13 22:47:53.959 25553-25553/br.com.instachat.demo D/FragmentManager:   FragmentManager misc state:
02-13 22:47:53.959 25553-25553/br.com.instachat.demo D/FragmentManager:     mHost=android.support.v4.app.FragmentActivity$HostCallbacks@d98e861
02-13 22:47:53.959 25553-25553/br.com.instachat.demo D/FragmentManager:     mContainer=android.support.v4.app.FragmentActivity$HostCallbacks@d98e861
02-13 22:47:53.959 25553-25553/br.com.instachat.demo D/FragmentManager:     mCurState=5 mStateSaved=false mDestroyed=false
02-13 22:47:53.959 25553-25553/br.com.instachat.demo D/FragmentManager:   View Hierarchy:
02-13 22:47:53.959 25553-25553/br.com.instachat.demo D/FragmentManager:     com.android.internal.policy.PhoneWindow$DecorView{f889320 V.ED.... ... 0,0-1080,1920}
02-13 22:47:53.959 25553-25553/br.com.instachat.demo D/FragmentManager:       android.widget.LinearLayout{5a1ae9e V.E..... ... 0,0-1080,1776}
02-13 22:47:53.962 25553-25553/br.com.instachat.demo D/FragmentManager:         android.view.ViewStub{ceeaf86 G.E..... ... 0,0-0,0 #10203ab android:id/action_mode_bar_stub}
02-13 22:47:53.962 25553-25553/br.com.instachat.demo D/FragmentManager:         android.widget.FrameLayout{3b1ca13 V.E..... ... 0,72-1080,1776}
02-13 22:47:53.962 25553-25553/br.com.instachat.demo D/FragmentManager:           android.support.v7.widget.FitWindowsLinearLayout{bf70450 V.E..... ... 0,0-1080,1704 #7f0d0080 app:id/action_bar_root}
02-13 22:47:53.962 25553-25553/br.com.instachat.demo D/FragmentManager:             android.support.v7.widget.ViewStubCompat{2bfc047 G.E..... ... 0,0-0,0 #7f0d0081 app:id/action_mode_bar_stub}
02-13 22:47:53.962 25553-25553/br.com.instachat.demo D/FragmentManager:             android.support.v7.widget.ContentFrameLayout{15d6649 V.E..... ... 0,0-1080,1704 #1020002 android:id/content}
02-13 22:47:53.962 25553-25553/br.com.instachat.demo D/FragmentManager:               android.widget.RelativeLayout{f64fb4e V.E..... ... 0,0-1080,1704 #7f0d0094 app:id/activity_canvas}
02-13 22:47:53.962 25553-25553/br.com.instachat.demo D/FragmentManager:                 android.support.design.widget.AppBarLayout{ee4f46f V.E..... ... 0,0-1080,168 #7f0d0095 app:id/toolbar_wrapper}
02-13 22:47:53.962 25553-25553/br.com.instachat.demo D/FragmentManager:                   android.support.v7.widget.Toolbar{6d0157c V.E..... ... 0,0-1080,168 #7f0d0096 app:id/toolbar}
02-13 22:47:53.962 25553-25553/br.com.instachat.demo D/FragmentManager:                     android.widget.RelativeLayout{c997e5a V.E..... ... 168,0-528,168}
02-13 22:47:53.962 25553-25553/br.com.instachat.demo D/FragmentManager:                       com.mikhaellopez.circularimageview.CircularImageView{d196b08 V.ED.... ... 0,15-135,152 #7f0d0097 app:id/thumbnail}
02-13 22:47:53.962 25553-25553/br.com.instachat.demo D/FragmentManager:                       android.widget.LinearLayout{576688b V.E..... ... 150,27-360,141}
02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager:                         android.support.v7.widget.AppCompatTextView{dc70d68 V.ED.... ... 0,0-210,65 #7f0d0098 app:id/name}
02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager:                         android.support.v7.widget.AppCompatTextView{a469581 V.ED.... ... 0,65-99,114 #7f0d0099 app:id/status}
02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager:                     android.widget.ImageButton{70d1e05 VFED..C. ... 0,0-168,168}
02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager:                     android.support.v7.widget.ActionMenuView{48ca098 V.E..... ... 816,0-1080,168}
02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager:                       android.support.v7.view.menu.ActionMenuItemView{e995357 VFED..CL ... 0,12-144,156 #7f0d00f2 app:id/action_attach_media}
02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager:                       android.support.v7.widget.ActionMenuPresenter$OverflowMenuButton{41af862 VFED..C. ... 144,12-264,156}
02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager:                 android.support.v7.widget.RecyclerView{4612626 VFE..... F.. 0,168-1080,1506 #7f0d009a app:id/messages}
02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager:                 android.widget.LinearLayout{e610267 V.E..... ... 0,1506-1080,1704 #7f0d009b app:id/bottomLayoutWrapper}
02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager:                   android.widget.LinearLayout{b39814 V.E..... ... 24,24-1056,174}
02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager:                     android.widget.LinearLayout{84608bd V.E..... ... 0,0-882,150}
02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager:                       android.widget.LinearLayout{ba97eb2 V.E...C. ... 1,0-145,150 #7f0d00da app:id/emojiButtonWrapper}
02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager:                         android.support.v7.widget.AppCompatImageView{b715e03 V.ED.... .S. 36,39-108,111 #7f0d00db app:id/emojiButton}
02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager:                       com.rockerhieu.emojicon.EmojiconEditText{33c2180 VFED..CL ... 145,0-822,150 #7f0d00b7 app:id/message}
02-13 22:47:53.963 25553-25553/br.com.instachat.demo D/FragmentManager:                       android.widget.LinearLayout{bcf73b9 V.E..... ... 822,38-822,111}
02-13 22:47:53.964 25553-25553/br.com.instachat.demo D/FragmentManager:                         android.widget.LinearLayout{624b074 VFE..... ... 0,0-0,0}
02-13 22:47:53.964 25553-25553/br.com.instachat.demo D/FragmentManager:                         android.support.v7.widget.AppCompatAutoCompleteTextView{6acd3fe VFED..CL ... 0,0-0,73 #7f0d00ec app:id/autotext}
02-13 22:47:53.964 25553-25553/br.com.instachat.demo D/FragmentManager:                     android.support.v7.widget.AppCompatImageButton{4a1d75f VFED..C. ... 882,0-1032,150 #7f0d00dc app:id/send}
02-13 22:47:53.964 25553-25553/br.com.instachat.demo D/FragmentManager:       android.view.View{e881223 V.ED.... ... 0,1776-1080,1920 #1020030 android:id/navigationBarBackground}
02-13 22:47:53.964 25553-25553/br.com.instachat.demo D/FragmentManager:       android.view.View{4ba94d9 V.ED.... ... 0,0-1080,72 #102002f android:id/statusBarBackground}
02-13 22:47:53.964 25553-25553/br.com.instachat.demo D/AndroidRuntime: Shutting down VM
02-13 22:47:53.968 25553-25553/br.com.instachat.demo E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: br.com.instachat.demo, PID: 25553
                                                                       java.lang.IllegalArgumentException: No view found for id 0x7f0d00e3 (br.com.instachat.demo:id/emoji_keyboard) for fragment EmojiconsFragment{d8f31ba #1 id=0x7f0d00e3}
                                                                           at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1059)
                                                                           at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
                                                                           at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
                                                                           at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
                                                                           at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
                                                                           at android.os.Handler.handleCallback(Handler.java:746)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                           at android.os.Looper.loop(Looper.java:148)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

SOLVED

I was able to manage the issue by using the code below:
public class SampleDialogFragment extends DialogFragment {

    static SampleDialogFragment newInstance() {
        SampleDialogFragment f = new SampleDialogFragment();
        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_NoTitleBar);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.rsc_emoji_keyboard, container, false);

        this.getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
        this.getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
        this.getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        this.getDialog().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

        WindowManager.LayoutParams lp = this.getDialog().getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = (int) App.context().getResources().getDimension(R.dimen.soft_keyboard_min_height);
        lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
        lp.dimAmount = 0;

        getChildFragmentManager()
                .beginTransaction()
                .replace(R.id.emoji_keyboard, EmojiconsFragment.newInstance(false))
                .commit();

        return v;
    }
}


Q: convert hex to decimal with awk incorrect (with --non-decimal-data or strtonum) awk hex to decimal result is incorrect, not equal with bash/python
echo 0x06375FDFAE88312A |awk --non-decimal-data '{printf "%d\n",$1}'

or
echo 0x06375FDFAE88312A |awk '{printf "%d\n",strtonum($1)}'

the result is 447932102257160448， but with python the result is 447932102257160490
python -c "print int('0x06375FDFAE88312A', 16)"

A: You need to use --bignum option, as this answer suggests. (Supported in gawk since version 4.1).
echo 0x06375FDFAE88312A |awk --bignum '{printf "%d\n",strtonum($1)}'

echo 0x06375FDFAE88312A |awk --bignum --non-decimal-data '{printf "%d\n",$1}'

The problem is that AWK typically uses double floating point number to represent numbers by default, so there is a limit on how many exact digits can be stored that way.


Q: TSQL getting record count and records in single query I got this tasks table that has TODO items. We are retrieving the todo items and the count of Finished, Pending tasks using separate query in single stored procedure even though it is querying from same table. Here is the query,
select
TaskName 'Task/TaskName',
CASE IsDone WHEN '1' THEN 'True' ELSE 'False' END 'Task/IsDone',
(
 SELECT COUNT(*) FROM Tasks WHERE IsDone = '1'
) 'CompletedCount'
FROM Tasks FOR XML PATH('Tasks')

here is the output
'<Tasks>
    <Task>
        <TaskName>Write a email to Mayor<TaskName>
        <IsDone>True</IsDone>
        <CompletedCount>2<CompletedCount>
    </Task>
</Tasks>'

CompletedCount is present in each Task which is unnecessary  also is there anyway i can query the count too without explicitly writing this      SELECT COUNT(*) FROM Tasks WHERE IsDone = '1'
How do i get a output as below
'<Tasks>
    <CompletedCount>2<CompletedCount>
    <Task>
        <TaskName>Write a email to Mayor<TaskName>
        <IsDone>True</IsDone>
    </Task>
    <Task>
        <TaskName>Organize Campaign for website<TaskName>
        <IsDone>False</IsDone>
    </Task>
</Tasks>'

A: select (
          select count(*)
          from Tasks
          where IsDone = 1
          for xml path('CompletedCount'), type
       ),
       (
          select TaskName,
                 case IsDone
                   when 1 then 'True'
                   else 'False'
                 end as IsDone
          from Tasks
          for xml path('Task'), type
       )
for xml path('Tasks')

Update:
You can do it with a singe select if you first build your task list and then query the XML for the completed count. I doubt this will be any faster than using two select statements.
;with C(Tasks) as
(
  select TaskName,
         case IsDone
           when 1 then 'True'
           else 'False'
         end as IsDone
  from Tasks
  for xml path('Task'), type
)
select C.Tasks.value('count(/Task[IsDone = "True"])', 'int') as CompletedCount,
       C.Tasks
from C
for xml path('Tasks')

A: You can use type to calculate part of the XML in a subquery:
declare @todo table (TaskName varchar(50), IsDone bit)
insert @todo values ('Buy milk',1)
insert @todo values ('Send thank you note',1)

select  sum(case when isdone = 1 then 1 end) as 'CompletedCount'
,       (
        select  TaskName 'TaskName'
        ,       case when isdone = 1 then 'True' else 'False' end 'IsDone'
        from    @todo
        for xml path('Task'), type
        ) as 'TaskList'
from    @todo
for xml path('Tasks')

This prints:
<Tasks>
    <CompletedCount>2</CompletedCount>
    <TaskList>
        <Task>
            <TaskName>Buy milk</TaskName>
            <IsDone>True</IsDone>
        </Task>
        <Task>
            <TaskName>Send thank you note</TaskName>
            <IsDone>True</IsDone>
        </Task>
    </TaskList>
</Tasks>


Q: Removing Singularity of real bounded harmonic in punctured disk.
If $u(z)$ is real harmonic and bounded in the punctured disk $0<|z-z_0|<R.$ Show that $\lim_{z\to z_0} u(z)$ exists.

I already know Complex analytic function $f$ which has singularity $z_0$ and bounded on some deleted neighborhood of $z_0$, Then $\lim_{z\to z_0} f(z)$ exists and $f$ can be defined at $z_0$ so that it is analytic at $z_0$.


Q: Надо выбрать из матрицы диагональные элементы Пытаюсь выбрать из матрицы элементы на главной диагонали с тем, чтобы следом реализовать функционал расчета определителя матрицы по формуле:

a11*a22*a33 + a12*a23*a31 + a21*a13*a32 - a31*a22*a13 - a12*a21*a33 - a11*a23*a32.

В результате обхода строк и колонок матрицы получаю ошибку:

arrays used as indices must be of integer (or boolean) type

То  есть:

массивы, используемые в качестве индексов, должны быть целочисленного
(или логического) типа.

Почитал: пишут, что проблема в пустом массиве; советуют явно в нем задать тип float (вроде того: list_plus_1=np.array([], dtype=float)), однако не работает. Есть идеи, как записать в пустой список диагональные элементы?
import numpy as np
def det(matrix):
    list_plus_1=np.array([])
    for rows in matrix[:,:3]:
        for columns in matrix[rows]:
            if columns == matrix[columns][columns]:
                list_plus_1.append(columns)
                print(list_plus_1)

matrix = np.array([[3.8, 6.7, -1.2, 5.2],
                   [6.4, 1.3, -2.7, 3.8],
                   [2.4, -4.5, 3.5, -0.6]])

det(matrix)

A: import numpy as np

matrix = np.array([[3.8, 6.7, -1.2, 5.2],
                   [6.4, 1.3, -2.7, 3.8],
                   [2.4, -4.5, 3.5, -0.6]])
print(np.diag(matrix))

[3.8 1.3 3.5]

np.diag может принимать параметры. читайте документацию.

A: def det(matrix):
    list_diag = []
    for i in range(len(matrix)):
        list_diag.append(matrix[i][i])
    return list_diag

A: Реализовал вот такой код
def det(matrix):
    list_plus_1=[]
    for nrow, row in enumerate(matrix[:,:3]):
        elem = row[nrow]
        list_plus_1.append(elem)
    print(list_plus_1)


Q: HID reports/scan codes for iPhone's/iPad's home button I'm creating a very simple Arduino BT keyboard for iOS using a RN-42-HID Bluetooth module. I've been able to connect to an iPad and send it a few HID reports.
So far, I can make the cursor go left, right, up and down, as well as select a certain app. Yay! I do this using the HID raw reports as detailed by Roving Network's HID manual.
I've been trying to figure out how to make my iPad go to the home screen, or change the page. When I connect with a regular BT keyboard, with VoiceOver enabled, the BT keyboard combination of "ctrl + alt + H" makes the iPad return to the home page.
When I send the corresponding HID raw report, the iPad doesn't return home.
const byte HOME1[] = { //equivalent to keyboard ctrl + opt/alt + h
  0xFD,0x09,0x01,0x05,0x00,0x0B,0x00,0x00,0x00,0x00,0x00};

It sees the "H", and prints "H" when I have a text field open, but it just doesn't return to the home page.
I've also tried sending the modifier keys just as a combination of 3 scan codes at the same time, but that didn't work on the iPad, either.
const byte HOME2[] = { //equivalent to keyboard ctrl + opt/alt + h
  0xFD,0x09,0x01,0x00,0x00,0xE0,0xE2,0x0B,0x00,0x00,0x00};

Am I sending the report in the right format? Am I sending the right scan codes?
Even if you don't have the actual scan code, it would be nice if there was a way to figure out what code activates the home page. Does anyone know how I can find the scan code for the home button (and for page turn, which also involves the alt button)?

A: I had a similar issue but with a different combination of keys. I found that i had to split the action into 3 steps: Ctrl+alt+ "letter", then Ctrl+alt, then all buttons released. So just looking at your code, maybe try sending this sequence:
0xFD,0x09,0x01,0x05,0x00,0x0B,0x00,0x00,0x00,0x00,0x00 //ctrl + alt + h
0xFD,0x09,0x01,0x05,0x00,0x00,0x00,0x00,0x00,0x00,0x00 //ctrl + alt
0xFD,0x09,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 //all released.

A: I'm not sure of a raw report, but I did manage it with [0xFD,0x03,0x03,0x01,0x00] (down), and [0xFD,0x03,0x03,0x00,0x00] (up)


Q: Use the same object animator property (translationx) twice on one object at the same time I have spent the entire day trying to figure this out. I have tried a plethora of code combinations but none of them want to work. Well technically they do work but not the way I'm wanting it to. If I add translationY property it works. I'm basically wanting run 2 animations, both translationx, on a single object at the same time. The object should go from left to right for the entire width of the screen and be moving back and forth a short distance at the same time. So the main question is, is it possible to achieve this or is it not possible to use the same property with an AnimatorSet at the same time?
here is the current code I'm working with:
private void _ballLevel20Animation () {
    move1.cancel();
    int center = (board.getMeasuredWidth() / 2);
    int lr = board.getMeasuredWidth();
    final float left = Float.valueOf(100 - center);
    final float right = Float.valueOf(center - 100);
    int center1 = (board.getMeasuredWidth() / 6);
    final float left1 = Float.valueOf(100 - center);
    final float right1 = Float.valueOf(center - 100);
    move1.setTarget(ball);
    move1.setPropertyName("translationX");
    move1.setFloatValues(left, right);
    move1.setRepeatCount(ObjectAnimator.INFINITE);
    move1.setDuration((int)(ball_duration_increa));
    move1.setRepeatMode(ValueAnimator.REVERSE);
    bounce_ani.setTarget(ball);
    bounce_ani.setPropertyName("translationX");
    bounce_ani.setFloatValues((float)(SketchwareUtil.getDip(getApplicationContext(), (int)(-20))), (float)(SketchwareUtil.getDip(getApplicationContext(), (int)(20))));
    bounce_ani.setRepeatCount(ObjectAnimator.INFINITE);
    bounce_ani.setDuration((int)(ball_duration_increa / 6));
    bounce_ani.setRepeatMode(ValueAnimator.REVERSE);
    AnimatorSet animatorSet = new AnimatorSet();

    animatorSet.play(bounce_ani).with(move1);

    animatorSet.start();
    /*bounce_ani.setFloatValues(right1, left1);*/
}

A: You could try adding an animation listener to the animation. In the listener, there is onAnimationEnd() which gets called when the animation is done. Here, you may call succeeding animations such that they appear that they are chained.
Android Guide on Animation - Animation Listeners


Q: MySQL: добавить новую запись в таблицу с обновлением значений существующих записей Здравствуйте!
Есть массив картинок
$usr_imgs = array('1.jpg','3.jpg','8.jpg','9.jpg','11.jpg');

Массив добавлен в таблицу, ключами которого является поле ord, а значения - photo_name:
+----+------------+-----+
| id | photo_name | ord |
+----+------------+-----+
| 13 | 1.jpg      |   0 |
| 14 | 3.jpg      |   1 |
| 15 | 8.jpg      |   2 |
| 16 | 9.jpg      |   3 |
| 17 | 11.jpg     |   4 |
+----+------------+-----+

В массиве $usr_imgs пользователь добавил ещё одну картинку, например '5.jpg'. Массив теперь имеет следующий вид:
$usr_imgs = array('1.jpg','3.jpg','5.jpg' ,'8.jpg','9.jpg','11.jpg');

Вопрос заключается в том, как можно одним запросом MySQL перезаписать ключи для значений, которые уже существуют в таблице? (или одним не получится?)
А новую картинку 5.jpg добавить как новую запись с соответствующим ключом.
Т.е. чтобы получилась такая таблица:
+----+------------+-----+
| id | photo_name | ord |
+----+------------+-----+
| 13 | 1.jpg      |   0 |
| 14 | 3.jpg      |   1 |
| 15 | 8.jpg      |   3 |
| 16 | 9.jpg      |   4 |
| 17 | 11.jpg     |   5 |
| 18 | 5.jpg      |   2 |
+----+------------+-----+


Q: CSS Transitions on tab load - bug I am creating a home screen and I have 3 tabs that you can go between on the home screen. When you click one all the li's within the tab transition in to the page but if you click between the tabs quickly then they don't always load. This only seems to effect Chrome on pc and mac and sometimes safari on mac. Fine on firefox on pc and mac.
http://codepen.io/2ne/pen/1f7dbb81f464fb5b0e1a4f5bacc30a56
Tab JS
$(document).ready(function() {
  $('nav li').click(function(){
    $('nav li').removeClass('active');
    $(this).addClass('active');
    $('.tab').removeClass('active');
    $('#' + $(this).attr('data-tab')).addClass('active');
  });
});

Portion of css
.tab-content .tab li {
  opacity: 0;
  transform: translatey(-50px) scale(0);
}
.tab-content .tab.active li {
  transition: all 500ms ease;
  transform-origin: top center;
  transform: translatey(0) scale(1);
  opacity: 1;
}
@for $i from 1 through 50 {
  .tab-content .tab.active li:nth-child(#{$i}) {
    transition-delay: (#{$i * 0.1}s);
  }
}

A: You need to add vendor specific values for transform and transition properties. Below is the modified CSS:
  $headerColour: #456878; $headerHeight: 58px; $headerLineHeight: $headerHeight - 2px; @import url(http://fonts.googleapis.com/css?family=Lato:100,300,400,700,900); .cf:after {
            clear: both;
            content: " ";
            display: table;
        }

        body {
            background: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/12596/bg.png");
            background-attachment: fixed;
            -ms-background-size: contain;
            background-size: contain;
            color: #fff;
            font-family: "Lato";
            font-size: 18px;
            font-weight: 300;
            overflow-y: scroll;
        }

        header {
            background: $headerColour;
            height: $headerHeight;
            position: relative;
        }

            header li {
                position: absolute;
                top: 0;
                line-height: $headerLineHeight;
            }

                header li.logo {
                    left: 20px;
                }

                header li.user {
                    right: 20px;
                }

        .wrapper {
            position: absolute;
            top: 120px;
            left: 0;
            right: 0;
            margin: auto;
            width: 80%;
        }

        nav {
            margin-bottom: 50px;
            margin-left: 20px;
        }

            nav li {
                color: rgba(255, 255, 255, 0.75);
                cursor: pointer;
                float: left;
                font-size: 20px;
                margin-right: 60px;
                -webkit-transition: color 500ms ease 0s;
                -moz-transition: color 500ms ease 0s;
                -ms-transition: color 500ms ease 0s;
                -o-transition: color 500ms ease 0s;
                transition: color 500ms ease 0s;
                width: 100px;
            }

                nav li:not(.active):hover,
                nav li.active {
                    color: rgba(255, 255, 255, 1);
                }

                nav li.active {
                    font-size: 22px;
                    font-weight: 400;
                }

        .tab-content .tab {
            position: absolute;
            margin-bottom: 100px;
            visibility: hidden;
        }

            .tab-content .tab.active {
                visibility: visible;
            }

            .tab-content .tab > ul {
                margin-bottom: 100px;
            }

            .tab-content .tab li {
                background: #fff;
                height: 200px;
                width: 200px;
                float: left;
                background: #fff;
                margin: 20px;
                -ms-border-radius: 30px;
                border-radius: 30px;
                -ms-opacity: 0;
                opacity: 0;
                -webkit-transform: translatey(-50px) scale(0);
                -moz-transform: translatey(-50px) scale(0);
                -ms-transform: translatey(-50px) scale(0);
                -o-transform: translatey(-50px) scale(0);
                transform: translatey(-50px) scale(0);
            }

            .tab-content .tab.active li {
                -webkit-transition: all 500ms ease;
                -moz-transition: all 500ms ease;
                -ms-transition: all 500ms ease;
                -o-transition: all 500ms ease;
                transition: all 500ms ease;
                -webkit-transform-origin: top center;
                -moz-transform-origin: top center;
                -ms-transform-origin: top center;
                -o-transform-origin: top center;
                transform-origin: top center;
                -webkit-transform: translatey(0) scale(1);
                -moz-transform: translatey(0) scale(1);
                -ms-transform: translatey(0) scale(1);
                -o-transform: translatey(0) scale(1);
                transform: translatey(0) scale(1);
                -ms-opacity: 1;
                opacity: 1;
            }

        @for $i from 1 through 50 {
            .tab-content .tab.active li:nth-child(#{$i}) {
                transition-delay: (#{$i * 0.1}s);
            }
        }

Code Pen: http://codepen.io/anon/pen/gIDsv


Q: lines, where the last value for $6 = 0? How do I print all lines, where the last value for the line and print $6 = 0?
snap --list --all | awk '{print $1, $2, $3, $6}'

Example of desired output. Notice the last character on each line is 0 (ZERO). These would be the only lines I wish to see.... >>>
VDC-NIM-VMFS-SOFTWARE VDC-NIM-VMFS-ITNI-DEFAULT-Weekly-2018-09-11::06:50:00.000 1048576 0
VDC-NIM-VMFS-SOFTWARE VDC-NIM-VMFS-ITNI-DEFAULT-Daily-2018-09-11::06:45:00.000 1048576 0
VDC-NIM-VMFS-SOFTWARE VDC-NIM-VMFS-ITNI-DEFAULT-Daily-2018-09-10::06:45:00.000 1048576 0

A: You can add a condition to the awk commands
snap --list --all | awk '$6 == 0 {print $1, $2, $3, $6}'


Q: Flutter & Firestore - problem about "startAfter" pagination I am able to use "startAfter" and "limit" to do pagination but it have bug.
For example, in Firestore DB I have 7 records:
{"title": "item1", "create_datetime": "2018-11-11 11:11:11"}
{"title": "item2", "create_datetime": "2018-11-11 11:11:11"}
{"title": "item3", "create_datetime": "2018-11-11 11:11:11"}
{"title": "item4", "create_datetime": "2018-11-11 11:11:11"}
{"title": "item5", "create_datetime": "2018-11-11 11:11:11"}
{"title": "item6", "create_datetime": "2018-11-11 11:11:11"}
{"title": "item7", "create_datetime": "2018-12-22 22:22:22"}

When the page size is 5, first page is ok because I used:
.orderBy('create_datetime').limit(5)

It gives me item 1-5.
When it load second page, I used:
.orderBy('create_datetime').startAfter(['2018-11-11 11:11:11']).limit(5)

The problem is that the second page result had item7 only, item6 was disappeared.
"startAt" have the same problem too.
I really hope it has "offset" function. Does anyone have solution?

A: Your query will always return 'item7' because you always starting after 2018-11-11 11:11:11 so it will ignore all the other items and go to the last 2018-11-11 11:11:11 and skip from there. You need to get the last item returned and keep a reference to it, then on your startAfter use the document reference to start after. Usually, flutter's startAfter requires a list to keep a reference to it.
Look at Firebase query cursors

A: Currently flutter don't support startAfter(lastDocFetched) or startAt(anyDoc).
This is required as you said it starts with the string matching values, not at a particular document.


Q: query nutch 2 table result from cassandra 2 dose not look right I am using Nutch 2.2.1 and Cassandra 2 to craw pages. for a test i just inject one url to Cassandra and explore the database.
Using CQL i can query the table in the webpage keyspace
cqlsh:simplex> select * from webpage.f;
 key                                  | column1 | value
--------------------------------------+---------+--------------------
 0x6564752e6373752e7777773a687474702f |  0x6669 |         0x00278d00
 0x6564752e6373752e7777773a687474702f |    0x73 |         0x3f800000
 0x6564752e6373752e7777773a687474702f |  0x7473 | 0x00000145a266703e

which is fine if i convert those hex bytes to string. the key will be the reverted url.
then i write java code to read the table f using datastax java driver 2 (http://www.datastax.com/documentation/developer/java-driver/2.0/java-driver/whatsNew2.html)
i followed the sample code
Cluster cluster = Cluster.builder().addContactPoint("10.20.104.181").build();
Session session = cluster.connect();
ResultSet results = session.execute("SELECT * FROM webpage.f");
for (Row row : results) {

            System.out.println("Key");
        System.out.println(toStrFromByteBuffer(row.getBytes("key")));
        System.out.println("column1");
        System.out.println(toStrFromByteBuffer(row.getBytes("column1")));
        System.out.println("value");
        System.out.println(toStrFromByteBuffer(row.getBytes("value")));

}
cluster.close();

public static String toStrFromByteBuffer(ByteBuffer buffer)
    {
        byte[] ar=buffer.array();
        System.out.println(ar.length);
        return new String(ar,Charset.forName("UTF-8"));
    }

the result is below. You can see row.getBytes("key") returns a whole row data not a specific column value.
Could some master help on this?

A: Nutch stores its data in the f column family as BytesType. The column names are stored as UTF8Type.
If you want to get the data as a String you have to convert it first. A row is completely stored in the ByteBuffer. In your example you convert the whole byte buffer to String what gives you the whole row. When you select one row, you get the current position an limit of that row. So you have to read from begin:buffer current pointer position to buffer limit. For example to get the websites content in the "cnt" field:
// This is the byte buffer you get from selecting column "cnt"
ByteBuffer buffer;
int length = buffer.limit() - buffer.position();

byte[] cellValue = new byte[length];

buffer.get(cellValue, 0, length);

return new String(cellValue, Charset.forName("UTF-8"));


Q: Need help on choosing locks for thread synchronization I have several modifying threads and some reading threads, which all access the global variable X. I want to make my synchronization policy like this:
When a thread try to modify X, it will require a lock first, and several modifying threads can have several locks required.
When a thread try to read X, it must wait until all the modifying threads drop their locks.
Is there any solution to this situation in linux pthread library? Many thanks

A: You are looking for a read/write lock (or reader-writer lock).  I believe there is one in pthreads (pthread_rwlock_*).


Q: Accessing a class method from within an Active Record scope? I am having issues with the scope in this model and I'm at a loss at how best to fix it. I would like to call the distinct_mechanics_sql from within the scope to keep things cleaner, but when I run this I get an "undefined local variable or method" error. Here is the model:
class Mechanics < ActiveRecord::Base
  scope :with_moz, -> { joins("JOIN (#{distinct_mechanics_sql}) mh ON mh.mechanic_id = mechanics.id") }

  def distinct_mechanics_sql
    """
    SELECT DISTINCT ON (mechanic_id) *
    FROM checkups
    ORDER BY mechanic_id, updated_at DESC
    """
  end

end

Any help would be greatly appreciated!

A: Scopes are same as class methods, so within the scope you are implicitly call another class methods. And your distinct_mechanics_sql is an instance method, to use it inside a scope declare it as:
def self.distinct_mechanics_sql

or
def Mechanics.distinct_mechanics_sql

or
class << self
  def distinct_mechanics_sql
    ...
  end
end