text:
Q: Get the title of a window of another program using the process name This question is probably quite basic but I'm having difficulty cracking it. I assume that I will have to use something in ctypes.windll.user32. Bear in mind that I have little to no experience using these libraries or even ctypes as a whole.
I have used this code to list all the window titles, but I have no idea how I am supposed to change this code to get a window title with a process name:
import ctypes

EnumWindows = ctypes.windll.user32.EnumWindows
EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))
GetWindowText = ctypes.windll.user32.GetWindowTextW
GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW
IsWindowVisible = ctypes.windll.user32.IsWindowVisible

titles = []
def foreach_window(hwnd, lParam):
    if IsWindowVisible(hwnd):
        length = GetWindowTextLength(hwnd)
        buff = ctypes.create_unicode_buffer(length + 1)
        GetWindowText(hwnd, buff, length + 1)
        titles.append(buff.value)
    return True
EnumWindows(EnumWindowsProc(foreach_window), 0)

print(titles)

This code is from https://sjohannes.wordpress.com/2012/03/23/win32-python-getting-all-window-titles/
If my question is unclear, I would like to achieve something like this (just an example - I'm not asking specifically about Spotify):
getTitleOfWindowbyProcessName("spotify.exe") // returns "Avicii - Waiting For Love" (or whatever the title is)

A complication that may arise, if there are multiple windows running with the same process name (e.g. multiple chrome windows)
Thank you.

EDIT: To clarify, I want some code that takes a process name and returns a (possibly empty) list of window titles owned by that process as strings.

A: Before everything, I want to point out [SO]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer). Read it before working with CTypes.
Here's what I meant in the comment:
import win32gui

def enumWindowsProc(hwnd, lParam):
    print win32gui.GetWindowText(hwnd)

win32gui.EnumWindows(enumWindowsProc, 0)

Below, I pasted the whole thing...it doesn't work on the PC that I am at right now, since I messed up with security settings (it's an XP!!!) and I get a bunch of Access denied (error code: 5) errors, but here it is.
code00.py:
#!/usr/bin/env python

import sys
import os
import traceback
import ctypes as ct
from ctypes import wintypes as wt
import win32con as wcon
import win32api as wapi
import win32gui as wgui
import win32process as wproc

def enumWindowsProc(hwnd, lParam):
    if (lParam is None) or ((lParam is not None) and (wproc.GetWindowThreadProcessId(hwnd)[1] == lParam)):
        text = wgui.GetWindowText(hwnd)
        if text:
            wStyle = wapi.GetWindowLong(hwnd, wcon.GWL_STYLE)
            if wStyle & wcon.WS_VISIBLE:
                print("%08X - %s" % (hwnd, text))

def enumProcWnds(pid=None):
    wgui.EnumWindows(enumWindowsProc, pid)

def enumProcs(procName=None):
    pids = wproc.EnumProcesses()
    if procName is not None:
        bufLen = 0x100

        _OpenProcess = ct.windll.kernel32.OpenProcess
        _OpenProcess.argtypes = (wt.DWORD, wt.BOOL, wt.DWORD)
        _OpenProcess.restype = wt.HANDLE

        _GetProcessImageFileName = ct.windll.psapi.GetProcessImageFileNameA
        _GetProcessImageFileName.argtypes = (wt.HANDLE, wt.LPSTR, wt.DWORD)
        _GetProcessImageFileName.restype = wt.DWORD

        _CloseHandle = ct.windll.kernel32.CloseHandle
        _CloseHandle.argtypes = (wt.HANDLE,)
        _CloseHandle.restype = wt.BOOL

        filteredPids = ()
        for pid in pids:
            try:
                hProc = _OpenProcess(wcon.PROCESS_ALL_ACCESS, 0, pid)
            except:
                print("Process [%d] couldn't be opened: %s" % (pid, traceback.format_exc()))
                continue
            try:
                buf = ct.create_string_buffer(bufLen)
                _GetProcessImageFileName(hProc, buf, bufLen)
                if buf.value:
                    name = buf.value.decode().split(os.path.sep)[-1]
                    #print("proc name:", name)
                    if name.lower() == procName.lower():
                        filteredPids += (pid,)
                else:
                    _CloseHandle(hProc)
                    continue
            except:
                print("Error getting process name: %s" % traceback.format_exc())
                _CloseHandle(hProc)
                continue
            _CloseHandle(hProc)
        return filteredPids
    else:
        return pids

def main(*argv):
    if argv:
        procName = argv[0]
    else:
        procName = None
    pids = enumProcs(procName)
    #print(pids)
    for pid in pids:
        enumProcWnds(pid)

if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.")
    sys.exit(rc)

Needless to say that:

*

*In order for this code to work, you need to run it as a privileged user (Administrator); at least SeDebugPrivilege ([MS.Docs]: Privilege Constants) is required.

*There might be surprises when the processes are running in 32 / 64 bit modes (the python process that you execute this code from, and the target processes enumerated by the code)

Update #0

*

*Replaced all CTypes calls by PyWin32 ones

*Improved algorithm

*Fixed error in previous version

code01.py:
#!/usr/bin/env python

import sys
import os
import traceback
import win32con as wcon
import win32api as wapi
import win32gui as wgui
import win32process as wproc

# Callback
def enum_windows_proc(wnd, param):
    pid = param.get("pid", None)
    data = param.get("data", None)
    if pid is None or wproc.GetWindowThreadProcessId(wnd)[1] == pid:
        text = wgui.GetWindowText(wnd)
        if text:
            style = wapi.GetWindowLong(wnd, wcon.GWL_STYLE)
            if style & wcon.WS_VISIBLE:
                if data is not None:
                    data.append((wnd, text))
                #else:
                    #print("%08X - %s" % (wnd, text))

def enum_process_windows(pid=None):
    data = []
    param = {
        "pid": pid,
        "data": data,
    }
    wgui.EnumWindows(enum_windows_proc, param)
    return data

def _filter_processes(processes, search_name=None):
    if search_name is None:
        return processes
    filtered = []
    for pid, _ in processes:
        try:
            proc = wapi.OpenProcess(wcon.PROCESS_ALL_ACCESS, 0, pid)
        except:
            #print("Process {0:d} couldn't be opened: {1:}".format(pid, traceback.format_exc()))
            continue
        try:
            file_name = wproc.GetModuleFileNameEx(proc, None)
        except:
            #print("Error getting process name: {0:}".format(traceback.format_exc()))
            wapi.CloseHandle(proc)
            continue
        base_name = file_name.split(os.path.sep)[-1]
        if base_name.lower() == search_name.lower():
            filtered.append((pid, file_name))
        wapi.CloseHandle(proc)
    return tuple(filtered)

def enum_processes(process_name=None):
    procs = [(pid, None) for pid in wproc.EnumProcesses()]
    return _filter_processes(procs, search_name=process_name)

def main(*argv):
    proc_name = argv[0] if argv else None
    procs = enum_processes(process_name=proc_name)
    for pid, name in procs:
        data = enum_process_windows(pid)
        if data:
            proc_text = "PId {0:d}{1:s}windows:".format(pid, " (File: [{0:s}]) ".format(name) if name else " ")
            print(proc_text)
            for handle, text in data:
                print("    {0:d}: [{1:s}]".format(handle, text))

if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.")
    sys.exit(rc)

Output:

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q031278590]> "e:\Work\Dev\VEnvs\py_pc064_03.07.06_test0\Scripts\python.exe" code01.py
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] 064bit on win32

PId 8048 windows:
    131462: [Program Manager]
PId 10292 windows:
    133738: [Skype]
PId 5716 windows:
    89659824: [python - Get the title of a window of another program using the process name - Stack Overflow - Google Chrome]
    132978: [Service Name and Transport Protocol Port Number Registry - Google Chrome]
    329646: [CristiFati/Prebuilt-Binaries: Various software built on various platforms. - Google Chrome]
    133078: [unittest — Unit testing framework — Python 3.8.2 documentation - Google Chrome]
    263924: [libssh2/libssh2 at libssh2-1.9.0 - Google Chrome]
    264100: [WNetAddConnection2A function (winnetwk.h) - Win32 apps | Microsoft Docs - Google Chrome]
    525390: [Understanding 4D -- The Tesseract - YouTube - Google Chrome]
    198398: [Workaround for virtual environments (VirtualEnv) by CristiFati · Pull Request #1442 · mhammond/pywin32 - Google Chrome]
    591586: [struct — Interpret bytes as packed binary data — Python 3.8.2 documentation - Google Chrome]
    263982: [Simulating an epidemic - YouTube - Google Chrome]
    329312: [SetHandleInformation function (handleapi.h) - Win32 apps | Microsoft Docs - Google Chrome]
    263248: [studiu functie faze - Google Search - Google Chrome]
    198364: [Lambda expressions (since C++11) - cppreference.com - Google Chrome]
PId 13640 windows:
    984686: [Total Commander (x64) 9.22a - NOT REGISTERED]
    44046462: [Lister - [c:\c\pula.txt]]
    4135542: [Lister - [e:\Work\Dev\CristiFati\Builds\Win\OPSWpython27\src\pywin32-b222\win32\src\win32process.i]]
    3873800: [Lister - [e:\Work\Dev\CristiFati\Builds\Win\OPSWpython27\src\pywin32-b222\win32\src\PyHANDLE.cpp]]
    29825332: [Lister - [E:\Work\Dev\Projects\DevTel\ifm\yosemite\GitLabA\yose\issues\buildnr\dependencies_200412.json]]
    8329240: [Lister - [e:\Work\Dev\Projects\DevTel\ifm\yosemite\src\svn\yosemite\CFATI_TRUNK_2\src\res\icpVerAppX.h]]
    985026: [Lister - [e:\Work\Dev\CristiFati\Builds\Win\OPSWpython27\src\pywin32-b222\win32\src\win32apimodule.cpp]]
PId 10936 windows:
    264744: [Junk - cristian.fati@devtelsoftware.com - Mozilla Thunderbird]
PId 10848 windows:
    1115842: [Registry Editor]
PId 6164 windows:
    264756: [Rocket.Chat]
PId 2716 windows:
    854508: [Skype]
    199310: [New tab and 5 more pages - Microsoft Edge]
PId 14936 windows:
    655466: [Administrator: C:\Windows\System32\cmd.exe]
PId 15132 windows:
    526852: [Administrator: Cmd (064) - "e:\Work\Dev\VEnvs\py_pc064_03.07.06_test0\Scripts\python.exe"]
PId 15232 windows:
    133918: [Microsoft Edge]
PId 9748 windows:
    68492: [Microsoft Edge]
PId 14968 windows:
    134146: [Microsoft Edge]
    68634: [Microsoft Edge]
PId 15636 windows:
    134208: [Microsoft Edge]
PId 16348 windows:
    1379450: [Microsoft Edge]
PId 15568 windows:
    68828: [Microsoft Edge]
    68788: [Microsoft Edge]
PId 16040 windows:
    265406: [Administrator: Cmd (032)]
PId 5792 windows:
    2034532: [e:\Work\Dev\StackOverflow\q031278590\code00.py - Notepad++ [Administrator]]
PId 12032 windows:
    69134: [Microsoft Edge]
PId 16200 windows:
    69146: [Microsoft Text Input Application]
PId 16224 windows:
    69184: [Microsoft Edge]
PId 5288 windows:
    265806: [Administrator: Cmd (064) - "e:\Work\Dev\VEnvs\py_pc032_03.07.06_test0\Scripts\python.exe"]
PId 16476 windows:
    265814: [Administrator: Cmd (064) - "e:\Work\Dev\VEnvs\py_pc064_03.08.01_test0\Scripts\python.exe"]
PId 16612 windows:
    331388: [Administrator: Cmd (064) - python]
PId 16796 windows:
    592540: [Administrator: Cmd (064)]
PId 16880 windows:
    264894: [Administrator: C:\Windows\System32\cmd.exe]
PId 17156 windows:
    69284: [Console1 - Microsoft Visual Studio (Administrator)]
PId 16636 windows:
    69396: [QtConsole0 - Microsoft Visual Studio  (Administrator)]
PId 18380 windows:
    69522: [Console0 - Microsoft Visual Studio (Administrator)]
PId 18108 windows:
    200528: [BlackBird - Microsoft Visual Studio (Administrator)]
PId 19476 windows:
    1052868: [pcbuild - Microsoft Visual Studio  (Administrator)]
PId 16680 windows:
    200924: [Yosemite - Microsoft Visual Studio  (Administrator)]
PId 16020 windows:
    201030: [-bash]
PId 6532 windows:
    200996: [-bash]
PId 13140 windows:
    266602: [-bash]
PId 6032 windows:
    790834: [-bash]
PId 8496 windows:
    8130950: [-bash]
PId 3208 windows:
    4198878: [-bash]
PId 19088 windows:
    528856: [-bash]
PId 12744 windows:
    266770: [-bash]
PId 3896 windows:
    201370: [-bash]
PId 11512 windows:
    1315422: [Yosemite - Microsoft Visual Studio  (Administrator)]
PId 20660 windows:
    267028: [Yosemite - Microsoft Visual Studio  (Administrator)]
PId 20684 windows:
    70554: [Microsoft Visual Studio  (Administrator)]
PId 14808 windows:
    201692: [Dependency Walker]
PId 13056 windows:
    5509836: [Oracle VM VirtualBox Manager]
PId 17756 windows:
    70802: [TIC2Vone.pdf - Adobe Acrobat Reader DC]
PId 14572 windows:
    267868: [Select Administrator: Powershell (064)]
PId 25588 windows:
    332550: [Administrator: Cmd (064)]
PId 20504 windows:
    463448: [Administrator: C:\Windows\System32\cmd.exe]
PId 24740 windows:
    2298466: [Administrator: C:\Windows\System32\cmd.exe - "e:\Work\Dev\VEnvs\py_pc064_03.07.06_test0\Scripts\python.exe"]
PId 25960 windows:
    2430020: [Utils [E:\Work\Dev\Utils] - ...\current\ifm\pe_ver.py - PyCharm (Administrator)]
PId 28836 windows:
    332582: [E:\Work\Dev\Projects\DevTel\ifm\yosemite\src\svn\yosemite - Log Messages - TortoiseSVN]
PId 29796 windows:
    4724788: [Administrator: C:\Windows\System32\cmd.exe]
PId 26344 windows:
    2883688: [Dependency Walker]
PId 34124 windows:
    242746876: [Administrator: C:\Windows\System32\cmd.exe]
PId 21972 windows:
    1317748: [Administrator: Cmd (064)]
PId 35060 windows:
    2563162: [Administrator: C:\Windows\System32\cmd.exe - "e:\Work\Dev\VEnvs\py_pc064_03.07.06_test0\Scripts\python.exe"  code00.py]
PId 14692 windows:
    102695792: [Device Manager]
PId 35776 windows:
    990338: [Process Explorer - Sysinternals: www.sysinternals.com [CFATI-5510-0\cfati] (Administrator)]
PId 33524 windows:
    656408: [PE Explorer - 30 day evaluation version]
    25368616: [PE Explorer]
PId 29488 windows:
    3218206: [Microsoft Edge]
PId 13184 windows:
    267896: [cfati-ubtu16x64-0 [Running] - Oracle VM VirtualBox]
PId 33716 windows:
    3932934: [Cheat Engine 7.0]
    73098: [Cheat Engine 7.0]

Done.

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q031278590]>
[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q031278590]> "e:\Work\Dev\VEnvs\py_pc064_03.07.06_test0\Scripts\python.exe" code01.py "notepad++.exe"
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] 064bit on win32

PId 5792 (File: [C:\Install\pc064\NP++\NP++\Version\notepad++.exe]) windows:
    2034532: [e:\Work\Dev\StackOverflow\q031278590\code00.py - Notepad++ [Administrator]]

Done.


text:
Q: Ptys (Pseudo terminals) internal buffer size I am trying to emulate both master and slave Ptys but don't know that what is the buffer limit and does it varies on different versions of Linux?
Is there any way(system call) to get the max size of buffer, master and slave use to read and write?

A: Anyways, I found the answer myself. I read and verified (with my program) the following line from the book "Kerrisk, Michael. The Linux Programming Interface". On Linux, the pseudoterminal capacity is about 4 kB in each direction (Master-->slave and slave --> master).

A: It depends.
I've empirically determined that this number changes across versions of Debian:
ptsbufsize.py:
#!/usr/bin/env python3
import os
from pty import openpty
from fcntl import fcntl, F_GETFL, F_SETFL
from itertools import count

def set_nonblock(fd):
    flags = fcntl(fd, F_GETFL)
    flags |= os.O_NONBLOCK
    fcntl(fd, F_SETFL, flags)

master, slave = openpty()

set_nonblock(slave)

for i in count():
    try:
        os.write(slave, b'a')
    except BlockingIOError:
        i -= 1
        break

print("pts write blocked after {} bytes ({} KiB)".format(i, i//1024))

Debian 8
$ uname -v
#1 SMP Debian 3.16.7-ckt11-1+deb8u6 (2015-11-09)

$ ./ptsbufsize.py
pts write blocked after 134144 bytes (131 kB)

Debian 9
$ uname -v
#1 SMP Debian 4.9.144-3.1 (2019-02-19)

$ ./ptsbufsize.py
pts write blocked after 19456 bytes (19 KiB)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Counting based on recent date sql I am trying to count unique users that made a transaction from whatever device they are register to.
Here is my query :
select Distinct
    username ,
    case
       when user_agent like '%Android%' then 'Android'
       when user_agent like '%iPhone%' OR user_agent like '%Iphone%' then     'IOS'
       else 'Internet Banking'
    end as type,
    min(time)
from
    activeUsers
group by
    (1, 2);

However, in the result set I get this :

I want for example user ujvs24hxen9/abdallah to be counted based on  the latest date , for example to be counted once only in internetbanking and not in internetbanking and ios.
How can I do this? I am using postgresql
Thanks!

A: Try this:
select Distinct username ,
Case When user_agent like '%Android%' then 'Android'
when user_agent like '%iPhone%' OR user_agent like '%Iphone%' then     'IOS'
else 'Internet Banking'
END as type , time
from activeUsers a1
where time = (select max(time) from activeUsers a2 where a1.username = a2.username)

I am assuming when you say 'latest' time that you mean max no min time.

A: Use PostgreSQL's DISTINCT ON (username) to get only one record per user. Use the ORDER BY clause to get the desired record per user (i.e. the latest) first:
select distinct on (username)
  username,
  case when user_agent like '%Android%' then 'Android'
       when user_agent like '%iPhone%'
         or user_agent like '%Iphone%' then  'IOS'
       else 'Internet Banking'
  end as type,
  time
from activeusers
order by username, time desc;

As to your own query:

*

*GROUP BY xyz means you want one result row per xyz. In your query you group by the first two columns, so you get a result row per user and type. But you only want a result row per user. Hence having type in your GROUP BY clause makes no sense.

*DISTINCT removes duplicate rows from the results. As you group by user and type and both of these columns get selected, there can be no duplicates; these two columns make each row distinct already, so applying DISTINCT on these rows is superfluous.

*And there is no place where you even try to find the latest time per user and use this to access the desired record. So obviously this query cannot work.

A: select distinct on (username)
    username,
    case
        when user_agent like '%Android%' then 'Android'
        when user_agent like '%iPhone%' OR user_agent like '%Iphone%' then 'IOS'
        else 'Internet Banking'
    end as type
    time
from activeUsers
order by username, time desc

A: You could use the row_number window function to just get the last transaction per user:
SELECT username, type
FROM   (SELECT username ,
               CASE WHEN user_agent LIKE '%Android%' THEN 'Android'
                    WHEN user_agent LIKE '%iPhone%' OR
                         user_agent LIKE '%Iphone%' THEN 'IOS'
                    ELSE 'Internet Banking'
        END AS type,
        time
        ROW_NUMBER() OVER (PARTITION BY username ORDER BY time DESC) AS rn
FROM    activeUsers) t
WHERE   rn = 1

A: An alternative to the answer given by @Mureinik would be to use a subquery to identify the latest time for each user, and then use it to restrict the original table to the records we actually want in the result set.
WITH cte AS (
    SELECT username, MAX(time) AS max_time
    FROM activeUsers
    GROUP BY username
)

SELECT t1.username,
       CASE WHEN t1.user_agent LIKE '%Android%' THEN 'Android'
            WHEN t1.user_agent LIKE '%iPhone%' OR t1.user_agent LIKE '%Iphone%' THEN 'IOS'
            ELSE 'Internet Banking'
       END AS type
FROM activeUsers t1
INNER JOIN cte t2
    ON t1.username = t2.username AND
       t1.time     = t2.max_time


text:
Q: Ant in a Cuboid find shortest path: length, width and height of a cuboid are given. Output should display the shortest distance in floating point An ant saw a box of sugar. It climbs to the top corner of the box to get inside. Unfortunately, the box has only few sugar cubes at the bottom corner opposite to the ant. Write a program to help the ant to find the shortest path to reach the sugar cubes.
Input and Ouptut Format:
Input consists of three integers corresponds to length, width and height of a cuboid.
Output should display the shortest distance in floating point. Correct to two decimal places.
Sample Input and Output:
Enter the length
5
Enter the width
6
Enter the height
7
The Shortest distance is 14.81
The formula i used
minimum among (1) square root[(a+b)^2 + c^2] (2) square root[(b+c)^2 + a^2] (3) square root[(a+c)^2 + b^2]
The answer i am getting for same inputs is 13.42
Where am i going wrong?
    s1=x+y;
    s2=y+z;
    s3=x+z;
   s1sq=s1*s1;
   s2sq=s2*s2;
   s3sq=s3*s3;
   x2=pow(x,2.0);
   y2=pow(y,2.0);
   z2=pow(z,2.0);
   full1=s1sq+z2;
   full2=s2sq+x2;
   full3=s3sq+y2;
   sq1=sqrt(full1);
   sq2=sqrt(full2);
   sq3=sqrt(full3);
   min=sq1;
   if(sq1<sq2 && s1<sq3)
   min=sq1;
   if(sq2<sq3 && sq2<sq1)
   min=sq2;
   else min=sq3;
   Printf("%.2f",min);
   return 0;

A: You made a mistake in the formulae. The way you're looking at it, you should write:
(a + sqrt(b^2 + c^2))
(b + sqrt(a^2 + c^2))
(c + sqrt(a^2 + b^2)).

And even then, you wouldn't get the shortest distance. To give an example,
suppose the cube is of 1x1x1 units with sides along the x, y and z axes. In order for the ant to get from (0,0,0) to (1,1,1), it can go from
(0,0,0) -> (0,1,1) -> (1,1,1)
or
(0,0,0) -> (0, 0.5, 0.5) -> (1,1,1)
The second path is the shorter one obviously.


text:
Q: Callback to sectionHeadersPinToVisibleBounds I have a requirement in my project that I have to add shadow to UICollectionView headers when they become sticky.
I am using the property on UICollectionViewFlowLayout sectionHeadersPinToVisibleBounds, which when set to YES makes the headers sticky.
Can we get some sort of callback when the headers become sticky and actually pin to top so that I can add a shadow to that header? I don't want the shadow to be there when a header is not sticky.
The challenge here is, I can't really make use of the information in method- layoutAttributesForSupplementaryView: which does provide me the views on screen as my sections having dynamic no of items, hence which section is on screen doesn't really tell me who needs a shadow.

A: I've managed to find the solution to this question by:

*

*manually saving position of a header in:
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let cell = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "CategoryNameReusableView", for: indexPath) as! CategoryNameReusableView
            cell.nameLbl.text = sectionNames[indexPath.section]
            if viewWithPosition.isEmpty { viewWithPosition.append(( name: cell.nameLbl.text!, position: cell.frame.origin.y))}
            let x = isElementInArray(array: viewWithPosition, string: cell.nameLbl.text!)
            if !x {
                viewWithPosition.append((name: cell.nameLbl.text!, position: cell.frame.origin.y))
            }
        return cell
}

I am using an array of viewWithPosition tuples var viewWithPosition = [(name: String, position: CGFloat)](). It might have been the same if i saved only position of a cell, but since my cells have different text i used name parameter to check if the element already exists in the array. I used helper function:
fileprivate func isElementInArray(array: [ViewAndPosition], string: String) -> Bool {
    var bool = false
    for views in array {
        if views.name == string {
            bool = true
            return bool
        }
    }
    return bool
}

*When i have initial positions i check if visible headers are misplaced:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if let visibleHeadersInSection = collectionView.visibleSupplementaryViews(ofKind: UICollectionElementKindSectionHeader) as? [CategoryNameReusableView] {
    for header in visibleHeadersInSection{
        if let index = viewWithPosition.index(where: { (element) -> Bool in
            element.name == header.nameLbl.text
        }){
            if header.frame.origin.y == viewWithPosition[index].position {
                header.backgroundColor = UIColor.clear
            } else {
                header.backgroundColor = UIColor.white
            }
        }
    }
}

}
At the moment it seems that there are no callbacks provided by Apple for this kind of situation. Hopefully this is also the solution for you.


text:
Q: Allow mouse events to pass through semitransparent Popup I'm trying to do a drag-n-drop operation from a control inside a Popup. The content being dragged will be placed at the position of the drop so when the drag starts I want to make the Popup semitransparent to allow placement under it. But so far I fail to make mouse events pass through my semitransparent Popup.
The following xaml works fine, the Button is still clickable when hovering the Rectangle with the mouse
<Grid>
    <Rectangle Panel.ZIndex="2"
               Width="200"
               Height="200"
               Fill="Green"
               IsHitTestVisible="False"
               Opacity="0.5"/>
    <Button Content="Click Me"
            FontSize="22"
            FontWeight="Bold"/>
</Grid>

But the following xaml fails to allow mouse event to pass through when the mouse hovers the Rectangle inside the Popup.
<Grid>
    <Popup Placement="Center"
           AllowsTransparency="True"
           IsHitTestVisible="False"
           IsOpen="True">
        <Rectangle Width="100"
                   Height="50"
                   Fill="Green"
                   IsHitTestVisible="False"
                   Opacity="0.5"/>
    </Popup>
    <Button Content="Click Me"
            FontSize="22"
            FontWeight="Bold"/>
</Grid>

I've tried to get the PopupRoot top parent of the Rectangle and set both IsHitTestVisible and Opacity for every element in the visual tree explicitly but it still doesn't work. The only way I can sort of get it to work is by setting Background/Fill to Transparent but it looks weird and hovering the parts that aren't Transparent still fails.
I've read the following link but as far as I can tell, that will only work for a Window and not a Popup.
How to create a semi transparent window in WPF that allows mouse events to pass through
Does anyone have any solutions or suggestions? :-)

A: Thanks to the comment made by @NETscape I tried to get a hold of the actual Window for the Popup. It works with the following code (after the Popup is initially shown I might add..)
// FromVisual can take any Visual inside the Popup..
HwndSource popupHwndSource = HwndSource.FromVisual(rectangle) as HwndSource;

Combining this with the answer to this question I created an attached behavior which adds the property IsPopupEventTransparent which can be set on any child in the Popup. At first, this solution caused a bug which forced the users to click twice to re-activate the Window after the Popup lost its event transparency. I solved this with a "Mouse.Capture-workaround".
elementInPopup.Dispatcher.BeginInvoke(new Action(() =>
{
    Keyboard.Focus(elementInPopup);
    Mouse.Capture(elementInPopup);
    elementInPopup.ReleaseMouseCapture();
}));

Usable like this
<Popup AllowsTransparency="True"
       ...>
    <Border inf:PopupBehavior.IsPopupEventTransparent="{Binding SomeProperty}"
            BorderThickness="1"
            BorderBrush="Black"
            Background="White"
            Margin="0 0 8 8">
        <Border.Effect>
            <DropShadowEffect ShadowDepth="2.25"
                              Color="Black"
                              Opacity="0.4"
                              Direction="315"
                              BlurRadius="4"/>
        </Border.Effect>
        <!--...-->
    </Border>
</Popup>

PopupBehavior
public class PopupBehavior
{
    public static readonly DependencyProperty IsPopupEventTransparentProperty =
        DependencyProperty.RegisterAttached("IsPopupEventTransparent",
                                            typeof(bool),
                                            typeof(PopupBehavior),
                                            new UIPropertyMetadata(false, OnIsPopupEventTransparentPropertyChanged));

    public static bool GetIsPopupEventTransparent(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsPopupEventTransparentProperty);
    }
    public static void SetIsPopupEventTransparent(DependencyObject obj, bool value)
    {
        obj.SetValue(IsPopupEventTransparentProperty, value);
    }
    private static void OnIsPopupEventTransparentPropertyChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
    {
        FrameworkElement element = target as FrameworkElement;
        if ((bool)e.NewValue == true)
        {
            FrameworkElement topParent = VisualTreeHelpers.GetTopParent(element) as FrameworkElement;
            topParent.Opacity = 0.4;
            HwndSource popupHwndSource = HwndSource.FromVisual(element) as HwndSource;
            WindowHelper.SetWindowExTransparent(popupHwndSource.Handle);
        }
        else
        {
            FrameworkElement topParent = VisualTreeHelpers.GetTopParent(element) as FrameworkElement;
            topParent.Opacity = 1.0;
            HwndSource popupHwndSource = HwndSource.FromVisual(element) as HwndSource;
            WindowHelper.UndoWindowExTransparent(popupHwndSource.Handle, element);
        }
    }
}

WindowHelper based on the answer to this this question
public static class WindowHelper
{
    private static Dictionary<IntPtr, int> _extendedStyleHwndDictionary = new Dictionary<IntPtr, int>();

    const int WS_EX_TRANSPARENT = 0x00000020;
    const int GWL_EXSTYLE = (-20);

    [DllImport("user32.dll")]
    static extern int GetWindowLong(IntPtr hwnd, int index);

    [DllImport("user32.dll")]
    static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle);

    public static void SetWindowExTransparent(IntPtr hwnd)
    {
        int extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
        SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_TRANSPARENT);
        if (_extendedStyleHwndDictionary.Keys.Contains(hwnd) == false)
        {
            _extendedStyleHwndDictionary.Add(hwnd, extendedStyle);
        }
    }

    public static void UndoWindowExTransparent(IntPtr hwnd, FrameworkElement elementInPopup)
    {
        if (_extendedStyleHwndDictionary.Keys.Contains(hwnd) == true)
        {
            int extendedStyle = _extendedStyleHwndDictionary[hwnd];
            SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle);
            // Fix Focus problems that forces the users to click twice to
            // re-activate the window after the Popup loses event transparency
            elementInPopup.Dispatcher.BeginInvoke(new Action(() =>
            {
                Keyboard.Focus(elementInPopup);
                Mouse.Capture(elementInPopup);
                elementInPopup.ReleaseMouseCapture();
            }));
        }
    }
}

A: The issue is not with popup but issue is with the color Green when applied to the rectangle this effectively blocks the mouse event to pass through
try the sample below with transparent background, I placed a border to show the presence
<Grid>
    <Popup Placement="Center"
           AllowsTransparency="True"
           IsHitTestVisible="False"
           IsOpen="True">
        <Border Width="100"
                Height="50"
                Background="Transparent"
                BorderBrush="Black"
                BorderThickness="4"
                IsHitTestVisible="False"
                Opacity="0.5" />
    </Popup>
    <Button Content="Click Me"
            FontSize="22"
            FontWeight="Bold" />
</Grid>

so any color having non zero alpha component will block the mouse events
refer to below for alpha example

*

*#FF00FF00 Green Fail

*#9900FF00 semi transparent Green Fail

*#0100FF00 almost invisible Green Fail

*#0000FF00 full transparent Green Pass
so you need to have transparent color in order for mouse event to be passed through
Since popup is a generated as a layered window on top of the app window, so if you need a background you may need to implement the how to create the semi transparent window solution. there seems to be no built solution in wpf


text:
Q: How to get required Contact display name based on phone number in react-native I am working on react-native. I want to get Contact display name based on the phone number from his/her phone Contacts.
I am using below code. It is giving me the error. Can any suggest correct APIs or code?
 Contacts.searchContacts( "ABC", (error, contacts) =>  {
        if (error) {
          console.error(error);
        }
        else {
          console.log(contacts);
        }
      });

A: If you're using react-native-contacts, it doesn't look like they have a "searchContacts" function in their API. I would recommend using "getContactsMatchingString" (string, callback) - where the string is any string to match a name (first, middle, family)
{
  recordID: '6b2237ee0df85980',
  company: "",
  emailAddresses: [{
    label: "work",
    email: "carl-jung@example.com",
  }],
  familyName: "Jung",
  givenName: "Carl",
  jobTitle: "",
  note: 'some text',
  urlAddresses: [{
    label: "home",
    url: "www.jung.com",
  }],
  middleName: "",
  phoneNumbers: [{
    label: "mobile",
    number: "(555) 555-5555",
  }],
  hasThumbnail: true,
  thumbnailPath: 'content://com.android.contacts/display_photo/3',
  postalAddresses: [
    {
      street: '123 Fake Street',
      city: 'Sample City',
      state: 'CA',
      region: 'CA',
      postCode: '90210',
      country: 'USA',
      label: 'home'
    }
  ],
  birthday: {"year": 1988, "month": 0, "day": 1 }
}


text:
Q: shall I use Spring framework for a performance-critical proxy application? I've created a servlet (Tomcat) application which has these functions:

*

*It performs HTTP Basic Authentication. It connects to a user and role database.

*It works as "security facade" for some geodata servers behind

*It forwards requests after doing some authorization tests

*In case the response contains XML data, it performs some manipulation (changing URLs, deleteting some XML-Elements or changing it's content). I'm using STaX for this task.

*It logs some information about the response to a database.

It's likely that there is a need for connecting to another user database and to extend the capabilities of the authorization components.
The size of the response data reaches form 10 kB to 500 MB.
I'm new to Spring. Shall I introduce the Spring framework in my application?
EDIT:
Perhaps, this question is better: is there a framework (Spring for example) which causes minimal performance loss?
EDIT 2:
Is the SO community "Programmers" a better place for this question?

A: Before re-writing your code first thing you should analyze is why do you require Spring framework? What problem are you facing in your current architecture?
Just because size of the response data stokes up shouldn't be the only reason to re-write your code. You can better design your existing code to scale your application.
On the flipside the primary upside of writing your code in Spring is it will cut down the boiler plate code for an instance you don't have to explicitly write code for creating JDBC connection with database every now & then rather you would use the Spring JDBC template. Spring facilitates features like convention over configuration which would require you to write less code.
Also a framework is written keeping in mind all the performance optimization issues so definitely Spring will help in reducing the latency of your app.


text:
Q: google maps help First, I'm trying this through Google (not using API). Want to see if it's possible without API first.
I have a saved map in google which has some points of interest. (ex: national parks)
However, when I search for directions (ex: from: denver, co to: chicago, il) the directions appear, but my saved map (POI's) disappear.
Has or does anyone know how I can modify the URL to have these 2 overlay?
Thanks!

A: You can save directions to the 'My Maps' feature of Google Maps. Once you search for directions, there is a link at the bottom of the direction sidebar titled 'Save to My Maps'. After the directions are saved, you can add custom features to the map in the 'My Maps' editor.

A: My workflow is:
-Go to Google maps  (sign in if necessary)
-Go to My Places
-Select the map you're interested in,
-From here, click on Get directions, type A an B then enter
-Here, you have your directions but your map is lost, but...
-If you click on My Places and your map again, bingo!


text:
Q: Windows Server version and SQL Server Is there a blog / webpage / information (I did not find anything) out there, if it has performance benefits, if I use a newer Windows Server version for my SQL Server?
Example: I run SQL 2016 on a Windows Server 2012. Does it make sense to update this server to Windows Server 2016 or the upcoming Windows Server 2019 beside those out-of-support lifecycle topics? Does it make a difference, if I install a new SQL Server 2019 (if it is out) on Windows Server 2016 or Windows Server 2019?
PS: The only point I found to this topic was that - if I want to use NVDIMMs I should use Windows Server 2016 for better support.

A: There would not be any noticeable performance benefit if you move to higher version of windows server. Normally people move to higher version keeping support in perspective and the host of new features they get in newer version of windows. Refer Compare features in Windows Server versions to see list of new features you get in various versions of Windows Server.

A: It depends what features you are going to use from SQL end. Per my experience, if you are going to use availability groups, then you should consider Windows 2016 running SQL 2016 rather than on Windows 2012 due to many reasons. I personally have seen performance improvements running SQL 2016 on windows 2016 when compared the baselines I had collected overtime.
Apart from performance, there are many benefits running SQL2016 on windows 2016 specially Quorum changes in this version.please check msdn link for further info.


text:
Q: How to replace between existing table rows in JavaScript I am trying to regenerate a table with a new order, the problem i encounter is in the performance,
I Have something like this:

Obviously my table is much more complex, but what i would like is a solution with good performance for a replacing command
my target table should be something like:

When I redraw it the performance is bad(for more then 100 lines)
is there any way to just replace the rows between themselves without redrawing it?
Thanks

A: For rearranging them append them using append() or next()

$table = $('#mainTable');

$table.append($('#row1,#row2', $table));

    1

    2

    3

    4

A: The basic sultion is using jquery "after" function , which move the target element after the wanted element ..
$("#row1").after("#row4");

or if you want to sort the table based on its values , you can use plugins like :  table sorter


text:
Q: How to handle session expire in partially loaded divs in mvc I have 2 divs on a page, based on the click id on left i load the content in the right div.
But when session expires, i am expecting the page to redirect to Login, but it does not behave tht way.
some times the button wont work or some times the login screen loads in the right div.
Any suggestions to handle this session expire?

A: By default, the IIS simply returns the login-page with an HTTP status code 200 when the session is expired. This makes your ajax not see it as an error.
So you need to do a check in your controller action to see whether the Session has expired, and if it has, you can return an HttpStatusCodeResult(HttpStatusCode.Unauthorized).
After that, in your ajax, you can use somthing like this:
$.ajax({
//...
error: function(data, textStatus, xhr) {
    if(xhr.status == "401"){ window.location.href = "/login";
    }
}


text:
Q: RSS alert via sms I was searching for a service that can provide RSS updates via sms also any such API that I may integrate so that my subscribers can get updates for their subscribed RSS feeds via SMS. Perhaps an open source implementation will be more favorable.

A: Not sure I understand the question. There is some PHP and Javascript coding involved plus the use of a cloud telephony app called Tropo as well as configuring Windows Task Scheduler with a Visual Basic file (.vbs) to run as a kind of client-side cron-job. ~Eric


text:
Q: How can I get AbsoluteExpiration DateTimeOffset of key in IMemoryCache I add a value to IMemoryCache
_cache.Set("Key", "Value", DateTimeOffset.UtcNow);

I wanna to get absolute expiration value of this key in other methods.
Or
I wanna to update value of this key without changing expiration.
How can i do that?

In IMemoryCache document doesn't have any way to get it (at least i didn't see), I handle it by caching expiration. Is there any better solution for handle it?

A: IMemoryCache (as in its documentation) doesn't have any method to get item expiration.
Same for its default implementation MemoryCache.


text:
Q: JSON with HttpClient error in Android I have some problems while working with JSON in Android, it gives me some error in log cat please help me what should i do, here is my code:
String feedUrl= "https://107.170.117.18:7000/infoes/";
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

     context=this;

    infoListTask loaderTask = new infoListTask();
  loaderTask.execute();

}

private class infoListTask extends AsyncTask<Void,Void,Void> {

    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        dialog= new ProgressDialog(context);
        dialog.setTitle("Loading ...");
        dialog.show();

        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub
        HttpClient client = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet(feedUrl);

        try {
            HttpResponse response =client.execute(getRequest);
            StatusLine statusline= response.getStatusLine();
            int statusCode= statusline.getStatusCode();

            if(statusCode != 200){

                return null;
            }

            InputStream jsonStream = response.getEntity().getContent();
            BufferedReader reader= new BufferedReader(new InputStreamReader(jsonStream));
            StringBuilder builder = new StringBuilder();
            String line;
            while((line= reader.readLine()) != null)
            {
                builder.append(line);
            }

            String jsonData= builder.toString();

            Log.i("You json Data", jsonData);

        }
        catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e) {
             //TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        dialog.dismiss();
        //videoAdapter.notifyDataSetChanged();

        super.onPostExecute(result);
    }

}

and this is my log cat :
06-17 11:55:50.361: W/System.err(2224): javax.net.ssl.SSLPeerUnverifiedException: No peer certificate
06-17 11:55:50.397: W/System.err(2224):     at com.android.org.conscrypt.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:146)
06-17 11:55:50.409: W/System.err(2224):     at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:93)
06-17 11:55:50.413: W/System.err(2224):     at org.apache.http.conn.ssl.SSLSocketFactory.createSocket(SSLSocketFactory.java:388)
06-17 11:55:50.413: W/System.err(2224):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:165)
06-17 11:55:50.413: W/System.err(2224):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
06-17 11:55:50.413: W/System.err(2224):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
06-17 11:55:50.417: W/System.err(2224):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
06-17 11:55:50.417: W/System.err(2224):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
06-17 11:55:50.421: W/System.err(2224):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
06-17 11:55:50.421: W/System.err(2224):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
06-17 11:55:50.421: W/System.err(2224):     at com.amirhossein.test.MainActivity$infoListTask.doInBackground(MainActivity.java:78)
06-17 11:55:50.421: W/System.err(2224):     at com.amirhossein.test.MainActivity$infoListTask.doInBackground(MainActivity.java:1)
06-17 11:55:50.421: W/System.err(2224):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
06-17 11:55:50.425: W/System.err(2224):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
06-17 11:55:50.425: W/System.err(2224):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
06-17 11:55:50.433: W/System.err(2224):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-17 11:55:50.437: W/System.err(2224):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-17 11:55:50.437: W/System.err(2224):     at java.lang.Thread.run(Thread.java:841)
06-17 11:55:50.449: W/EGL_genymotion(2224): eglSurfaceAttrib not implemented
06-17 11:55:50.529: W/EGL_genymotion(2224): eglSurfaceAttrib not implemented

A: See other questions for 'SSLPeerUnverifiedException: No peer certificate':
Android: Making Https Request
Safely fixing: javax.net.ssl.SSLPeerUnverifiedException: No peer certificate


text:
Q: Выходит ошибка character maps to  Выходит ошибка charmap codec can't encode character '\U0001f48e' in position 7000: character maps to
from requests import get
import json

def NFT(textas):
    text = '''<!DOCTYPE html PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ton Scan</title>

    '''
    text3 = ''
    wer = ""
    ton = get(f'https://tonapi.io/v1/nft/searchItems?owner={textas}&include_on_sale=true&limit=1000&offset=0', stream=True).text
    data = json.loads(ton)
    if data["nft_items"] != []:
        my_file = open(f"{textas}.html", "w+")
        for i in range(99):
            try:
                aw = data["nft_items"][i]["metadata"]["image"].split("//")
                if aw[0] == "ipfs:":
                    wer = wer + '

{data["nft_items"][i]["metadata"]["name"]}

{data["nft_items"][i]["collection"]["name"]}

==================================================
'''
                else:
                    wer = wer + '

{data["nft_items"][i]["metadata"]["name"]}

{data["nft_items"][i]["collection"]["name"]}

==================================================
'''
                #print(str(i)+" "+data["nft_items"][i]["collection"]["name"]+"\n"+data["nft_items"][i]["metadata"]["name"]+"\n"+data["nft_items"][i]["metadata"]["image"]+"\n=======================")
            except:
                ...

        wer = wer + text3
        wer = text + wer
        my_file.write(wer)
        my_file.close()
    else:
        return False

NFT("EQCtiv7PrMJImWiF2L5oJCgPnzp-VML2CAt5cbn1VsKAxLiE")

Искал в Google, не нашел ответа.

A: Чтоб избавиться от этой ошибки добавьте encoding="utf-8":
my_file = open(f"{textas}.html", "w+", encoding="utf-8")

Вместо try/except можно применить with open. Модуль json импортировать излишне, так как в requests встроен метод обработки таких файлов.
ton = get(f'https://tonapi.io/v1/nft/searchItems?owner={textas}&include_on_sale=true&limit=1000&offset=0', stream=True)
data = ton.json()
print(type(data))

Все-таки видите, что плохо искали - ответы уже были.


text:
Q: XQuery/Xpath optimization: query different parts of the same document Let's say we have XML files with different parts: title, description, text, note.
<book>
    <title>Some title</title>
    <description>Some description</description>
    <text>Some texte</text>
    <note>Some note</note>
</book>

Let's say we want to be able to query in these different parts. This can be done by different approaches.
For exemple, we want to query only in title and note.
approach 1 (basic verbose version)
for $result in (
    collection("path_to_my_collection")//title[ft:query(., "'word_to_search'")]
    ,
    collection("path_to_my_collection")//note[ft:query(., "'word_to_search'")]
    )

approach 2 (take this one from here)
for $result in collection("path_to_my_collection")//(title | note)[ft:query(., "'word_to_search'")]

approach 3 (this one seems to be advised by the documentation )
let $docs_and_parts :=
    for $parts in (collection("path_to_my_collection")//title, collection("path_to_my_collection")//note)
    return
        $parts

for $result in $docs_and_parts[ft:query(., "'word_to_search'")]

After reading the XQuery optimization technic, I'm wondering which one of these approaches is more efficient/fast for execution in large collections with many (more than 100) files?

A: I think the article mentioned all relevant aspects to consider when writing expressions for eXists-db, e.g. avoid unnecessary nested filters, prefer XPath predicates over where expressions, use group by, construct the initial node set once and use it as input for the main expression when querying multiple collections..
It would seem the 3rd approach is advised since it follows the recommendation to construct the initial node set before querying it.
However, approach 2 seems to solve this by relying only on XPath; which could be even better.
In the end, it depends on your input data and the implementation details of the optimizer.   Following the general recommendations and common sense (e.g.g avoid nested loops, etc) should help in most cases but running tests and find out what actually works best in a given scenario might be still required for critical cases.


text:
Q: Sort by a function that takes argument(s) in c++? I'm trying to write a function to sort a vector of custom class objects by a variety of different attributes.
The c++ sort reference, found here:
http://www.cplusplus.com/reference/algorithm/sort/
Says that you can sort like this:
std::sort (myvector.begin(), myvector.end(), myfunction);

What I would like to be able to do is pass an argument to myfunction in addition to the two objects from my vector like this:
std::sort (myvector.begin(), myvector.end(), myfunction(mode=7));

Do you know of a way to do so?
I am relatively new to c++, coming from python where this would be easy.

A: If you are using C++11, you can use a lambda:
sort(myvec.begin(), myvec.end(), [] (Type a, Type b) { return myfunction(a,b,7); });

A: You can use a functor instead of a free function:
struct Functor{
  int mode;
  bool operator() (int a,int b) { return (a<b);}
} functor;

The overloaded () operator executes when the functor is called by sort. In there you can have a variable mode and use it as you need.
Then set mode (you could also set in on the functor constructor) and call sort using it:
functor.mode = 7; // or set it in the constructor
std::sort (myvector.begin(), myvector.end(), functor);

A: Create a functor:
struct MyFunction {
  bool operator()(const T& lhs, const T& rhs) const { /* implement logic here */ }
  int mode;
};

Then pass an instance of that instead of your plain function myfunction. Here, T is the type used to instantiate your std::vector.
MyFunction f;
f.mode = 7;
std::sort (myvector.begin(), myvector.end(), f);

If you have C++11 support, you can use a lambda function:
std::sort(myvector.begin(), myvector.end(), [](const T&a, const T& b) { /* implement*/ });


text:
Q: GIS confidentiality, how to convert address to block level I have a list of addresses in a spreadsheet to use with ArcGIS and geocode using the provided ESRI street level geolocator.
But I intend to make point information viewable for the public, thus I want to change sensitive address information to the block level.
EG: 2686 Workman Street, Los Angeles CA 90031 ->
recoded to the block level as 2600-2700 Workman Street, Los Angeles, CA 90031
What can I do to accomplish this other than manually rewriting hundreds of entries?

A: Convert all the addresses to latitude and longitude then delete the addresses. Then spatial join to the vector street line closest. Then delete the coordinates. Then the file will have just the block info.

A: Good question.  I don't know where you can find out the range for each block but maybe this will help you get started.  Using the ZIP+4 data from the USPS or a distributor like zip-codes.com (I have no affiliation) you can determine the valid ranges for each street.  for example, 0-10 odd or 13-29 even.  Again, you'll still need to be able to determine the blocks.

A: Census Block GIS data are part of a larger dataset called TIGER, for Topologically Integrated Geographic Encoding and Referencing. Block boundaries are defined based on the location of roads and other lines in the "All Lines" TIGER dataset (also known as "Edges"). The lines in the Edges dataset include address ranges for both left and right sides of the road, as shown on page 2 of the documentation.
I would perform a spatial join of address points to Edges lines and then create a new composite address based on the FULLNAME, LFROMADD, LTOADD, RFROMADD, and RTOADD fields in combined attribute table.


text:
Q: two way difference in sending cookies with requests by restAssured? as far as i know there is two ways to work with RestAssured, long and short one.
at the short way to send request with cookie you just use
RestAssured.baseURI = "http://example.com/";

than for the cookie
given().cookie("cookiname", "cookie value").when().get("URL").then().statusCode(200);

and than you can use cookie builder if needed
but at the long way with:
Response response = httpRequest.get("/something");

how you send the cookie?
i saw something like:
RestAssured.requestSpecification = new RequestSpecBuilder().addCookie("my cookie","mycookievalue").build();

but still i didn't understand it and didn't saw an request with that, can you explain me these please?


text:
Q: Process Large number of zipped xml files in s3 bucket I have a very large number of xml files zipped and sitting in s3 bucket. What will be the best way to process the data in AWS?

A: Depends on what you need to do with them or what is the nature of the processing operations required.
But I would look into S3 Batch Operations:

S3 Batch Operations performs large-scale batch operations on Amazon S3 objects. You can use S3 Batch Operations to copy objects, set object tags or access control lists (ACLs), initiate object restores from Amazon S3 Glacier, or invoke an AWS Lambda function to perform custom actions using your objects.


text:
Q: way to get ion-checkbox values I'm trying to get the value from checkbox so i can bind it .
but i keep get it with the condition ( true or false)
When I click the checkbox, it sets my model like so:
[9: true, 15: true]
What I want is a flat array like:
[9, 15]
Is there a better to get the values from the checkbox and set them in an array on the model?
enter image description here
    <ion-checkbox ng-repeat="model in models | filter:query" ng-model="order.models[model.id]" >{{model.model_number}} </ion-checkbox>
</ion-item>
current order: {{order}}

    .controller('compareModelsCtrl',['$scope','$http', '$state' ,
function($scope, $http, $state,$location) {
$http.get('js/data.json').success(function(data){
$scope.models = data;
$scope.whichmodel = $state.params.modelId;
//$scope.toggleStar = function(model){
// model.star = !model.star;
//}
$scope.order = {};

A: Ionic framework doesn't do that by default. You need custom function such as format in the code below. Since, I don't have your data.json file, I mimicked two ion-checkbox.
     <ion-content ng-controller="LoginCtrl">
       <ion-checkbox  ng-model="order[0]" ng-change="format()" >1 </ion-checkbox>
       <ion-checkbox  ng-model="order[1]" ng-change="format()" >2</ion-checkbox>
    current order: {{modifiedOrder}}
  </ion-content>

And implemented following function inside the controller.
angular.module('ionic.example', ['ionic'])
.controller('LoginCtrl', function($scope) {
$scope.order={};
$scope.format=function(){
  $scope.modifiedOrder=[];
  angular.forEach($scope.order, function(value, key) {
    if(value){
      $scope.modifiedOrder.push(parseInt(key));
    }
});
}
});

The order now you had before is modifiedOrder
See working code here. https://codepen.io/anon/pen/vXYvPG
Goodluck!

A:
In Html file,
<ion-content padding>
  <ion-input type="text" placeholder="What's Your groups name?"></ion-input>
  <ion-list>

        <ion-item *ngFor="let friend of friendList">
          <ion-label>{{friend.name}}</ion-label>
          <ion-checkbox [(ngModel)]="friendsSelected[friend.name]"></ion-checkbox>
        </ion-item>
    </ion-list>
    <button ion-button  (click)="save()">Save</button>
</ion-content>

And in your TS file
I have created a variable friendsSelected
 friendsSelected:any={};

   save(){
    var array = [];
    for(var i in this.friendsSelected) {
        console.log(this.friendsSelected[i]);
        if(this.friendsSelected[i] == true) {
            array.push(i);
        }
    }
    console.log(array);
  }


text:
Q: sed substitution on multiple lines I need to substitute owl:Class in the following text with the LP number
Input
<owl:Class rdf:about="https://loinc.org/LP173100-1">
        <rdfs:subClassOf rdf:resource="https://loinc.org/LP410935-3"/>
        <rdfs:label rdf:datatype="http://www.w3.org/2001/XMLSchema#string">Counseling (LP)</rdfs:label>
        <skos:prefLabel rdf:datatype="http://www.w3.org/2001/XMLSchema#string">Counseling</skos:prefLabel>
        <loinc:hasCode rdf:datatype="http://www.w3.org/2001/XMLSchema#string">LP173100-1</loinc:hasCode>
    </owl:Class>

so that the substituted output looks like the following
Output
<LP173100-1 rdf:about="https://loinc.org/LP173100-1">
        <rdfs:subClassOf rdf:resource="https://loinc.org/LP410935-3"/>
        <rdfs:label rdf:datatype="http://www.w3.org/2001/XMLSchema#string">Counseling (LP)</rdfs:label>
        <skos:prefLabel rdf:datatype="http://www.w3.org/2001/XMLSchema#string">Counseling</skos:prefLabel>
        <loinc:hasCode rdf:datatype="http://www.w3.org/2001/XMLSchema#string">LP173100-1</loinc:hasCode>
    </LP173100-1>

I have used s/\(owl:Class\)\(.*org\/\)\(LP.*\)"/\3\2\3/g for the first line but I don't know how to apply it on the last line. Is there a more elegant solution? I have a huge file where I need to do such substitution.
I am using a Centos OS 7.7 Linux machine.

A: You can replace the \n symbol with a different one (such that is not located anywhere else inside the file) and then continue working as usual.
cat foo.txt | tr '\n' '\r' | sed -e 's/\(owl:Class\)\(.*org\/\)\(LP.*\)"/"\3"\2\3/g'  | tr '\r' '\n'


text:
Q: Functional equation in quaternion algebra Let $F,G:\mathbb{C}^2\rightarrow\mathbb{H}\otimes\mathbb{R}^4$ be two functions with components $F_0,F_1,F_2,F_{1,2},G_0,G_1,G_2,G_{1,2}:\mathbb{C}^2\rightarrow\mathbb{H}$ with quaternionic values. Assume that for $K\in\{0,1,2,\{1,2\}\}$
$$F_K\left(\overline{z}_1,z_2\right)=\left\{\begin{array}{l}
F_K(z_1,z_2)\qquad \text{if }\ 1\notin K\\
-F_K(z_1,z_2)\qquad \text{if }\ 1\in K
\end{array}\right.$$
and
$$F_K\left(z_1,\overline{z}_2\right)=\left\{\begin{array}{l}
F_K(z_1,z_2)\qquad \text{if }\ 2\notin K\\
-F_K(z_1,z_2)\qquad \text{if }\ 2\in K.
\end{array}\right.$$
The same holds for $G_K$. These functions are usually called Stem functions.
Is there any hope to deduce some property of the components of $F$ and $G$ by the fact that they solve the following equation
$$F_{12}G_0+F_1G_2+F_2G_1+F_0G_{12}=0?$$
I'm looking for something like $F_{1,2}=G_{1,2}=0$, but this is not the case in general.
P.S. What about if we suppose $F$ and $G$ holomorphic, adding these "Cauchy-Riemann equations" of the form
$$\dfrac{\partial F_0}{\partial\alpha_1}=\dfrac{\partial F_1}{\partial\beta_1},\quad\dfrac{\partial F_0}{\partial\beta_1}=-\dfrac{\partial F_1}{\partial\alpha_1},\quad\dfrac{\partial F_2}{\partial\alpha_1}=\dfrac{\partial F_{1,2}}{\partial\beta_1},\quad\dfrac{\partial F_2}{\partial\beta_1}=-\dfrac{\partial F_{1,2}}{\partial\alpha_1},$$
$$\dfrac{\partial F_0}{\partial\alpha_2}=\dfrac{\partial F_2}{\partial\beta_2},\quad\dfrac{\partial F_0}{\partial\beta_2}=-\dfrac{\partial F_2}{\partial\alpha_2},\quad\dfrac{\partial F_1}{\partial\alpha_2}=\dfrac{\partial F_{1,2}}{\partial\beta_2},\quad\dfrac{\partial F_1}{\partial\beta_2}=-\dfrac{\partial F_{1,2}}{\partial\alpha_2},$$
which hold for $G$ as well?
Thank you to anyone for the help.


text:
Q: Low frame rate with Greensock animation I've built an animation with greensock and I checked the frame rates with Chrome Devtools in incognito. Unforunately I have massive frame drops:
Here are the FPS numbers

Here is the animation
Can I optimize this animation somehow?


text:
Q: Confusing p values with ANOVA on a big dataframe I am trying to analyse the significant differences between different car company performance values across different countries. I am using ANOVA to do this.
Running ANOVA on my real dataset (30 countries, 1000 car companies and 90000 measurement scores) gave every car a zero p-value.
Confused by this, I created a reproducible example (below) with 30 groups, 3 car companies, 90000 random scores. Purposely, I kept a score of 1 for the Benz company where you shouldn't see any difference between countries. After running anova, I see a pvalue of 0.46 instead of 1.
Does any one know why is this ?
Reproducible example
set.seed(100000)
qqq <- 90000

df = data.frame(id = c(1:90000), country = c(rep("usa",3000), rep("usb",3000), rep("usc",3000), rep("usd",3000), rep("use",3000), rep("usf",3000), rep("usg",3000), rep("ush",3000), rep("usi",3000), rep("usj",3000), rep("usk",3000), rep("usl",3000), rep("usm",3000), rep("usn",3000), rep("uso",3000), rep("usp",3000), rep("usq",3000), rep("usr",3000), rep("uss",3000), rep("ust",3000), rep("usu",3000), rep("usv",3000), rep("usw",3000), rep("usx",3000), rep("usy",3000), rep("usz",3000), rep("usaa",3000), rep("usab",3000), rep("usac",3000), rep("usad",3000)), tesla=runif(90000), bmw=runif(90000), benz=rep(1, each=qqq))

str(df)
out<-data.frame()

for(j in 3:ncol(df)){
amod2 <- aov(df[,j]~df$country)
out[(j-2),1]<-colnames(df)[j]
out[(j-2),2]<-summary(amod2, test = adjusted("bonferroni"))[[1]][[1,"Pr(>F)"]]
}

colnames(out)<-c("cars","pvalue")
write.table(out,"df.output")

df.output
"cars" "pvalue"
"1" "tesla" 0.245931589754359
"2" "bmw" 0.382730335188437
"3" "benz" 0.465083026215268

A: With respect to the "benz" p-value in your reproducible example: an ANOVA analysis requires positive variance (i.e., non-constant data).  If you violate this assumption, the model is degenerate.  Technically, the p-value is based on an F-statistic whose value is a normalized ratio of the variance attributable to the "country" effect (for "benz" in your example, zero) divided by the total variance (for "benz" in your example, zero), so your F-statistic has "value" 0/0 or NaN.
Because of the approach R takes to calculating the F-statistic (using a QR matrix decomposition to improve numerical stability in "nearly" degenerate cases), it calculates an F-statistic equal to 1 (w/ 29 and 89970 degrees of freedom).  This gives a p-value of:
> pf(1, 29, 89970, lower=FALSE)
[1] 0.465083
>

but it is, of course, largely meaningless.
With respect to your original problem, with large datasets relatively small effects will yield very small p-values.  For example, if you add the following after your df definition above to introduce a difference in country usa:
df = within(df, {
    o = country=="usa"
    tesla[o] = tesla[o] + .1
    bmw[o] = bmw[o] + .1
    benz[o] = benz[o] + .1
    rm(o)
})

you will find that out looks like this:
> out
   cars       pvalue
1 tesla 9.922166e-74
2   bmw 5.143542e-74
3  benz 0.000000e+00
>

Is this what you're seeing, or are you seeing all of them exactly zero?


text:
Q: Open Interval in subsets Suppose that $X$ is a subset of $\Bbb R$.  If there exists an open interval contained in $X$, then $\# X = \# \Bbb R$.

A: For the converse just take the set of irrationals $\;Irr.:=\Bbb R\setminus\Bbb Q\;$ . It has the same cardinal as the reals (why?), yet it contains no open non-trivial interval (again, why?) .
For the first part of the original question: if $\;(a,b)\subset X\;$ , then use that any open interval is homeomorphic to $\;(0,1)\;$ by means of the homeomorphism
$$x\mapsto\frac{x-a}{b-a}\;\;\text{(show this is a continuous bijection and find its inverse)}$$
and now, composing homeomorphisms, observe that also $\;(a,b)\sim(-\pi/2\,,\,\pi/2)\;$ , and this last is hom. with $\;\Bbb R\;$ by means of $\;f(x):=\tan x\;$ , with obvious continuous inverse...


text:
Q: Performance Improvement: Alternative for array_flip function Is there any way I can avoid using array_flip to optimize performance. I am doing a select statement from database, preparing the query and executing it and storing data as an associative array in $resultCollection and than I have array op and for each element in $resultCollection am storing its outputId in op[] as evident from the code.
I have explained code and so my question is how can I achieve an similar alternative for array_flip with using array_flip as I want to improve performance.
$resultCollection = $statement->fetchAll(PDO::FETCH_ASSOC);

$op = array();

//Looping through result collection and storing unicaOfferId into op array.
foreach ($resultCollection as $output)
{
$op[] = $output['outputId'];
}

//Here op array has key as 0, 1, 2...and value as id {which I am interested in}

//Flip op array to get offer ids as key

$op = array_flip($op);

//Doing a flip to get id as key.

foreach ($ft as $Id => $Off)
{
    $ft[$Id]['is_set'] = isset($op[$Id]);
}

A: I'm adding this answer because you mentioned in the title "Performance Improvement".
TL;DR
You should continue with array_flip(). In the terms of performance compared to a foreach loop, it does things much faster, especially on large arrays (maybe because of its native nature).
Let's test
The result of what I tested (PHP 8.1.5):
Testing an array with 10 elements:
  Average time for array_flip(): 2.0E-5
  Average time for foreach: 3.0E-5
  How much array_flip() is faster: 78%

Testing an array with 100 elements:
  Average time for array_flip(): 0.00011
  Average time for foreach: 0.00025
  How much array_flip() is faster: 137%

Testing an array with 1000 elements:
  Average time for array_flip(): 0.00108
  Average time for foreach: 0.00272
  How much array_flip() is faster: 150%

Testing an array with 10000 elements:
  Average time for array_flip(): 0.00918
  Average time for foreach: 0.02429
  How much array_flip() is faster: 164%

Testing an array with 100000 elements:
  Average time for array_flip(): 0.10644
  Average time for foreach: 0.2439
  How much array_flip() is faster: 129%

Testing an array with 1000000 elements:
  Average time for array_flip(): 0.93669
  Average time for foreach: 2.47616
  How much array_flip() is faster: 164%

Did you see that? Approximately, array_flip() is 2.5 times faster. In addition, it seems the performance of array_flip() increases slightly when the array becomes bigger. So, forget foreach. Even with the help of JIT? Read on...
Could JIT help things out?
Yes! Let's see (PHP 8.1.5, with tracing JIT, opcache.jit_buffer_size = 100M):
Testing an array with 10 elements:
  Average time for array_flip(): 3.0E-5
  Average time for foreach: 3.0E-5
  How much array_flip() is faster: -3%

Testing an array with 100 elements:
  Average time for array_flip(): 0.00011
  Average time for foreach: 0.00011
  How much array_flip() is faster: 0%

Testing an array with 1000 elements:
  Average time for array_flip(): 0.00098
  Average time for foreach: 0.00101
  How much array_flip() is faster: 3%

Testing an array with 10000 elements:
  Average time for array_flip(): 0.00955
  Average time for foreach: 0.00985
  How much array_flip() is faster: 3%

Testing an array with 100000 elements:
  Average time for array_flip(): 0.09958
  Average time for foreach: 0.10182
  How much array_flip() is faster: 2%

Testing an array with 1000000 elements:
  Average time for array_flip(): 0.90585
  Average time for foreach: 1.03467
  How much array_flip() is faster: 14%

Interesting! Notice that:

*

*It may seem obvious for some, but tracing JIT starts becoming more useful when you start calling a particular function in a run more and more (try playing with the $iterationsCount in the code below). Also, in most cases you could ignore the performance of a single function call.

*JIT made everything faster. For array_flip(), it was up to 5-10% performance increase. For foreach, it was magical: about 150% (i.e. 2.5 times faster)!

*As a result of the previous note, the difference between these two methods reduced drastically. JIT is great and is improving!
Although having a JIT-enabled environment is great, internal functions mostly are faster, independent from your configurations. So, use array_flip().
Talk is cheap...
This is what I tested (feel free to configure variables yourself):
// The ratio of array size being increased
$arraySizeBase = 10;
// Limits of the exponention of the array size
$arraySizePowerMin = 1;
$arraySizePowerMax = 6;

// Number of tests being run within one time capture
$iterationsCount = 100;
// Number of time capture repeats
$repeatCount = 20;
// Precision of rounded result
$precision = 5;

// Array values limits
$minVal = 0;
$maxVal = 10000;

function printTime(callable $x, string $title)
{
    global $iterationsCount, $repeatCount, $precision;

    $tests = [];
    for ($i = 0; $i < $repeatCount; $i++) {
        $startTime = microtime(true);

        for ($j = 0; $j < $iterationsCount; $j++) {
            $x();
        }

        $tests[] = microtime(true) - $startTime;
    }

    $averageTime = array_sum($tests) / $repeatCount;
    echo "  Average time for $title: ", round($averageTime, $precision), PHP_EOL;

    // To be used to calculate ratio
    return $averageTime;
}

$arraySizeMin = $arraySizeBase ** $arraySizePowerMin;
$arraySizeMax = $arraySizeBase ** $arraySizePowerMax;

for ($i = $arraySizeMin; $i <= $arraySizeMax; $i *= $arraySizeBase) {
    // Filling the array with some random stuff
    echo "Testing an array with $i elements:", PHP_EOL;
    $array = array_fill(0, $i - 1, random_int($minVal, $maxVal));

    $arrayFlipTime = printTime(function () use ($array) {
        $flippedArray = array_flip($array);

        // Don't be crazy, clean RAM
        $flippedArray = null;
    }, "array_flip()");

    $foreachTime = printTime(function () use ($array) {
        $flippedArray = [];
        foreach ($array as $key => $value) {
            $flippedArray[$value] = $key;
        }

        // Don't be crazy, clean RAM
        $flippedArray = null;
    }, "foreach");

    // Print a ratio in percentage
    echo "  How much array_flip() is faster: ",
        floor(($foreachTime / $arrayFlipTime) * 100) - 100, "%",
        PHP_EOL;

    echo PHP_EOL;
}

A: You should be able to use the key from the foreach for indexes and build the array pre-flipped like this.
    foreach ($resultCollection as $key => $output) {
        $op[ $output['outputId'] ] = $key;
    }

A: Well, since it doesn't look like you care about the value, bur rather just the O(1) lookup speed of the keys, I'd build the $op that way the first time
foreach ($resultCollection as $output)
{
  $op[$output['outputId']] = null;
}

Or you can look into in_array(), I don't know how its speed compares. (Seems like this is 0(n), so not faster)
EDIT
If you wanted to create the first time around what you were getting after array_flip(), do it this way.
$i = 0;
foreach ($resultCollection as $output)
{
  $op[$output['outputId']] = $i++;
}

But after your comments, I'm still not sure if I really "get" what you're after.


text:
Q: Databinding custom objects and populating controls with unique values etc I have a custom object that gets values form a table in a db.  Lets call it - Product table.
My code populates a List<Product> and binds to several comboboxes using myCombobox.DisplayMember = "Country" in order to display the correct values.
Here's the sample code (nothing out of the ordinary, OnFormLoad()).
DatabaseTools dbTools = new DatabaseTools();
List<Product> productList = dbTools.GetProducts();

cboCountry.BeginUpdate();
cboCountry.DataSource = productList ;
cboCountry.DisplayMember = "Country";
cboCountry.EndUpdate();

Simple enough.  However some of the values returned from the database are either missing, duplicated or need string formatting before they get displayed in the control.  Is there a way to do this.  Otherwise the data in my comboboxes looks awful:

A: To prevent duplicated product use a EqualityComparer :
 public class ProductCountryEqualityComparer : IEqualityComparer<Product>
    {

        #region IEqualityComparer<Product> Members

        public bool Equals(Product x, Product y)
        {
            return x != null && y != null && x.Country  == y.Country;
        }

        public int GetHashCode(Product obj)
        {
            return 0;
        }

        #endregion
    }

Then :
//That will make products distincts according to there Country
productList = productList.Distinct(new ProductCountryEqualityComparer()).ToList();

To format country :
productList = productList.Distinct(new ProductCountryEqualityComparer())
              .Select(f => new Product()
              {
               Country = string.Format(f.Country,"SomeFormat")
              }).ToList();

To Order :
productList = productList.Distinct(new ProductCountryEqualityComparer())
              .Select(f => new Product()
              {
               Country = string.Format(f.Country,"SomeFormat")
              }).OrderBy(f => f.Country).ToList();

Just use last one :)

A: Why not LINQ, saves having to hit the database and as you are not using a unique ID for your country objects, this should work...
            List<string> countries = new List<string>()
            { "Brazil", "Pakistan", "Pakistan", "Norway", "Senegal", "Senegal", "Senegal", };
            // Place into a LINQ query and utilise the distinct keyword
            var unique = (from c in countries
                          select c).Distinct().ToArray();
            // Test output
            Array.ForEach<string>(unique, x => Console.WriteLine(x));
            Console.ReadKey();


text:
Q: Is there any way to get the file where a class was instantiated in auto-loading features in PHP? Its similar question of Is there an easy way to get the file where a class was instantiated in PHP? but with different approach.
I need to know the source in autoloading (__autoload() or spl_autoload()) functions so that  I can load right class of sub-namespacing
Lets illustrate my problem a little bit by an example -
Please consider my following classes:
/my/project/root/faculties/faculty.class.php [namespace: faculties]
/my/project/root/faculties/faculty1/faculty.class.php [namespace: faculties/faculty1]
/my/project/root/faculties/completely/different/project/at/deep/project/root/faculties/faculty.class.php [namespace: faculties]
Now if I want to access instance of that different project its conflict with root project cause its same namespace.


text:
Q: ssas dimension processing incremental I am having a large dimension and it is taking me more and more time to process it. I would like to decrease the processing time as much as possible
there is literally hundreds of different articles  on how to process ssas objects as efficient and fast as possible.
There are lots of tips and tricks that one can apply to speed up dimensions and cube processing. I managed to apply all or at least a big majority of them and I am still not happy with the result,.
I have a large dimension built on top of a table.
It has around 60 mil records and it keeps on growing fast.
It either add new rows to it or delete the existing ones. there are no updates possible
I am looking for a solution that will allow me to perform an incremental processing of my dimension.
I know that the data in the previous month will not be changed. I would like to do smth similar to partitioning of my cube but on the dimension.
I am using SLQ SERVER 2012 and to my knowledge dimension partitioning is not supported.
I am currently using process update on my dimension - I tried processing using by attribute and by table but both render almost the same result. I have hierarchies and relationships - some set to rigid. I am only using those attributes that are truly needed etc etc etc
process update has to read all the records in a dimension even those that i know have not changed. is there a way to partition a dimension? if I could tell SSAS to only process the last 3-4 weeks of data in my dimension and not touch the rest - it would greatly speed up my processing time.
I would appreciate your help

A: ok so I did a bit of research and I can confirm that incremental dimension processing is not supported.
it is possible to do process add on a dimension but if you have records that got deleted or updated you cannot do that
it would be a useful thing to have but MS hasn't developed it and I don't think it will
incremental processing of any table is however possible in tabular cubes
so if you have a similar requirement and your cube is not too complex then creating a tabular cube is the way to go


text:
Q: Emberjs DefaultTo Computed Property Often, I want my views to default to a specific value if the actual model property is not set.
This placeholder text/value is strictly view only and hence, should not be placed in the model imo.
So, this is what I end up doing:
// Sample 'Model' for illustration purposes only.
var myModel = Ember.Object.extend({
  title: null,

  description: null,

  thumbUrl: null
});

/**
 * Sample View
 * Render view properties which are actually
 * computed of the actual 'content' properties
 */
var myView = Ember.View.extend({
  template: Ember.Handlebars.compile('
Title: {{view.title}}

Description: {{view.description}}

Image:
'),

  title: function () {
    return this.get('content.title') || 'Title goes here';// placeholder 'title' text
  }.property('content.title'),

  description: function () {
    return this.get('content.description') || 'This is your description'; // placeholder 'description'
  }.property('content.description'),

  thumbUrl: function () {
    return this.get('content.thumbUrl') || 'http://placehold.it/100x100';
  }.property('content.thumbUrl')
});

Any suggestions on how can I reduce boilerplate on defining defaults on all those properties i.e. 'title', 'description' and 'thumbUrl' ?
I looked into Ember.computed.defaultTo but failed to understand on how I can use it. This is how I envision it in action:
var myView = Ember.View.extend({
  template: Ember.Handlebars.compile('
Title: {{view.title}}

Description: {{view.description}}

Image:
'),

  title: Ember.computed.defaultTo('content.title', 'Title goes here'),

  description: Ember.computed.defaultTo('content.description', 'This is your description'),

  thumbUrl: Ember.computed.defaultTo('content.thumbUrl', 'http://placehold.it/100x100')
});

So how can this be done ?
If there are better approaches to do this type of a thing, I would like to hear them in the comments.
Also, pointers to what Ember.computed.defaultTo does would be really helpful as well.

A: This is not what Ember.computed.defaultTo is intended to do. Ember.computed.defaultTo takes a single defaultPath parameter. From the docs:

computed property which acts like a standard getter and setter, but defaults to the value from defaultPath.

If you read the test, it sheds some light.
testBoth('Ember.computed.defaultTo', function(get, set) {
  var obj = { source: 'original source value' };
  Ember.defineProperty(obj, 'copy', Ember.computed.defaultTo('source'));

  equal(get(obj, 'copy'), 'original source value');

  set(obj, 'copy', 'new copy value');
  equal(get(obj, 'source'), 'original source value');
  equal(get(obj, 'copy'), 'new copy value');

  set(obj, 'source', 'new source value');
  equal(get(obj, 'copy'), 'new copy value');

  set(obj, 'copy', null);
  equal(get(obj, 'copy'), 'new source value');
});

Instead, you could write your own helper like so:
Ember.computed.defaultValue = function(dependentKey, defaultValue) {
  return Ember.computed(dependentKey, function() {
    return Ember.get(this, dependentKey) || defaultValue;
  });
};

var myView = Ember.View.extend({
  template: Ember.Handlebars.compile('
Title: {{view.title}}

Description: {{view.description}}

Image:
'),

  title: Ember.computed.defaultValue('content.title', 'Title goes here'),

  description: Ember.computed.defaultValue('content.description', 'This is your description'),

  thumbUrl: Ember.computed.defaultValue('content.thumbUrl', 'http://placehold.it/100x100')
});

If you'd rather not create your own helper function, an alternative approach would be to use separate properties for default values and then use Ember.computed.any.
var myView = Ember.View.extend({
  template: Ember.Handlebars.compile('
Title: {{view.title}}

Description: {{view.description}}

Image:
'),

  defaultTitle: 'Title goes here',
  title: Ember.computed.any('content.title', 'defaultTitle'),

  defaultDescription: 'This is your description',
  description: Ember.computed.any('content.description', 'defaultDescription'),

  defaultThumbUrl: 'http://placehold.it/100x100',
  thumbUrl: Ember.computed.any('content.thumbUrl', 'defaultThumbUrl')
});


text:
Q: How to resolve npm ERR! Code ERR_INVALID_URL in cypress In my windows-10, I installed:
nodejs-v 16.14.0
npm -v 8.3.1

When I tried to run npm install cypress -save-dev
I got this error:
npm ERR! code ERR_INVALID_URL
npm ERR! Invalid URL

How do I get this resolved?


text:
Q: JSON.parse: unexpected non-whitespace character after JSON data at line 1 I am using a really easy JavaScript (AngularJS, but that is not relevant) like:
app = angular.module('app', []);
app.controller("NavCtrl",function($scope,$http){
    var serviceBase = 'api/';
    $http.get(serviceBase + 'orders').then(function (results) {
        $scope.categories = results.data;
    var total = 0;
    for(var i = 0; i < $scope.categories.length; i++){
        var categories = $scope.categories[i];
    }
    });
});

HTML

       Sander

1 minutes

                  {{p.orderID}}

API
//PHPSLIM
require '.././libs/Slim/Slim.php';
\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();
$app = \Slim\Slim::getInstance();

//GET ALL ORDERS
$app->get('/orders', function(){
$extranames = "";
$extrasprice = 0;
    global $conn, $servername, $username, $password, $dbname;
    $sql = "SELECT `orderID`, `customerID`, `storeID`, `orderDate`, `orderDeliveryDate`, `orderStatus` FROM `order`";

    mysql_connect($servername, $username, $password);
    mysql_select_db($dbname);
    $query = mysql_query("SELECT `orderID`, `customerID`, `orderDate`, `orderDeliveryDate`, `orderStatus` FROM `order`");
    $ordersall = array();

    while($line = mysql_fetch_array($query, MYSQL_ASSOC)){
        $orders[] = $line;
    }

    $count = 0;
    $extrasprice = 0;

    foreach($orders as $key => $looporders){
        $extracounter = 1;

        $sql = "SELECT `orderdetailID`, `productID`, `orderdetailAantal`  FROM `orderdetail` WHERE `orderID` = '$looporders[orderID]'";
        $result = $conn->query($sql);

        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
            $sql2 = "SELECT `productTitle`, `productPrijs`  FROM `products` WHERE `productID` = '$row[productID]'";
            $result2 = $conn->query($sql2);
                if($result2->num_rows > 0) {
                    while($row2 = $result2->fetch_assoc()){
                        $productTitle = $row2["productTitle"];
                        $productPrijs = $row2["productPrijs"];

                    }
                }
            $sql3 = "SELECT `customerName` FROM `customers` WHERE `customerID` = '$looporders[customerID]'";
            $result3 = $conn->query($sql3);
                if($result3->num_rows > 0) {
                    while($row3 = $result3->fetch_assoc()){
                        $customerName = $row3["customerName"];
                    }
                }
            $sql4 = "SELECT `extraID` FROM `orderdetailextra` WHERE `orderdetailID` = '$row[orderdetailID]'";
            $result4 = $conn->query($sql4);

            if ($result4->num_rows > 0) {
                while($row4 = $result4->fetch_assoc()) {
                    $sql5 = "SELECT `extraName`, `extraPrice` FROM `extra` WHERE `extraID` = '$row4[extraID]'";
                    $result5 = $conn->query($sql5);
                    if ($result5->num_rows > 0) {
                     while($row5 = $result5->fetch_assoc()) {

                        $extranames = $extranames . $row5["extraName"]. ', ';
                        $extrasprice += $row5["extraPrice"];
                     }
                    }
                 }
                }

                $ordersall[$count] = array(
                "orderID" => $looporders["orderID"],
                "customerID" => $looporders["customerID"],
                "customerName" => $customerName,
                "orderDate" => $looporders["orderDate"],
                "orderDeliveryDate" => $looporders["orderDeliveryDate"],
                "orderStatus" => $looporders["orderStatus"],
                "orderdetailID" => $row["orderdetailID"],
                "productTitle" => $productTitle,
                "productPrijs" => $productPrijs,
                "aantal" => $row["orderdetailAantal"],
                "extras" => substr($extranames, 0, -2),
                "extrasPrice" => $extrasprice
            );

                $count++;
                $extranames ="";
                $extrasprice = 0;

            }
        }

    }

    echoResponse(200, $ordersall);

});

$app->run();

function echoResponse($status_code, $response) {
    global $app;
    $app->status($status_code);
    header('Content-Type: application/json');
    $app->contentType('application/json');
    echo json_encode($response,JSON_NUMERIC_CHECK);
}

JSON
[{"orderID":4,"customerID":1,"customerName":"Sander","orderDate":"2015-04-20 09:49:06","orderDeliveryDate":"2015-04-20","orderStatus":"done","orderdetailID":2,"productTitle":"Sexy Teacher","productPrijs":4,"aantal":1,"extras":"","extrasprice":""},
{"orderID":5,"customerID":2,"customerName":"Jelle","orderDate":"2015-04-20 12:05:09","orderDeliveryDate":"2015-04-20","orderStatus":"prepare","orderdetailID":3,"productTitle":"The Coach","productPrijs":3,"aantal":1,"extras":"","extrasprice":""},

    {"orderID":5,"customerID":2,"customerName":"Jelle","orderDate":"2015-04-20 12:05:09","orderDeliveryDate":"2015-04-20","orderStatus":"prepare","orderdetailID":4,"productTitle":"The Virgin","productPrijs":3.2,"aantal":1,"extras":"","extrasprice":""},

    {"orderID":5,"customerID":2,"customerName":"Jelle","orderDate":"2015-04-20 12:05:09","orderDeliveryDate":"2015-04-20","orderStatus":"prepare","orderdetailID":5,"productTitle":"Sexy Teacher","productPrijs":4,"aantal":3,"extras":"","extrasprice":""},

    {"orderID":22,"customerID":11,"customerName":"Tom","orderDate":"2015-04-20 14:15:12","orderDeliveryDate":"2015-04-20","orderStatus":"prepare","orderdetailID":22,"productTitle":"The Virgin","productPrijs":3.2,"aantal":1,"extras":"","extrasprice":""},

    {"orderID":22,"customerID":11,"customerName":"Tom","orderDate":"2015-04-20 14:15:12","orderDeliveryDate":"2015-04-20","orderStatus":"prepare","orderdetailID":23,"productTitle":"The Virgin","productPrijs":3.2,"aantal":1,"extras":"","extrasprice":""}]

Now I am getting an error:

JSON.parse: unexpected non-whitespace character after JSON data at line 1.

Is there something wrong with my JavaScript or PHP and how can this be fixed?
I don't think there is anything wrong with my code or data I am passing on...

A: You shouldn't use JSON.parse on an array of JSON objects, please use instead something like:
for (var i = 0; i < jsonData.length; i++) {
    console.log(jsonData.orderID);
}

Also, I can't see any field categories in your JSON result.


text:
Q: Swift - Looping over a struct array This is so basic, I'm a little embarrassed to ask, but... I'm retrieving some JSON from my server into these structs:
struct CategoryInfo: Codable {
    var categoriesResult: [CategoryDetail]
}

struct CategoryDetail: Codable{
    var categoryName: String
    var categoryDescription: String
    var categorySortOrder: Int
    var categoryId: String
}

And now I want to loop over CategoryDetail for each of the few-dozen occurrences, saving them into CoreData.  My current attempt looks like this:
            let decoder = JSONDecoder()
            do {
                let categories = try decoder.decode(CategoryInfo.self, from: data!)
                for category in [CategoryDetail] {
                    //... perform the CoreData storage here
                }

But I get the error that CategoryDetail either doesn't conform to Sequence or to IterateProtocol, but when I try to implement those, the solution appears, frankly, too complicated. It's just an array... shouldn't I be able to loop over it without a lot of hoohaw (using that in a technical sense, of course)?

A: Please take a closer look at your structs
You are decoding the CategoryInfo struct
let categoryInfo = try decoder.decode(CategoryInfo.self, from: data!)

and the categories are in the categoriesResult member
for category in categoryInfo.categoriesResult {
    //... perform the CoreData storage here
}


text:
Q: Using replace and concat in MySQL I have strings values such as the following in a column:
|333|,|331|

I want to perform a balanced string replacement as follows:
xxTM_333_TMxx,xxTM_331_TMxx

I have tried to do this with the REPLACE and CONCAT functions but didn't get the desired output.
For example:
SELECT REPLACE('|333|,|331|','|','xxTM');

This replaces one of the | symbols correctly in each case, but not its matched (balanced) counterpart.
How can I achieve this result in MySQL?

A: SET @st := '|333|,|331|';

SELECT
  CASE WHEN @st LIKE '|%|' THEN
    CONCAT(
      'xxTM',
      REPLACE(REPLACE(@st, '|,|', '_TMxx,xxTM_'), '|', '_'),
      'TMxx')
  END rep_st;

Please see fiddle here.


text:
Q: jqGrid set SubGrid width to the row width I'm creating the jqGrid with a simple Subgrid.
I have set the property
autowidth:true
so that the jqGrid expands to the width of the parent element. When I
expand the row the Subgrid doesn't expand to the width of the jqGrid. The width of the Subgrid remains the sum of all Subgrid columns. Is this an expected behavior or a bug?
Do I need to use jQuery to manually set the width of the Subgrid or is there an another way?
This is an example of the code that I use:
jQuery("#list").jqGrid({
    url:'some-url.php',
    mtype: "POST",
    datatype: "json",
    colNames:['Inv No','Date','Total'],
    colModel:[
                {name:'id',index:'id', width:55},
                {name:'amount',index:'amount', width:55},
                {name:'tax',index:'tax', width:55}
    ],
    multiselect: false,
    autowidth: true,
    rowNum:10,
    rowList:[10,20,30],
    pager: '#pager',
    sortname: 'id',
    sortorder: "desc",
    viewrecords: true,
    subGrid : true,
    subGridUrl: 'some-other-url.php',
    subGridModel: [ {name:['CustomerId','CustomerName'], width:[55,55,]} ],
    caption: "Subgrid Example",
    sortable: true
});

jQuery("#list").jqGrid('navGrid','#pager',{add:false,edit:false,del:false});

A: I have found alternative solution, but it requires creating jqGrid as subgrid. Then the width of the sub grid can be adjusted as we want.
This is as example of the code, I hope that somebody will find it useful:
   $("#list").jqGrid({
    url:'some-url.php',
    mtype: "POST",
    datatype: "json",
    colNames:['Inv No','Date','Total'],
    colModel:[
                {name:'id',index:'id', width:55},
                {name:'amount',index:'amount', width:55},
                {name:'tax',index:'tax', width:55}
    ],
    multiselect: false,
    autowidth: true,
    rowNum:10,
    rowList:[10,20,30],
    pager: '#pager',
    sortname: 'id',
    sortorder: "desc",
    viewrecords: true,
    subGrid : true,
    subGridRowExpanded: function(subgrid_id, row_id) {
    var subgrid_table_id, subgrid_pager_id, desired_width;
            subgrid_table_id = subgrid_id+"_t";
            subgrid_pager_id = "p_"+subgrid_table_id;
            desired_width = $("#list").width();
            desired_width -= 25;  // adjust this value as needed
            $("#"+subgrid_id).html("

");
                jQuery("#"+subgrid_table_id).jqGrid({
                url:"subgrid-url.php?id="+row_id,
                datatype: "json",
                colNames: ['No','Item','Qty','Unit','Line Total'],
                colModel: [ {name:"num",index:"num",width:80,key:true},
                            {name:"item",index:"item",width:130},
                            {name:"qty",index:"qty",width:70,align:"right"},
                            {name:"unit",index:"unit",width:70,align:"right"},
                            {name:"total",index:"total",width:70,align:"right",sortable:false}
                ],
                rowNum:20,
                pager: pager_id,
                sortname: 'num',
                sortorder: "asc",
                height: '100%',
                autowidth: false,
                width: desired_width
            });
        },
    caption: "Subgrid Example",
    sortable: true
});

A: You could use CSS:
td.subgrid-data div.tablediv table {
  width: 100%
}


text:
Q: javascript алгоритмы и структуры данных Подскажите пожалуйста,очень часто в вакансиях и стажировках по javascript пишут,что нужно знание алгоритмов и структур данных.Где лучше их изучить и насколько глубоко их нужно знать?Сорри,если глупые вопросы задаю..

A: Алгоритмы и структуры данных не связаны с конкретным языком программирования.
Это, так сказать, общие теоретические знания.
Изучить можно много где. Классика: это книги Дональда Кнута.
Можно еще почитать книги Роберта Седжвика. У него так же есть курс на Coursera.
Ну или просто почитать в инете про такие вещи как список, стек, очереди, хеш и дальше по ссылкам в википедии :)


text:
Q: Limit number of data points rendered I am trying to render cities on the map, using Geonames' dataset (source). I have downloaded the top 10000 cities as a GeoJSON file, and loaded it into QGIS. However, when I zoom out, this shows too many points: they completely fill the map.
I have enabled labels, and there is the option under Layer Properties › Labels › Rendering › Feature Options to limit the number of features rendered. This way, only the largest cities in an area will be labelled (I have set render priority to be based on population), but when I zoom in I can see more city names appear.
Is it possible to apply a similar limit to the symbols themselves? Can I hide all but the largest 100 cities within the viewport? I do not want to hard-code limits for population and zoom level, because I would like cities in less populous areas to appear sooner when zooming in there.

A: There are several ways I can think of to address this situation using the Expression Builder, or even using a custom python function. Because of the size of the layer, however, these can be incredibly resource-intensive.
There is, thankfully, an easier, sneakier way, using the label settings you've already established. This will result in label text which is fixed in its position, but this can be addressed with a few extra steps. Here's how it works:

*

*On the Background tab, enable label backgrounds.

*Choose Marker Symbol as the background type.

*Adjust the symbology of the marker as necessary.

*Adjust symbol placement and offsets so that marker symbol is properly placed.

*

*You'll want to choose "offset from point" under Placement, and choose for the label to be placed directly on top of the point.

*If you're labeling the city name using the same layer, make sure that whatever offset you choose to move the text off of the point, that the inverse of that offset is applied to the background marker symbol.

*(Optional) Get dynamic label text back.

*

*Set the label text to a single whitespace character.

*Duplicate the layer.

*On the new layer, remove the marker symbol, and re-set the label text to the "name" field, or whichever you are using.

*Adjust the labeling properties on the new layer to get the text to your liking. You may need to change some of the labeling priority weights between the two layers.

In my map, I offset the "label" by -4. By offsetting the background marker symbol by +4, the point will render directly on top of the geometry feature.

And here are the results. I've left the actual feature layer being rendered just to show that it is highlighting the larger population points correctly. With this label setting, I can actually opt to uncheck the Enable symbol layer box on the symbology tab, and let the label points take their place entirely.

And here's the same setup at a much broader scale, with the point features no longer being rendered.

A: In fact, the rendering style cluster does something similar, only that points that are too close are not suppressed, but clustered in a separate symbol. However, you can use this at least as a workaround by adapting to your needs.
Choose clustering as rendering style for your points layer. Than define your cluster symbol and set it as completely transparent. Define the distance for clustering, so all points that are closer than this value will be clustered - and thus be transparent.
Alternatively, you could also use a date-driven size for the cluster, defining in an expression the conditions when size should be 0 (thus invisible). Also play around with Control feature rendering order, see: https://docs.qgis.org/3.10/en/docs/user_manual/working_with_vector/vector_properties.html#layer-rendering