text:
Q: When allowing istio to manage authorization, how can I properly run and debug my application locally given istio only runs on kubernetes? I have recently starting switching some of my apps to abstract out the authorization to istio and it works great. I have been testing the application by deploying a kube cluster locally with Tilt, however I don't think I'd want to have each dev be forced to deploy an entire kubernetes cluster just to work on their app. You also lose things like running/debugging code in your IDE which is obviously far from ideal.
Our devs currently run some backend projects locally with a ui and need to be able to test e2e because some services for example check does a user have access to a particular resource via db lookup, so if they are not running istio the backend would be forced to also implement the jwt serialization which kinda destroys the point of have the auth managed in istio....
Has anyone come up with a soluton for this case?


text:
Q: Laravel querying eager load I've got this query in Laravel:
return Forum::with(['users' => function($query){
            $query->select('user.id', 'user.name', 'user.last_name');
        }])->latest()->withCount('messages')->paginate(10);

This returns all users that have posted a message in a forum.
On my forum model I've these relations:
public function users()
{
    return $this->belongsToMany(User::class, 'message');
}

public function messages()
{
    return $this->hasMany(Message::class);
}

I would like to receive only the latest user that has posted a message. How could I do this?

A: You can retrieve the last user by messages relationship, try this:
return Forum::with(['messages' => function($query){
    $q->orderBy('created_at', 'desc');
},'messages.users'])->first();

A: Use has() method and order by created_at in descending order.
User::has('forums.messages')->orderBy('created_at','desc')->first();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calculated Column Duplicate Values I am fairly new to access. I am trying to create a column that calculates duplicates values in a query. Taking in consideration that the duplicates value may change after other few filters taking action.
Supplier    Spec   SupplierDuplicate
   A         X            2
   B         Y            1
   A         Z            2
   C         X            1

I most appreciate your help!

A: I think you can run a SELECT query with DCount() function to get expected result.
SELECT Table1.Supplier, Table1.Spec, DCount("[Supplier]","[Table1]","[Supplier]='" & Table1.Supplier & "'") AS SupplierDuplicate FROM Table1;


text:
Q: How to make finite loop in Arduino I'm a beginner in coding and especially in Arduino. I have been doing many projects, but I came across a problem. I can't seem to be able to figure out how to make a finite loop. I'm looking at something like a while loop which stops after four times around. Here is where it will be implemented to give you a better idea of what I'm looking for.
#include <Servo.h>

int thumbPin = 2;
int ndxPin = 3;
int midPin = 4;
int rngPin = 5;
int pnkyPin = 6;

Servo thumb;
Servo index;
Servo middle;
Servo ring;
Servo pinky;
void setup() {
  Serial.begin(9600);

  thumb.attach(thumbPin);
  index.attach(ndxPin);
  middle.attach(midPin);
  ring.attach(rngPin);
  pinky.attach(pnkyPin);
}
void loop() {
  /* I want this code in the comment to be ran four times, then continued on to the code after
  thumb.write(0);
  delay(20);
  thumb.write(0);
  index.write(0);
  middle.write(0);
  ring.write(0);
  pinky.write(0);

  thumb.write(150);
  index.write(150);
  middle.write(150);
  ring.write(150);
  pinky.write(150);
  */
  thumb.write(0);
  index.write(0);
  pinky.write(0);

  middle.write(0);
  thumb.write(150);
  pinky.write(150);
}

A: You want a for loop: https://www.arduino.cc/en/Reference/For
for (int i = 0; i < 4; i++) {
  thumb.write(0);
  delay(20);
  thumb.write(0);
  index.write(0);
  middle.write(0);
  ring.write(0);
  pinky.write(0);

  thumb.write(150);
  index.write(150);
  middle.write(150);
  ring.write(150);
  pinky.write(150);
}


text:
Q: Core Data: Inserting a new row after performing fetch I'm having trouble figuring out this GCD problem.
Let's say there's one UITableViewCell in the table view. This cell has some text fields that the user is editing. After the user finishes editing, the cell creates a new object in Core Data based on what the user typed in. This object is inserted with insertNewObjectForEntityForName.
After this, I need to performFetch on the NSFetchedResultsController and reload the tableview. However, I also want to add a new cell to the end of the tableview, so the user can add another item to their list.
This is what I'm doing to try that:
dispatch_async(dispatch_get_main_queue(), {
    do {
        try self.fetchedResultsController.performFetch()
    } catch {
        fatalError("Fetch failed: \(error)")
    }

    self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: self.fetchedResultsController.sections!.first!.numberOfObjects - 1, inSection: 0)], withRowAnimation: .Automatic)
    self.tableView.reloadData()
})

The new cell is added, but without the row animation. I think there's something I'm misunderstanding with GCD and Core Data. Thanks for the help.

A: Need to use first closure as the thread process that running asynchronously. Once the process done, it will go into second closure which is on the main thread to do anything with your view
dispatch_async(dispatch_get_global_queue(priority, 0)) {

        // process here
        do {
            try self.fetchedResultsController.performFetch()
        } catch {
            fatalError("Fetch failed: \(error)")
        }
        dispatch_async(dispatch_get_main_queue(), { Void in
            // then refresh UI
            self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: self.fetchedResultsController.sections!.first!.numberOfObjects - 1, inSection: 0)], withRowAnimation: .Automatic)
            self.tableView.reloadData()
        })
    }

check this tutorial for details https://www.raywenderlich.com/79149/grand-central-dispatch-tutorial-swift-part-1

A: Fixed this by implementing:
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?)

Using a switch statement inside of this function allows for more control over each change that occurs:
switch type {
    case NSFetchedResultsChangeType.Insert:
        print("Insert")
    case NSFetchedResultsChangeType.Delete:
        print("Delete")
    case NSFetchedResultsChangeType.Update:
        print("Update")
    case NSFetchedResultsChangeType.Move:
        print("Move")
}

Inside this switch, you can use the indexPath to remove cells, add cells, whatever you want. Just use insertRowsAtIndexPaths or another relevant function.


text:
Q: Powershell error message in console is being wrongly indented What I am trying to do is run the wsl process, get its stdout and stderr channels to print to console as if they were executing normally, throw an error in powershell if stderr and for the printout to be 1:1 as the original.
But I am getting this indentation error:
when running wsl.exe echo a 1`>`&2`;echo b 2>&1 twice
Powershell's console is being overindented than it should be.
it sometimes even gets so bad that Write-Host output is being indented despite no indentation.
wsl.exe echo a 1`>`&2`;echo b 2>&1

cmd.exe /c echo a 1`>`&2`&echo b 2>&1

Sometimes this also happens after running a lot of the wsl command above

further more, when it gets stuck like that it infect other Write-Error calls:

$PSVersionTable
Name  |Value
----|-----
PSVersion|5.1.22000.282
PSEdition|Desktop
PSCompatibleVersions|{1.0, 2.0, 3.0, 4.0...}
BuildVersion|10.0.22000.282
CLRVersion|4.0.30319.42000
WSManStackVersion|3.0
PSRemotingProtocolVersion|2.3
SerializationVersion| 1.1.0.1
Edit:

A: While I have no explanation for the behavior, I have a workaround:
Enclose the entire command in (...) (I've also rewritten the command to make it more obvious what it does, but it is functionally equivalent):
# !! The (...) makes the symptom go away.
(wsl.exe bash -c 'echo a 1>&2; echo b' 2>&1)

Note:

*

*Using (...), the grouping operator, means that the all output lines from the wsl.exe call are collected up front before being output to PowerShell's pipeline. That is, you forgo PowerShell's streaming behavior of relaying the output lines as they're being received. That said, that won't be a problem in practice, unless the call at hand emits so many lines that collecting them all in memory would run out of memory or the act of collecting them would cause an unacceptable delay, if (themselves streaming) downstream commands such as Tee-Object are expected to produce display output in a timely fashion.

The symptom you're seeing is related to how the formatting system renders the System.Management.Automation.ErrorRecord instances that stderr lines are wrapped in, but how the problem occurs and why it only starts surfacing from the second invocation on is unclear to me.

Two asides:

*

*That stderr lines (2) redirected (>) to the success error stream (&1) render as errors is fundamentally problematic.

*

*In PowerShell (Core) 7+, this no longer happens (even though the stderr lines are still wrapped in [ErrorRecord] instances).

*To emulate this behavior in Windows PowerShell, call .ToString() on each output object:
wsl.exe bash -c 'echo a 1>&2; echo b' 2>&1 | ForEach-Object ToString

*The way PowerShell merges stdout and stderr when 2>&1 is used does not guarantee the original output ordering; that is, the above command either may either output a before b, or vice versa - unpredictably so; see GitHub issue #5424.


text:
Q: Prove algorithm to find a tour in an even degree graph by induction. Suppose I have an even degree undirected graph G. Given an algorithm to find a tour in G FINDTOUR(G,s), where s is the starting vertex, prove by induction on the length of the walk that the only place the algorithm will get stuck is at s.
FINDTOUR(G,s): start by walking from a vertex s, at each step choose an untraversed edge incident to the current vertex until you get stuck.
Proof by induction on n, the length of the walk in an even degree graph G=(V,E)
Base Case: for n=0 the claim is trivially true as there is no tour.
Inductive Hypothesis: Suppose that for a walk of length $n = k \geq 0$ the algorithm gets stuck at the starting vertex.
*Inductive Step: This is where I'm unsure of how to proceed.
Intuitively the claim makes sense because if the graph has an even degree then every vertex $v \neq s$ will have an odd number of untraversed incident edges to it.


text:
Q: Python & JSON - Appending to String Object Relatively new to using JSON & Python, but running into an issue trying to append to an existing JSON object. First, some pseudo-code:

*

*Want to use a JSON "template" for each append, so that is created

*The first item in a new list will always be this template (index 0)

*Once a new record is found, the template is appended to the object and then populated

I've tried json.update and dict.append and just concatenating to a string, but I keep getting either list index out of range (current error with code below) or append errors.
Please help!
def parse(self, response):
    # Create Store JSON template
    unit_JSON_template = {
        "Store": [
        {
            "ID": "",
            "Seller":
            {
                "Name": ""
            },
            "Detail":
            {
                "StoreURL": "",
                "Title": "",
                "Stock": "",
                "Other": "",
                "Images": [
                {
                    "Url": "",
                    "Encode": "",
                    "Title": ""
                }
                ],
                "Request":
                {
                    "DateTime": "",
                    "RequestHeaders": "",
                    "ResponseHeaders": ""
                }
            }
        }
        ],
    }

    # Convert template string to JSON
    unit_JSON_str = json.dumps(unit_JSON_template, indent = 4, separators = (", ", ": "), sort_keys = False)
    print(unit_JSON_str)
    unit_JSON_obj = json.loads(unit_JSON_str)
    unit_JSON = unit_JSON_obj

    # Create identifying information
    record = response.url.split("/")[2] + "-" + response.url.split("/")[-2]
    record_timestamp = datetime.now().strftime("%m%d%Y%-H%M%S")
    page_filename = f'{record}-{record_timestamp}.html'
    screenshot_filename = f'{record}-{record_timestamp}.png'

    # Parse data, load to JSON object for Insert to SQL
    data_units = response.xpath("//candy-stores")
    print("Units Found: " + str(len(data_units)))

    # Loop over each object and insert into JSON object (index 0 always template above)
    for i, data_unit in enumerate(data_units):
        i_1 = i + 1 #do this since template is always index 0
        unit_JSON.update(unit_JSON_obj)
        print(json.dumps(unit_JSON, indent=4))

        unit_JSON['Store'][i_1]['Detail']['Title'] = "Store Name"
        unit_JSON['Store'][i_1]['Detail']['StoreURL'] = "Unit"
        unit_JSON['Store'][i_1]['Detail']['Request']['DateTime'] = "12:00pm"
        unit_JSON['Store'][i_1]['Detail']['Other'] = "Additional Data"
        unit_JSON['Store'][i_1]['Seller']['Name'] = "ABC Candy"

A: You are very much overcomplicating this. Inside your python code, don't use JSON, but a list of dicts. Convert to JSON when you need to provide said JSON.
Take a look at how I would handle this. A simple helper function to add a new dict item to the list of dict items.
I've included some examples on printing this, assigning a JSON string, and saving a JSON file.
You will need to handle the images in the not_a_json_object, I didn't include this part.
As for the IndexError, you do this i_1 = i + 1 and then try to access the element on the list based on that.
import json
from pprint import pprint

def new_dict_from_template(
    storeid="",
    sellername="",
    storeurl="",
    title="",
    stock="",
    other="",
    images=[],
    req_datetime="",  # named to prevent name collision
    requestheaders="",
    responseheaders="",
) -> dict:
    return {
        "Store": [
            {
                "ID": storeid,
                "Seller": {"Name": sellername},
                "Detail": {
                    "StoreURL": storeurl,
                    "Title": title,
                    "Stock": stock,
                    "Other": other,
                    "Images": images,
                    "Request": {
                        "DateTime": req_datetime,
                        "RequestHeaders": requestheaders,
                        "ResponseHeaders": responseheaders,
                    },
                },
            }
        ],
    }

def parse(self, response):
    # Create identifying information
    record = response.url.split("/")[2] + "-" + response.url.split("/")[-2]
    record_timestamp = datetime.now().strftime("%m%d%Y%-H%M%S")
    page_filename = f"{record}-{record_timestamp}.html"
    screenshot_filename = f"{record}-{record_timestamp}.png"

    # Parse data, load to JSON object for Insert to SQL
    data_units = response.xpath("//candy-stores")
    print("Units Found: " + str(len(data_units)))

    # create a list
    not_a_json_object = []

    # Loop over each object and append to list
    for i, data_unit in enumerate(data_units):
        # Indexing is not really needed unless you use it in the JSON
        # you need to change the method call below
        # to match your data_unit
        not_a_json_object.append(
            new_dict_from_template(
                id="no idea",
                sellername="ABC Candy",
                other="Additional Data",
                req_datetime="12:00pm",
            )
        )

# note the [ and ] to make this a list of dicts
not_a_json_object = [new_dict_from_template()]
print(json.dumps(not_a_json_object, indent=4))
print("----------------------------------------")
not_a_json_object.append(
    new_dict_from_template(
        storeid="no idea",
        sellername="ABC Candy",
        other="Additional Data",
        req_datetime="12:00pm",
    )
)
print(json.dumps(not_a_json_object, indent=4))
print("----------------------------------------")
# just taking one element of the list is still a valid JSON
json_str = json.dumps(not_a_json_object[1], indent=4)
print(json_str)

with open("somejsonfile.json", 'w') as outfile:
    outfile.write(json.dumps(not_a_json_object, indent=4))


text:
Q: Win32 Device Events : Not receiving DBT_DEVTYP_VOLUME on DBT_DEVICEARRIVAL event What I'm basically trying to do is making a windows service that listens to storage device insertion such as (USB flash drive, external HDD/SSD)...
I'm follwing these 2 tutorials :
*

*https://www.codeproject.com/Articles/15612/Receiving-Device-Event-Notification-in-Windows-Ser

*https://learn.microsoft.com/en-us/windows/win32/devio/detecting-media-insertion-or-removal
I got the service part running correctly, I'm also receiving Device Notifications. But when I try to put a USB flash drive, I receive a notification but dbch_devicetype in PDEV_BROADCAST_HDRis always DBT_DEVTYP_DEVICEINTERFACE never DBT_DEVTYP_VOLUME. Also when I RegisterDeviceNotification with DBT_DEVTYP_VOLUME I don't receive anything. I have been searching for hours and I could't find why I'm not receiving the correct notificationsThe function responsible for registering the Service for device notifications :
void Myclassname::registerForDeviceNotifications() {
    DEV_BROADCAST_DEVICEINTERFACE NotificationFilter;
    ZeroMemory(&NotificationFilter, sizeof(NotificationFilter));
    NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
    NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
    NotificationFilter.dbcc_classguid = { 0x71a27cdd, 0x812a, 0x11d0, 0xbe, 0xc7, 0x08, 0x00, 0x2b, 0xe2, 0x09, 0x2f };

    m_hDevNotify = RegisterDeviceNotification(m_statusHandle,
        &NotificationFilter, DEVICE_NOTIFY_SERVICE_HANDLE |
        DEVICE_NOTIFY_ALL_INTERFACE_CLASSES);
}

The function responsible for handling the device notifications :
void AutobackupService::handleDeviceChangeNotif(DWORD dwEventType, LPVOID lpEventData) {
    switch (dwEventType) {
    case DBT_DEVICEREMOVECOMPLETE: {
        PDEV_BROADCAST_HDR eventData = (PDEV_BROADCAST_HDR)lpEventData;
        logToFile(std::to_string(eventData->dbch_devicetype));
        if (eventData->dbch_devicetype == DBT_DEVTYP_VOLUME)
        {
            PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)eventData;
            if (lpdbv->dbcv_flags & DBTF_MEDIA)
            {
                WriteEventLogEntry(L"USB device removed " + lpdbv->dbcv_unitmask, EVENTLOG_INFORMATION_TYPE);
            }
        }
    }
                                   break;
    case DBT_DEVICEARRIVAL: {
        PDEV_BROADCAST_HDR eventData = (PDEV_BROADCAST_HDR)lpEventData;
        logToFile(std::to_string(eventData->dbch_devicetype));
        if (eventData->dbch_devicetype == DBT_DEVTYP_VOLUME)
        {
            PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)eventData;
            if (lpdbv->dbcv_flags & DBTF_MEDIA)
            {
                WriteEventLogEntry(L"USB device removed " + lpdbv->dbcv_unitmask, EVENTLOG_INFORMATION_TYPE);
            }
        }
    }
    }
}

A: at first your wrong register for volume notification. code must be
        static DEV_BROADCAST_DEVICEINTERFACE NotificationFilter = {
            sizeof(DEV_BROADCAST_DEVICEINTERFACE),
            DBT_DEVTYP_DEVICEINTERFACE,
            0,
            GUID_DEVINTERFACE_VOLUME
        };

        m_hDevNotify = RegisterDeviceNotification(m_statusHandle,
             &NotificationFilter, DEVICE_NOTIFY_SERVICE_HANDLE);

note than need use GUID_DEVINTERFACE_VOLUME if you want volume arrival/removal notification but not GUID_DEVCLASS_VOLUME (you use it as { 0x71a27cdd, 0x812a, 0x11d0, 0xbe, 0xc7, 0x08, 0x00, 0x2b, 0xe2, 0x09, 0x2f };). with GUID_DEVCLASS_VOLUME you never got notifications, because this is not interface guid. you got notifications only because use set DEVICE_NOTIFY_ALL_INTERFACE_CLASSES flag - Notifies the recipient of device interface events for all device interface classes. (The dbcc_classguid member is ignored.)
then in handler - you must got dbcc_devicetype == DBT_DEVTYP_DEVICEINTERFACE type of notification (not DBT_DEVTYP_VOLUME) also will be dbcc_classguid == GUID_DEVINTERFACE_VOLUME if you register exactly for GUID_DEVINTERFACE_VOLUME only. so you can cast lpEventData to PDEV_BROADCAST_DEVICEINTERFACE and use dbcc_name member - this is win32 symbolic link to volume name (can be used in call CreateFileW)


text:
Q: Using Multiple Defined Variables In MYSQL Connect I wish to allow a user to login to their MySQL database. Their username and end of the SQL database is the same, however each Database name starts with;
linkycra_[username]
I'm attempting to use defined variables in connecting to the SQL.
It would work with a comma in an echo - however obviously, commas cannot be used in this format.
http://puu.sh/1IBJP.png

A: Use the concatenation operator.

A: Well, there is a lot of thing to fix in your code.
First, don't use an image to paste code, but directly in stackoverflow or if it's too long, in a pastebin-like website.
Then, you should not use mysql_* methods since they are deprecated (read the doc), but PDO instead.
Next, you should never use the value in the cookie directly like this. You must verify it, sanitize and filter it, to be sure the value returned is correct : I can modify this value and with some work, maybe hack your website. Not a good way.
Then, if it's lynkycra_[username], you can use the concatenation of strings (based on your code) :
$link = mysql_connect('server', 'linkycra_'.$_COOKIE['monlotronloggedin'], 'password');

See ?


text:
Q: Dexie.exists() method returns nothing (Dexie.js & IndexedDB) So I'm building a small app with offline support using dexie.js and IndexedDB for the first time. If a database already exists on the local machine, I want to open and use that existing database-->so I check to see if one already exists using Dexie.exists(). Borrowing the sample code from the Dexie.js wiki, I've added the following to my app (rather than logging to console, I'm testing with alerts)
Dexie.exists("myDatabase").then(function(exists) {
  if (exists)
    alert("Database exists");
  else
    alert("Database doesnt exist");
}).catch(function (error) {
    alert("Oops, an error occurred when trying to check database existence");
});

However, this code--which is taken directly from the sample--does not work for me. If the database does not exist, the code correctly returns the alert "Database doesn't exist". However, while testing, I previously created a database and then deleted it using db.delete(). Now, when I test for the existence of the database I deleted, nothing is returned. It should return "Database doesn't exist", or at least an error, but it doesn't. I've found that if I update the code to the following:
Dexie.exists("myDatabase").then(function(exists) {
  if (exists)
    alert("Database exists");
  else
    alert("Database doesnt exist");
}).catch(
    alert("Oops, an error occurred when trying to check database existence")
);

the alert "Oops, an error occurred when trying to check database existence" DOES pop up. Unfortunately, I have no idea what the error is and I have no idea why the catch() statement is only working when I remove the anonymous function.
Looking at the code for Dexie.exists(), it tests to see if it can open() the database in question. As far as I can tell, trying to open that database I deleted seems to fail in a similar manner to how Dexie.exists() is failing for me. It seems like maybe I messed up something while trying to delete the database previously, and now Dexie isn't working. Because of how well Dexie incorporates promises, I can't see any of the errors that I'm assuming are being generated.
I've spent about 8 hours trying to solve this now to no avail. If anyone has experience using Dexie.js and can point me in the right direction, I would VERY much appreciate it. Alternatively, if someone has experience with IndexedDB, perhaps I may be able to solve the problem by 'resetting' the local IndexedDB (if I did in fact screw something up while testing). I haven't been able to figure out a way to do this though (as far as I can tell, working with IndexedDB directly is painful).
SOOOO much thanks for any help with this!!

A: So your .catch(alert()) is returning a false negative... It will show an alert even if the promise resolves... From what you have said it would appear the promise is not resolving and is thus remaining in a pending state. Clearing the cache of the browser will help. Like This


text:
Q: Pygame with version of Python from EPD I can't figure out how to install Pygame on OS X 10.6 (Snow Leopard). I installed the version of Python provided by Enthought Python Distribution (EPD) - as required by the course instructor at MIT - and then installed the version of Pygame for Snow Leopard and Python 2.7. Unfortunately, when I try to do import pygame, I get an ImportError (No module named pygame). How do I fix this problem?

A: I also had a hard time in the beginning but found it to be easy after reading
this site

*

*Step1: cd /Library/Frameworks/Python.framework/Versions

*Step2: sudo ln -s 7.3 2.7 [The 7.3 is the epd version and the 2.7 is
the python version, obviously change it to the version of python and
epd that you have]

*Step3: Grab the installer from the pygame website. Download and
install.

Voila! pygame is working


text:
Q: Forcing Linux libraries to stay resident in physical RAM? We have a Linux app suite that consists of about 3G of shared libraries, with many different front ends that load various portions of the shared libraries.  We run on machines with 24G, and frequently load large portions of that 3G.  We are thinking about trying to force all 3G to stay resident in RAM all the time, so that every app starts as quickly as possible.
Can this be done?  Our first thought was putting the binaries in a ramdisk like /dev/shm, but it seems like then the kernel would be free to swap the contents out, which we don't want.  We could reduce the swappiness parameter to 0, but I don't think we want that either, because file caches are a good use of memory.  We just want to dictate that this particular chunk of stuff should be kept hot all the time.
There is the mlock system call, which sounds exactly like what we want, but I'm not sure how to integrate this with a ramdisk.
Maybe we don't want a ramdisk at all, but a daemon process that simply mmaps the full extent of every binary, passing MAP_SHARED, MAP_LOCKED, and MAP_POPULATE?  Will this cause future loads by other processes to immediately access the same physical memory?  Is it correct that ld loads shared libraries using mmap with MAP_SHARED?
Any pointers appreciated!  Also any observations about why this is or isn't a good idea.

A: You can force the linux kernel to keep the shared libraries in memory. I use for this vmtouch.
Look in this questions for more information:
https://serverfault.com/questions/43383/caching-preloading-files-on-linux-into-ram

A: You could look at prelink in combination with swappiness tuned down to zero. If you have 24G and your box starts to swap, you are toast anyway. Prelink will force you libraries to be relocated to the same specific memory area for each library everytime it is loaded. This makes it possible for the libraries to avoid any overlapping memory ranges (on a 64 bit system at least), so every library is loaded exactly once. Additionally a small amount of memory is saved (sums up to about 100 M on my system) and of course it is faster.
In my personal opinion it is generally a good idea to tune down swappiness to 0, even on machines with less ram. It is mainly there because Andrew Morton liked it and it aims more at a low memory desktop.

I'm gonna stick my fingers in my ears and sing "la la la" until people tell me "I set swappiness to zero and it didn't do what I wanted it to do"

Which of course never happens or only to stop the gruesome singing.
This won't disable file caches, it just avoids pages swapped out to make room for the file cache, which usually is a good idea, because swapping is much slower than reading a file from disk.


text: Q: spread of fock state distribution and infinite revival time of rabi oscillation in spontaneous emission In cavity QED for a 2-level atom, the revival time for oscillation b/w the states $\left|\ e\ 0\right\rangle$ and $\left|\ g\ 1\right\rangle$ (absorbing the same photon that is emitted) is said to be infinity because in general, Rabi oscillation revival time is proportional to the square root of the mean of the occupancies of Fock states. Why should the spread of the Fock states distribution go to large values or close to infinity in the spontaneous emission case, to make the revival time infinity ? Refer :- http://prl.aps.org/abstract/PRL/v94/i1/e010401 for a description of Rabi Oscillations Revival


text:
Q: Sql query group by question, creating monthly averages I am trying to compile a table which shows three columns:
product name, average monthly sales volume and average monthly sales price for said product.
I am using adventureworks 2019.
I have written the below query based upon some help I previously received.  I have summed the order quantity and unit price for each product and then in the outer query averaged them.
SELECT
Product_Name,
AVG(Sales_Volume) AS Avg_Sales_Volume,
AVG(Price) AS Avg_Price

FROM

(SELECT
PP.[Name] AS Product_Name,
SUM(SSOD.[OrderQty]) AS Sales_Volume,
SUM(SSOD.[UnitPrice]) AS Price,
FORMAT(SSOH.[OrderDate], 'MM-yyyy') AS Month_Year

FROM
[Sales].[SalesOrderHeader] AS SSOH
LEFT JOIN Sales.SalesOrderDetail AS SSOD
ON SSOH.SalesOrderID = SSOD.SalesOrderID
LEFT JOIN production.product AS PP
ON SSOD.ProductID = PP.ProductID

GROUP BY PP.[Name], SSOH.[OrderDate]) AS T

--WHERE Product_Name = 'Road-150 Red, 44' (doing this for reference)

GROUP BY T.Product_Name, Month-Year

If I group by  Month-Year I get  around 3600  rows, where as if I don't, I get 266. I am confused about this.   Basically, I am not sure what it is actually showing.
To some of you this may seem really basic, but it feels like I cannot get my head around it.
Could anyone take a bit of time to explain this to me?
Thanks

Product_Name    Avg_Sales_Volume    Avg_Price
LL Mountain Frame - Silver, 48  14  844.96
LL Touring Frame - Blue, 50 26  2100.546
Women's Mountain Shorts, L  13  161.494
Road-550-W Yellow, 44   3   1890.7332
HL Road Frame - Red, 48 18  6025.3137
Mountain-500 Silver, 42 8   1395.0116

(266 rows)
Query with group by Month-Year also:
Product_Name    Avg_Sales_Volume    Avg_Price
Road-150 Red, 44    1   6758.9544
HL Mountain Frame - Silver, 46  15  4465.6362
AWC Logo Cap    14  76.4672
Long-Sleeve Logo Jersey, L  2   102.611
Road-150 Red, 56    2   6817.546
Mountain-500 Silver, 52 13  2118.7125
LL Touring Frame - Yellow, 62   62  5001.30
ML Mountain Frame-W - Silver, 40    115 6546.3382

(3862 rows)

A: A few notes first, then an explanation of what you're seeing.
First, your outer query has GROUP BY Month-Year with a dash, but I believe this is intended to be the column Month_Year (with an underscore) from the subquery.
Next, I like your use of AS to explicitly define aliases on columns, as well as your use of square brackets [ and ] around object names rather than quoted identifiers.
Finally, start getting in the practice of using schema- and alias-identifiers throughout your code - especially when working with subqueries. They'll make it much more clear which objects should be returned, and will prevent "ambiguous column" errors.
Explanation:
The difference in row-counts returned for each of your two queries is due to how those queries instruct the grouping to occur.
GROUP BY T.Product_Name; returns 266 rows because it is aggregating all of the sales volume and pricing information for the given product across all time. Changing up your subquery a bit to read:
SELECT COUNT(DISTINCT pp.Name)
  FROM [Sales].[SalesOrderHeader] AS SSOH
  LEFT JOIN Sales.SalesOrderDetail AS SSOD
    ON SSOH.SalesOrderID = SSOD.SalesOrderID
  LEFT JOIN production.product AS PP
    ON SSOD.ProductID = PP.ProductID

Results in 266 rows being returned, indicating that there are 266 distinct product names included in that set.
When you add more grouping conditions (such as T.Month_Year), you are telling the engine to make "subgroups" in the aggregation structure.
GROUP BY T.Product_Name, T.Month_Year runs your aggregates for each of those distinct 266 product names as well as aggregating the data for each distinct T.Month_Year value that appears in each of your 266 product name groups.
Examining those row-counts a bit closer, the two-condition grouping returns 3,862 rows while the single-condition grouping returns 266 rows. Across those 3,862 rows there are 266 distinct product names represented an average of 14.52 times (3862 / 266 = 15.518...). If you assumed that every product had at least one sale per month, then you might conclude that we are looking at slightly more than one year's worth of sales data here. More likely, this is a set of several years of sales data with a lot of variation in sales volume and frequency between products.
ADDENDUM: Adding your GROUP BY columns to the SELECT illustrates the difference in result sets:
SELECT Product_Name,
       T.Month_Year,
       AVG(Sales_Volume) AS Avg_Sales_Volume,
       AVG(Price) AS Avg_Price
  FROM (SELECT PP.[Name] AS Product_Name,
               SUM(SSOD.[OrderQty]) AS Sales_Volume,
               SUM(SSOD.[UnitPrice]) AS Price,
               FORMAT(SSOH.[OrderDate], 'MM-yyyy') AS Month_Year
          FROM [Sales].[SalesOrderHeader] AS SSOH
          LEFT JOIN Sales.SalesOrderDetail AS SSOD
            ON SSOH.SalesOrderID = SSOD.SalesOrderID
          LEFT JOIN production.product AS PP
            ON SSOD.ProductID = PP.ProductID
         GROUP BY PP.[Name], SSOH.[OrderDate]) AS T
--WHERE Product_Name = 'Road-150 Red, 44' (doing this for reference)
 GROUP BY T.Product_Name,
          T.Month_Year
 ORDER BY Product_Name;

Examining the results shows that each product name also has records for any month in which that product sold:
+--------------------------+-----------+-------+-----------+
|        ProductName       | Month_Year|Avg_Vol| Avg_Price |
+--------------------------+-----------+-------+-----------+
|  All-Purpose Bike Stand  |  12-2013  |   1   | 193.0714  |
|  All-Purpose Bike Stand  |  06-2014  |   1   | 218.625   |
|  All-Purpose Bike Stand  |  05-2014  |   1   | 187.909   |
|  All-Purpose Bike Stand  |  10-2013  |   1   | 212.00    |
|  AWC Logo Cap            |  02-2014  |   6   | 57.7928   |
|  AWC Logo Cap            |  02-2012  |   48  | 93.357    |
|  AWC Logo Cap            |  08-2011  |   68  | 103.73    |
|  AWC Logo Cap            |  01-2013  |   124 | 129.4896  |
|  AWC Logo Cap            |  03-2014  |   21  | 71.1747   |
+--------------------------+-----------+-------+-----------+


text:
Q: Strimzi kafka accessing it privately with in GKE I have two clusters,
one cluster with my application Microservices and other with the strimzi kafka installed. Both are the private GKE clusters .
My challenge exactly is to how to connect to this kafka from my application. There are around 10 Microservices running each has to connect to the kafka.
I have an approach for now by making the Strimzi kafka as a Nodeport service and providing the Ip and nodeIp in the application code.
The problem with this approach is that if the GKE nodes get auto updated I will have to reconfigure the code.
Also one more critical condition is that , The Kafka should be only accessed by our application ., It shouldn't be available for the public Internet.

A: I had a similar situation and how I solved it.
Create an internal loadbalancer to be accessible from another AKS cluster. Also allowing access to specific subnet as well.
Strimzi supports externalizing the bootstrap service.
example:
...
spec:
  kafka:
    replicas: 3
    listeners:
      plain: {}
      tls: {}
      external:
        type: loadbalancer
        tls: false
    ...
    template:
      externalBootstrapService:
          metadata:
            annotations:
              service.beta.kubernetes.io/azure-load-balancer-internal: "true"
              service.beta.kubernetes.io/azure-load-balancer-internal-subnet: "apps-subnet"
      perPodService:
        metadata:
          annotations:
            service.beta.kubernetes.io/azure-load-balancer-internal: "true"
            service.beta.kubernetes.io/azure-load-balancer-internal-subnet: "apps-subnet"

for more details you can check internal load balancers section in this link:
https://strimzi.io/blog/2019/05/13/accessing-kafka-part-4/


text:
Q: Dropping a table based on data within it I've taken over a project where the previous developer used a SQLite database to store two tables per user. We have about 70k tables right now, which is now causing crashing/inconsistencies with the software.
This is a discord bot, but not all users use the bot. So some of them have a balance of 0.
The obvious choice is to refactor into one table (as it should be...) but in the mean time I'd like to do a temporary measure to hopefully stop the issues we're having:
Drop any table where the user has 0 balance.
I haven't been able to find any way to do this. I found I can select all tables and thei

*

*I can't DROP on a condition

*I tried doing: SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'myBalance_%' AND (SELECT myBalance FROM name WHERE myBalance = 0); to no avail (syntax error, can't access name)

I have sort of limited SQL knowledge and haven't had any luck googling.


text:
Q: How does the control flow in a recursive program work? I am not sure why this piece of code prints out "5678998765". I see how it gets the 56789 part but when the numbers start going down is where i get confused. So if someone could explain i would be grateful.
int out(int k) {

    if (k == 10) {
        return 1;
    }
    printf("%d", k);
    out(k +1);
    printf("%d", k);
}

int main()
{
    out(5);
    return 0;

A: It is printed from last printf; every function needs to be executed till the end.
int out(int k) {

    if (k == 10) {
        return 1;
    }
    printf(" + %d", k);
    out(k +1);
    printf(" - %d", k);
}

You should try this, when it will be clearer.

A: Within the function for each value of k that is not equal to 10 there are two calls of printf
printf("%d", k);
out(k +1);
printf("%d", k);

So if the function is called the first time when k is equal to 5 then you will have
5 ( a call of out( 6 ) ) 5

then in the recursive call you will heav
56 ( a call of out( 7 ) ) 65

and so on.
When k is equal to 10 then nothing is outputted.

A: When main evaluates out(5), out runs and does this:

*

*k is not 10, so continue.

*Print k, which is 5.

*Evaluate out(6).

*Print k, which is 5.

That evaluates out(6), so replace the step "Evaluate out(6)" with what out does for that:

*

*k is not 10, so continue.

*Print k, which is 5.

*

*k is not 10, so continue.

*Print k, which is 6.

*Evaluate out(7).

*Print k, which is 6.

*Print k, which is 5.

Now you can see the program is going to print 5, then 6, then evaluate out(7), then print 6, then print 5. This continues until we have:

*

*k is not 10, so continue.

*Print k, which is 5.

*

*k is not 10, so continue.

*Print k, which is 6.

*

*k is not 10, so continue.

*Print k, which is 7.

*

*k is not 10, so continue.

*Print k, which is 8.

*

*k is not 10, so continue.

*Print k, which is 9.

*

*k is 10, so return 1.

*Print k, which is 9.

*Print k, which is 8.

*Print k, which is 7.

*Print k, which is 6.

*Print k, which is 5.


text:
Q: Tensorflow Lite model inference has very low accuracy I want to create a model that predicts the age and the gender and to integrate it in an android app.
I am on Ubuntu 16 and use Python 3.6, Tensorflow 1.13.1 and Keras 2.2.4.
First I train different models with the IMDB data-set : Mobilenet V1 and V2 from keras, and a VGG I coded myself.
For the two mobilenets I used imagenet weights to initialize the model.
The accuracy is quite good with more than 90% for the gender.
When the training is over, I tried several ways to convert the models in tflite :

*

*three ways where I convert directly from the .h5 file :

converter = tf.lite.TFLiteConverter.from_keras_model_file(model_to_convert)
tflite_model = converter.convert()
open(model_converted, "wb").write(tflite_model)

converter = tf.contrib.lite.TFLiteConverter.from_keras_model_file(model_to_convert)
tflite_model = converter.convert()
open(model_converted, "wb").write(tflite_model)

converter = tf.contrib.lite.TocoConverter.from_keras_model_file(model_to_convert)
tflite_model = converter.convert()
open(model_converted, "wb").write(tflite_model)

*

*one where I first convert the model to a tf graph as explained in this example
I also tried to use this line of code before the conversion :
tf.keras.backend.set_learning_phase(0)

Finally I load the .tflite file in Android Studio :
private ByteBuffer convertBitmapToByteBuffer(Bitmap bitmap) {
        int SIZE_IMAGE = 96;
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4*1*SIZE_IMAGE*SIZE_IMAGE*3);
        byteBuffer.order(ByteOrder.nativeOrder());
        int[] pixels = new int[SIZE_IMAGE * SIZE_IMAGE];
        bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
        int pixel = 0;
        for(int i=0; i < SIZE_IMAGE; i++){
            for(int j=0; j<SIZE_IMAGE;j++){
                final int val = pixels[pixel++];
                byteBuffer.putFloat((float) (((val >> 16) & 0xFF)/255));
                byteBuffer.putFloat((float) (((val >> 8) & 0xFF)/255));
                byteBuffer.putFloat((float) ((val & 0xFF)/255));

            }
        }

public String recognizeImage(Bitmap bitmap) {
        ByteBuffer byteBuffer = convertBitmapToByteBuffer(bitmap);
        Map<Integer, Object> cnnOutputs = new HashMap<>();
        float[][] gender=new float[1][2];
        cnnOutputs.put(0,gender);
        float[][]age=new float[1][21];
        cnnOutputs.put(1,age);
        Object[] inputs = {byteBuffer};
        interpreter.runForMultipleInputsOutputs(inputs, cnnOutputs);
        String result = convertToResults(gender[0], age[0]);
        return result;
    }

During the final inference, the accuracy is very low regardless the model used. Either the interpreter predicts always exactly the same result, either the predicted age changes a little but the predicted gender is always "woman".
What should I do?
Thanks in advance!

A: Try use your keras model and the tflite model to process one input data and compare the inference result. Probably the outputs don't match. You can debug from there.


text:
Q: Replacing values in column based on conditions in pandas DataFrame I have the following data in a pandas DataFrame:
import pandas as pd

df = pd.read_csv('example_data_file.csv')
df.head()

ID  Year    status
223725  1991    No
223725  1992    No
223725  1993    No
223725  1994    No
223725  1995    No

I want to replace the values in the column status, which has the values Yes and No for an ID based on the following condition:
If an ID has at least one Yes in the column status then all observations (including No) in the column status specific to that ID is replaced with Yes. Otherwise, it remains unchanged.
For example in the DataFrame below, 844272365 has Yes in status in the last row, then all previous observations in status in those rows specific to 844272365 should be replaced with Yes.
ID          Year    status
844272365   1991    No
844272365   1992    No
844272365   1993    No
844272365   1994    No
844272365   1995    No
844272365   1996    No
844272365   1997    No
844272365   1998    No
844272365   1999    No
844272365   2000    No
844272365   2001    No
844272365   2002    No
844272365   2003    No
844272365   2004    No
844272365   2005    No
844272365   2006    No
844272365   2007    No
844272365   2008    No
844272365   2010    No
844272365   2011    No
844272365   2012    No
844272365   2013    Yes

How do I make these replacements for many IDs in a DataFrame in accordance with the above condition?

A: You can use transform:
df['new_status'] = (df
                    .groupby('ID')['status']
                    .transform(lambda x: 'Yes' if x.str.contains('Yes').any() else 'No'))

A: Check transform with max
'Yes'>'No' # this is the reason why max work
Out[433]: True
df['new_status'] = df.groupby('ID')['status'].transform('max')
df
Out[435]:
           ID  Year status new_status
0   844272365  1991     No        Yes
1   844272365  1992     No        Yes
2   844272365  1993     No        Yes
3   844272365  1994     No        Yes
4   844272365  1995     No        Yes
5   844272365  1996     No        Yes
6   844272365  1997     No        Yes
7   844272365  1998     No        Yes
8   844272365  1999     No        Yes
9   844272365  2000     No        Yes
10  844272365  2001     No        Yes
11  844272365  2002     No        Yes
12  844272365  2003     No        Yes
13  844272365  2004     No        Yes
14  844272365  2005     No        Yes
15  844272365  2006     No        Yes
16  844272365  2007     No        Yes
17  844272365  2008     No        Yes
18  844272365  2010     No        Yes
19  844272365  2011     No        Yes
20  844272365  2012     No        Yes
21  844272365  2013    Yes        Yes

A: The following should work:
s=set(df[df.status=='Yes']['ID'])
for i in range(len(df)):
    if df.ID.iloc[i] in s:
        df.status[i]='Yes'


text:
Q: Edittext place cursor at the end of a Hint Is it possible to place somehow cursor at the end of a hint (not end of a text)?
Method setSelection() is not working (throws IndexOutOfBounds exception, as length of text is 0).

A: You can't put the cursor based on the hint.  However, what you can do is append the text you want to the EditText and then the cursor will be after that.  You can then add a TextWatcher to prevent the user from deleting the appended (hint) text.  Here's some code:
public class MainActivity extends AppCompatActivity {
private String HINT = "Name: ";
private EditText editText;

private TextWatcher textWatcher = new TextWatcher()
{
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after)
    {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count)
    {
        if (!s.toString().startsWith(HINT))
        {
            editText.removeTextChangedListener(this);
            editText.setText("");
            editText.append(HINT);
            editText.addTextChangedListener(this);
        }
    }

    @Override
    public void afterTextChanged(Editable s)
    {

    }
};

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

    editText = findViewById(R.id.edit_text);
    editText.append(HINT);
    editText.addTextChangedListener(textWatcher);
}

}

A: There is a trick.First you get hint string and hint color then you set EditText's text (value equals hint string) and do not forget set textcolor (values hint color).When user clicks the EditText, you can change the color back while reset empty text.
    final EditText editText = (EditText) findViewById(R.id.your_id);
    String hint = editText.getHint().toString();
    ColorStateList hintTextColor = editText.getHintTextColors();
    final ColorStateList textColor = editText.getTextColors();
    editText.setTextColor(hintTextColor);
    editText.setText(hint);
    editText.setSelection(hint.length());

    editText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            editText.setTextColor(textColor);
            editText.setText("");
        }
    });

A: No, unless you put your hint as regular EditText content as hint is not one.  But that defeats the purpose of the hint feature...


text:
Q: How to Unit test the following method? public User AddTags(int userId, List<Tag> Tags)
            {
                var user = GetUserById(userId);
                Tags.ForEach( tag => user.Tags.Add(tag));
                return _repository.Update(user);
            }
public interface IRepository<T> where T:class
    {
        void Add(T item);
        void Remove(T item);
        T Update(T item);
    }

In the test class
protected IRepository<User> Repository;
protected UserService Service;
public Mock<IRepository<User>> MockUserRepository = new Mock<IRepository<User>>();
Repository = MockUserRepository.Object;
Service = new UserService(UnitOfWork, Repository);
//I don't quite understand how to mock the Update method.
var result = Service.AddUserTags(1,Tags);
Assert.AreEqual(result.UserTags.Count(),3);

I have a List<User> users and a List<Tag> tags.
I am using EF , NUnit ,MOQ and the generic repository pattern.
Edit :
In GetUserById
return _repository.GetAll().Where(_ => _.UserId == userId).SingleOrDefault();

I have mocked it doing the following

MockUserRepository.Setup(_ => _.GetAll()).Returns(Users.AsQueryable());

A: I depends on what happens in GetUserById(userId);.  In order to check the count of UserTags you must control the returned User by mocking the GetUserId.
Otherwise, the best you can do is to make sure that the Update method is called:
repository.Verify(x => x.Update(It.IsAny<User>()));

After edit:
Then, you would need to setup the User:
[TestFixture]
    public class TestPointer
    {
        private IRepository<User> Repository;
        private UserService Service;
        private Mock<IRepository<User>> MockUserRepository = new Mock<IRepository<User>>();

        [Test]
        public void GetItemsByUserName_UserName_ListOfItems()
        {
            //Arrange
            var unitOfWork = new UnitOfWork();
            Service = new UserService(unitOfWork,  MockUserRepository.Object);
            var Tags = new List<Tag>() { new Tag { Name = "TestTag1" }, new Tag { Name = "TestTag2" }, new Tag { Name = "TestTag3" } };
            var user = new User() {Id = 1};
            MockUserRepository.Setup(x => x.Find(1)).Returns(user);
            MockUserRepository.Setup(x => x.Update(user)).Returns(user);

            //Act
            var result = Service.AddTags(1, Tags);

            //Assert
            Assert.AreEqual(result.Tags.Count(),3);
        }
    }

    public class UserService
    {
        private IRepository<User> _repository;
        private UnitOfWork _unitOfWork;

        public UserService(UnitOfWork unitOfWork, IRepository<User> repository)
        {
            _unitOfWork = unitOfWork;
            _repository = repository;
        }

        public User AddTags(int userId, List<Tag> Tags)
        {
            var user = GetUserById(userId);
            Tags.ForEach(tag => user.Tags.Add(tag));
            return _repository.Update(user);
        }

        private User GetUserById(int userId)
        {
            return _repository.Find(userId);
        }
    }

    public class UnitOfWork
    {

    }

    public interface IRepository<T> where T:class
    {
        T Find(int id);
        void Add(T item);
        void Remove(T item);
        T Update(T item);
    }

    public class User
    {
        private List<Tag> tags = new List<Tag>();

        public int Id { get; set; }
        public List<Tag> Tags
        {
            get { return tags; }
            set { tags = value; }
        }
    }

    public class Tag
    {
        public string Name { get; set; }
    }

A: If you want to assert on what happens with the user, The GetuserById method should should be injected, so it can be replaced by a mock, that returns a mocked user. You can then verify, that the user.Tags.Add(tag) is called the right number of times.
After that, you can verify that _repository.Update(user) is called one time;
For veryfication syntax in Moq, check this link.


text:
Q: AOMDV in NS2.34 Segmentation Fault I use AOMDV NS2.34. I have generated a CBR file and a mobility scene file with pause time 0 (highly dynamic environment). When I run the wireless.tcl with AOMDV with the generated traffic and scene files, I always get segmentation fault.
If I try to run a static mobility scene file (pause time = simulation time), I get everything working normally.
Does anyone find problem in AOMDV provided with ns2.34? If yes, how can I solve it?

A: I found that I can use the aomdv.tcl file already provided in the tcl/ex folder of ns2. In this file, I can change the minPausTime and maxPauseTime based on my needs instead of using a pre-defined CBR file.


text:
Q: Cassandra time series data (right approach?) We have a table that will contain a huge amount of time series data. Probably we have to store several entries per millisecond in that table. To fulfill these requirements the table looks like
CREATE TABLE statistic (
    name        text,
    id          uuid,
    start       timestamp,
    other_data  ...,

PRIMARY KEY (name, start, id)
) WITH CLUSTERING ORDER BY (start DESC);

As you can see, the table consists of two clustering keys, start stores the time when the data arrives, id has the purpose to avoid that data is overwritten when it arrives at the same time.
Now this is ok, we can make range queries like
SELECT * FROM statistic WHERE name ='foo' AND start >= 1453730078182
     AND start <= 1453730078251;

But we also need the capability to have additional search parameters in the query like
SELECT * FROM statistic WHERE name = 'foo'
    AND start >= 1453730078182 AND start <= 1453730078251 AND other_data = 'bar';

This does not work of course because other_data is not part of the primary key. If we add it to the primary key, we get the following error

InvalidRequest: code=2200 [Invalid query] message="PRIMARY KEY column "other_data" cannot be restricted (preceding column "start" is restricted by a non-EQ relation)"

That is also OK, that is not the way Cassandra works (I think).
Our approach to solve the problem is to select the needed (time series) data with the above mentioned (first) range query and afterwards filter the data in our Java application. That means we go through the list and kick out all data we don't need in our Java application. One single entry has not much data, but it can happen that we talk about some millions of rows in worst case.
Now I have two questions:

*

*Is that the right approach to solve the problem?

*Is Cassandra capable to handle that amount of data?

A:
This does not work of course because other_data is not part of the primary key. If we add it to the primary key, we get the following error

This is a sweet spot for secondary index on column other_data. In your case this index will scale because you always provide the partition key (name) so Cassandra will not hit all nodes in the cluster.
With a secondary index on other_data, your second SELECT statement will be possible.
Now there is another issue with your data model, which is the partition size. Indeed, if you are inserting several entries per milliseconds per name, this will not scale because the partition for each name will grow very fast ...
If the insert is distributed on different partition keys (different name) then it's fine


text:
Q: NServicebus share nested container with WebAPI dependency scope Is it possible to share/use the nested container created by the WebAPI dependency resolver?
The structuremap.web (I'm using structuremap and NServiceBus.StructureMap and UseContainer<StructureMapBuilder>(x => x.ExistingContainer(container))) package provides IDependencyResolver, IDependencyScope implementations that are pretty self explanatory - the resolver is created with the root container and when a scope is requested, it returns a new scope that is created with a nested container from the root.
What I want to know is that in the context of a WebAPI endpoint, can I share that nested container with NSB. Looking here, the structure map builder does pretty much what the WebAPI resolver does - container.GetNestedContainer(). This means I get two nested containers for each (HTTP) request that uses the bus.
My use case is that I want to create a sort of headers bucket that I can put headers into from a DelegatingHandler and then pull them back out of in an OutgoingMessageMutator.

A: This question has also been posted on the google group here. I quickly summarize the discussions for people reading this question:

*

*NServiceBus only creates nested containers when receiving messages. By using IBus.Send or similar methods from within the ASP.NET Pipeline, NServiceBus uses the container it has been configured with initially (e.g. for resolving message mutators).

*OWIN HTTP pass through places messages from incoming requests directly on the queue. This also supports custom extension (e.g. adding headers).

*You can resolve dependencies from different (nested) containers with DI trickery e.g. by using delegates, but there is some complexity involved. While thread static may be used for DI trickery, be aware that this will be broken with version 6 of NServiceBus which introduces async APIs.

*IBus can be wrapped in a helper which can be resolved using the pipelines current container and appends the headers.

A: @Sabacc has summarized the options available as discussed in the NServiceBus google group. We decided that the IBus wrapper approach was best for our needs. Below is an example implementation of this for reference
First a delegating handler for adding to a header bucket, this example adds the authorization token. If the header is set, a HeaderBucket instance is resolved from the current dependency scope which is accessible via HttpRequestMessage.GetDependencyScope().
public class AuthorizationTokenCapturingHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        AuthenticationHeaderValue header = request.Headers.Authorization;
        if (header != null)
        {
            HeaderBucket bucket = (HeaderBucket)request.GetDependencyScope().GetService(typeof(HeaderBucket));
            bucket.Add(new HeaderBucket.Header(HeaderConstants.AUTHORIZATION_TOKEN, header.Parameter));
        }

        return base.SendAsync(request, cancellationToken);
    }
}

The HeaderBucket is configured transient in container configuration so will be shared just for the lifetime of the nested container.
The IBus wrapper is simple - just wraps the bus intercepting calls to Send and sets the headers that have been added to the bucket on the message being sent.
public class HeaderAwareBus : IHeaderAwareBus
{
    private IBus _bus;
    private HeaderBucket _bucket;

    public HeaderAwareBus(IBus bus, HeaderBucket bucket)
    {
        _bus = bus;
        _bucket = bucket;
    }

    public ICallback Send(object message)
    {
        foreach (HeaderBucket.Header header in _bucket)
        {
            _bus.SetMessageHeader(message, header.Key, header.Value);
        }
        return _bus.Send(message);
    }
}

Now just declare your controller dependency as IHeaderAwareBus and the ASP.Net pipeline will resolve that, and thus the HeaderBucket, from the same nested container accessed from the DelegatingHandler


text:
Q: display GeoReferencing image through MapServer I have a tiff image and got the world file which contains the needed information for GeoReferenceing,
how to start add this image on Mapserver ? if I use C# and use GMAP API to call the google server through internet to show map.
how to add this map with correct coordinate on it ? if I have to replace this API to have a local map server to use, it is ok as long as I still can use the new mapserver and API with C# windows application.
any suggestion? I have many times add similar to this question but all people answer to use GDAL, but I think GDAL to get the needed information which is already having them in the world file ?

A: GDAL is the core lib of MapServer. The way of publish a georeferenced raster image is mapserver can be found here : http://mapserver.org/input/raster.html
Very straightforward, but you may still want to be careful about:
First, you may want to run gdalinfo to get the coordination system info for your image to make sure what is the coordinate system and find out the EPSG number to see if it is supported in the proj4 in your mapserver.
Second,remember to make sure in the mapfile the 'data' is using a relative path. Make sure your tiff is put into the correct path you assigned to.
Third to test the wms, you may need a valid bbox for the area in the same unit and coordinate system to put into the wms request url.


text:
Q: Installing apk programmatically Intent not opening I am trying to download and install an apk, this works just fine for Android versions less than 9, but 10 and 11 never reach the package installer and reloads whole the app.
Uri fileUri = Uri.fromFile(new File(PATH));
Intent intent;

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
              intent = new Intent(Intent.ACTION_INSTALL_PACKAGE, fileUri);
              intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);

              intent.setDataAndType(fileUri, "application/vnd.android.package-archive");
              intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

              intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);

              intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            } else {
              intent = new Intent(Intent.ACTION_VIEW);
              intent.setDataAndType(fileUri, "application/vnd.android.package-archive");
              intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }

  context.startActivity(intent);

And it throws this error:
E/AndroidRuntime: FATAL EXCEPTION: main

android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=file:///storage/emulated/0/Download/app-name.apk typ=application/vnd.android.package-archive flg=0x10008001 (has extras) }

This is the Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="br.com.appname" >

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />

    <application>
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>
    </application>

</manifest>


text:
Q: AOSP (Android 9) build regenerates every time I run make When I run make at the top of my Android build, I get a notice that build files need regenerated every time, regardless of whether or not I change any files.
$(shell development/vndk/tools/header-checker/utils/create_reference_dumps.py -products <my product> -l libtinyalsa) was changed, regenerating...
Where is the correct place to debug why this happening?  If I use make showcommands, I notice there are other create_reference_dumps.py invocations before this specific invocation that pass without causing a regeneration.  Only the last one with -l libtinyalsa fails each time.  My previous Android 8 build tree didn't have this issue.


text:
Q: Alfresco 5 : Set quota on specific repository folder or users I'm fairly new to Alfresco and just started trying to customize our installation to fit our needs.
One of our repositories can be accessed by somes users only. They are allowed to add files on a specific folder of this repository.
I would like to set a quota so that they won't be allowed to upload too large files.
I've found that it was possible to set a quota for a user but it only applies to "My Files".
How can I do this on a specific folder ? Or for the users, but applied to all directories in which the would add file ?
Thx in advance for your help.


text:
Q: Why does url disappear from python scrapy? Why does url disappear from python scrapy?
disappear_url = 'https://disqus.com/embed/comments/?base=default&f=zdnet-1&t_i=5d1b4eb7-9581-4eaa-acb9-5fbc6c15bdb7&t_u=https%3A%2F%2Fwww.zdnet.com%2Fproduct%2Fsamsung-chg9-series-c49hg90dmn-qled-monitor-curved-49%2F&t_e=Samsung%2049%20inch%20QLED%20business%20monitor%20review%3A%20Multi-tasking%20single%20monitor%20setup&t_d=Samsung%2049%20inch%20QLED%20business%20monitor%20review%3A%20Multi-tasking%20single%20monitor%20setup&t_t=Samsung%2049%20inch%20QLED%20business%20monitor%20review%3A%20Multi-tasking%20single%20monitor%20setup&s_o=default#version=48537a333e429dcb726ce9cdcc57a44f'

I tried this.
scrapy shell disppear_url

response.url
https://disqus.com/embed/comments/?base=default&f=zdnet-1&t_i=5d1b4eb7-9581-4eaa-acb9-5fbc6c15bdb7&t_u=https%3A%2F%2Fwww.zdnet.com%2Fproduct%2Fsamsung-chg9-series-c49hg90dmn-qled-monitor-curved-49%2F&t_e=Samsung%2049%20inch%20QLED%20business%20monitor%20review%3A%20Multi-tasking%20single%20monitor%20setup&t_d=Samsung%2049%20inch%20QLED%20business%20monitor%20review%3A%20Multi-tasking%20single%20monitor%20setup&t_t=Samsung%2049%20inch%20QLED%20business%20monitor%20review%3A%20Multi-tasking%20single%20monitor%20setup&s_o=default

response.request.url
https://disqus.com/embed/comments/?base=default&f=zdnet-1&t_i=5d1b4eb7-9581-4eaa-acb9-5fbc6c15bdb7&t_u=https%3A%2F%2Fwww.zdnet.com%2Fproduct%2Fsamsung-chg9-series-c49hg90dmn-qled-monitor-curved-49%2F&t_e=Samsung%2049%20inch%20QLED%20business%20monitor%20review%3A%20Multi-tasking%20single%20monitor%20setup&t_d=Samsung%2049%20inch%20QLED%20business%20monitor%20review%3A%20Multi-tasking%20single%20monitor%20setup&t_t=Samsung%2049%20inch%20QLED%20business%20monitor%20review%3A%20Multi-tasking%20single%20monitor%20setup&s_o=default#version=48537a333e429dcb726ce9cdcc57a44f

help me.


text:
Q: pandas equivalent of np.where np.where has the semantics of a vectorized if/else (similar to Apache Spark's when/otherwise DataFrame method). I know that I can use np.where on pandas.Series, but pandas often defines its own API to use instead of raw numpy functions, which is usually more convenient with pd.Series/pd.DataFrame.
Sure enough, I found pandas.DataFrame.where. However, at first glance, it has completely different semantics. I could not find a way to rewrite the most basic example of np.where using pandas where:
# df is pd.DataFrame
# how to write this using df.where?
df['C'] = np.where((df['A']<0) | (df['B']>0), df['A']+df['B'], df['A']/df['B'])

Am I missing something obvious? Or is pandas' where intended for a completely different use case, despite same name as np.where?

A: Try:
(df['A'] + df['B']).where((df['A'] < 0) | (df['B'] > 0), df['A'] / df['B'])

The difference between the numpy where and DataFrame where is that the default values are supplied by the DataFrame that the where method is being called on (docs).
I.e.
np.where(m, A, B)

is roughly equivalent to
A.where(m, B)

If you wanted a similar call signature using pandas, you could take advantage of the way method calls work in Python:
pd.DataFrame.where(cond=(df['A'] < 0) | (df['B'] > 0), self=df['A'] + df['B'], other=df['A'] / df['B'])

or without kwargs (Note: that the positional order of arguments is different from the numpy where argument order):
pd.DataFrame.where(df['A'] + df['B'], (df['A'] < 0) | (df['B'] > 0), df['A'] / df['B'])

A: I prefer using pandas' mask over where since it is less counterintuitive (at least for me).
(df['A']/df['B']).mask(df['A']<0) | (df['B']>0), df['A']+df['B'])

Here, column A and B are added where the condition holds, otherwise their ratio stays untouched.


text:
Q: How to change value of a control (label) within a UserControl added multiple times inside a panel I have a panel to which I add a certain number of the same user control according to the selected item of a combo. I need to change the value of a label every time the user enters a value within a textbox. This is for each UC added to the panel:

Thank you in advance...


text:
Q: Collapsing of Kunneth formula for equivariant K-theory of homogeneous spaces. Minami in "K-groups of symmetric spaces" (equations 1.1, 1.2) states the following, originally due to Hodgkins:
Suppose that $G$ is a compact connected Lie group such that $\pi_1(G)$ is torison-free
and let $K_G^*$ denote the equivariant K-theory associated with $G$, in [8],[9] Hodgkin constructed a strongly convergent spectral sequence (assuming one of X or Y is a free $G$-space)
$$ E_2^{* \,*}= Tor_{R(G)}^{*\,*}(K_G^*(X),K_G^*(Y)) \implies K_G^*(X \times Y)$$
They go on to say that in the case $X = G$, $Y = G/H$ the spectral sequence becomes:
$$ E_2^{* \,0}= Tor_{R(G)}^{*\,0}(\mathbb{Z},R(H)) \implies K^*(G/H)$$
They then state a theorem (whose proof takes up a chunk of the paper) saying that the latter s.s. collapses when $H$ is a closed subgroup. I do not understand what he means by collapses, despite briefly reading through the proof and going to the referenced theorem of Snaith in his "Masssey products in K-theory". My thoughts:
Firstly, I believe the s.s. is $(\mathbb{Z}, \mathbb{Z}_2)$-graded, so differentials on odd pages map horizontally i.e $d^{2k+1}: E^{p,\,q} \rightarrow E^{p+2k+1,\,q}$, otherwise there is nothing to say about the latter s.s. This could be incorrect though.
$1$. The sequence collapses in the usual/modern definition of the word, i.e. the sequence lives in a single row or column. This is trivially true, unless they meant collapses into a single column (as well as a single row) but then this isn't true.
$2.$ All differentials from the $2^{nd}$ page onwards are zero, if this was the case I would expect the word degenerates to be used.
$3$. The sequence degenerates after a finite number of pages. Again I think this is trivial since any fixed $G$ has finite rank, since it's compact - so the pages can only have non-zero entries for so long, so eventually the differentials start mapping "into the void".
The only one which seems not trivial to me is option $2$, is this what was meant?

A: Yes, option 2 is what is meant. Equivalently, all classes on the $E_2$ page are permanent cycles: if you look at the proof of Lemma 2.2, you'll find this is what is really being proved. It is also compatible with the reference to Snaith, whose collapsing results also amount to showing that everything on the $E_2$ page is a permanent cycle.


text:
Q: Passing Argument to Grep to get specific output I am a newbie to Unix. Learning on my own.....I am writing a simple shell script to pull the Name of a dealer who was working a shift at the specified time where search takes place from multiple files within a directory.
Idea is I need to be able to pass Date of File e.g. 0310 or time in File e.g. 05 or time type from file AM or PM to pull specific dealer who was working at that time.
I am able to pull data using the following script
grep -i '05' 0310* | awk -F " " '{print $(01) , $(02) , $(05) , $(06)}' | grep -i am > Dealers_working_during_losses.txt

This gives me names of all dealers that are listed in file names 0310_Dealer_Analysis at 05 AM. Now I need to create a script so I can provide date, time & time type as an argument so a script can be used by anyone. Please advise how to proceed ? Since I am new bee , would appreciate simple solution so I can understand the logic rather than something complex....
Below is sample file data. I only need to pull data for Roulette dealer.
Hour AM/PM BlackJack_Dealer_FNAME LAST Roulette_Dealer_FNAME LAST Texas_Hold_EM_dealer_FNAME LAST

12:00:00 AM Izabela Parrish Marlene Mcpherson Madina Britton
01:00:00 AM Billy Jones Saima Mcdermott Summer-Louise Hammond
02:00:00 AM Summer-Louise Hammond Abigale Rich John-James Hayward
03:00:00 AM John-James Hayward Evalyn Howell Chyna Mercado

A: First let's clean up your existing script:
1) The -i arg to grep is for a lower case alphabetic comparison so it doesn't make sense to use it on numbers. So just get rid of the -i from grep -i '05' 0310*.
2) " " is the default FS value for awk so you don't need to specify that with -F " " - just get rid of that too.
3) The input field numbers don't need to be 2-digit, nor do they need to be wrapped in parentheses to delimit them so every $(01) etc. can just be $1 etc.
4) You never need grep when you're using awk so this:
grep '05' 0310* |
awk '{print $1, $2, $5, $6}' |
grep -i am > Dealers_working_during_losses.txt

can be written as just:
awk '/05/{$0=$1 OFS $2 OFS $5 OFS $6; if (tolower($0) ~ /am/) print}' 0310* > Dealers_working_during_losses.txt

Now let's fix existing bugs:
5) /05/ will find 05 anywhere in the record (as a minutes field for example) but you only want to find it at the start of the record as that's where the hour specification exists so change that to /^05/.
6) Similarly, just like grep -i am did, tolower($0) ~ /am/ will find am anywhere in the record (in a persons name for example) but you only want to find it when it's the 2nd field in the record so change that to tolower($2) == "am"
We now have this command:
awk '/^05/{$0=$1 OFS $2 OFS $5 OFS $6; if (tolower($2) == "am") print}' 0310* > Dealers_working_during_losses.txt

but since we're only testing $2 for am or pm, we don't need to build a whole new record ($0) first before testing then printing it and can instead do:
awk '/^05/{if (tolower($2) == "am") print $1, $2, $5, $6}' 0310* > Dealers_working_during_losses.txt

which we can write more idiomatically as:
awk '/^05/ && (tolower($2) == "am") {print $1, $2, $5, $6}' 0310* > Dealers_working_during_losses.txt

And now to how to create a shell script that accepts arguments for all of the values. That'd be:
#!/usr/bin/env bash

awk -v time="$2" -v ampm="$3" '($0 ~ ("^"time)) && (tolower($2) == tolower(ampm)) {print $1, $2, $5, $6}' "$1"* > Dealers_working_during_losses.txt

which, assuming the above is stored in an executable file named foo that's in your PATH, you'd call as:
foo 0310 05 am

The only thing that I think is non-obvious above is that we had to use a different syntax for the time comparison when we went from testing a literal value (^05) to a string produced by concatenating the string "^" with the value of the variable time because use of a string in a regexp context requires us to use a dynamic regexp which also means that the shortcut /.../ for $0 ~ /.../ that works in constant regexp comparisons cannot be used so we need to write the $0 ~ part too.


text:
Q: R Shiny HTML Integration For an R Shiny App, I am trying to come with an Intro/Login page which has its UI based on an HTML template. I am able to achieve this as suggested in this link https://shiny.rstudio.com/articles/templates.html. Now, I want it such that when a user gets logged in using username & password through Intro Page then they get navigated to ShinyDashboard. Basically, the Intro/Login Page should have an HTML template theme and other parts of the app have a ShinyDashboard theme. Could you please suggest any tips or examples which will help me achieve the same?
EDIT :
Here the piece of code which I have written:
ui
shinyUI(bootstrapPage(

tagList(
tags$head(
  tags$link(rel="stylesheet", type="text/css",href="style.css")
  )
),
htmlTemplate("htmlpage.html",
uilogin = uiOutput("uiLogin"),
textpass = textOutput("pass")
),

obs = div(class = "span4", uiOutput("obs")),
distplot = div(class = "span8", plotOutput("distPlot"))

))

server
Logged = FALSE;

PASSWORD <- data.frame(Brukernavn = c("Windows","Ubuntu"), Passord =   c("25d55ad283aa400af464c76d713c07ad","81b073de9370ea873f548e31b8adc081"))

shinyServer(function(input, output) {
source("www/Login.R",  local = TRUE)

observe({
if (USER$Logged == TRUE) {
  output$obs <- renderUI({
    sliderInput("obs", "Number of observations:",
                min = 10000, max = 90000,
                value = 50000, step = 10000)
  })

  output$distPlot <- renderPlot({
    dist <- NULL
    dist <- rnorm(input$obs)
    hist(dist, breaks = 100, main = paste("Your password:", input$passwd))
  })
 }
 })
 })

Login Part
USER <- reactiveValues(Logged = FALSE)

passwdInput <- function(inputId, label) {
tagList(
tags$label(label),
tags$input(id = inputId, type="password", value="")
)
}

output$uiLogin <- renderUI({
if (USER$Logged == FALSE) {
wellPanel(
  textInput("userName", "User Name:"),
  passwdInput("passwd", "Pass word:"),
  br(),
  actionButton("Login", "Log in")
)
}
})

output$pass <- renderText({
if (USER$Logged == FALSE) {
if (!is.null(input$Login)) {
if (input$Login > 0) {
  Username <- isolate(input$userName)
  Password <- isolate(input$passwd)
  Id.username <- which(PASSWORD$Brukernavn == Username)
  Id.password <- which(PASSWORD$Passord    == Password)
  if (length(Id.username) > 0 & length(Id.password) > 0) {
    if (Id.username == Id.password) {
      USER$Logged <- TRUE
    }
  } else  {
    "User name or password failed!"
  }
  }
  }
  }
  })

  output$uiTest <- renderUI({
  dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(

  # TextImput for Username and Password
  textInput("username", label = h4("Username"), value = "Enter     Username..."),
  textInput("password", label = h4("Password"), value = "Enter  Password..."),

  # Log in Button
  actionButton("action", label = "Log in")

  )
 )
 })

Also, there is HTML file- htmlpage.html which is a Intro page. Now, Using the above code everything is working fine. Now, I need when the user login through the Into page (HTML page in shiny), the charts (obs,displot) gets opened in the shinydashboard User Interface.Currently, displot is getting displayed in HTML theme UI.
Is there a way where I can have my Intro (Login Page) in HTML theme and other parts of app in ShinyDashboard Theme.

A: It can be achieved using renderUI,renderMenu, uioutput functions. Here is the part of code to achieve the asked query.
ui
shinyUI(
 dashboardPage(
  dashboardHeader(),
   dashboardSidebar(sidebarMenu(id="sidebartabs",menuItemOutput("side"))),
     dashboardBody(

   uiOutput("page")

  )
)
)

server
observe({
if (USER$Logged == FALSE){

output$page <- renderUI({

  # Integration of Custom HTML Page with login page

shinyUI(bootstrapPage(

htmlTemplate("htmlpage.html",

     uilogin = loginpanel()
    )

  ))
})
}
if (USER$Logged == TRUE){

output$side <- renderMenu({
  inp$sidebarpanel
})

isolate({updateTabItems(session, "sidebartabs")})

output$page <- renderUI({
  inp$main
})
}})

htmlpage
Include {{ uilogin }} in body tag


text:
Q: Why does my templated function require a conversion from one iterator to the other? I am trying to implement a binary search tree container. At the moment I have to implement a find() function that is able to return an iterator or a constant iterator. I choose to overload the find function to accomodate both possibilities
MyIterator<treepair> find(const key& x)
{
    return tree_search<MyIterator<treepair>>(root,x);
}
const_MyIterator<treepair> find(const key& x) const
{
    return tree_search<const_MyIterator<treepair>>(root,x);
}

Then the function tree_search recursively finds the node that contains the wanted key by percurring the tree:
template<typename iterator>
iterator tree_search(Node<treepair>* x, const key& y) const
{
    if(x == nullptr)
    {
        std::cout<<"element not found"<<std::endl;
        iterator x = end();//HERE I HAVE A PROBLEM
        return x;
    }
    else if (y == x->value.first)
    {
        iterator i{x,tree_maximum()};
        std::cout<<"element found"<<std::endl;
        return i;
    }
    if(y < x->value.first)
        return tree_search<iterator>(x->left,y);
    else return tree_search<iterator>(x->right,y);
}

Now the end() function is overloaded to give both a const_iterator and a regular iterator:
MyIterator<treepair> end(){
return MyIterator<treepair>{nullptr,tree_maximum()};
}

const_MyIterator<treepair> end() const{
return const_MyIterator<treepair>{nullptr,tree_maximum()};
}

however I receive this error
test_on_iterators.cc:508:12: error: conversion from 'const_MyIterator<std::pair<int, int> >' to non-scalar type 'MyIterator<std::pair<int, int> >' requested
      iterator x = end();

Is this error due to a requirement in the conversion between the types? Isn't the compiler supposed to choose the wanted end() function according to the iterator type it has to produce?

A:
Isn't the compiler supposed to choose the wanted end() function according to the iterator type it has to produce?

No.
tree_search() is a const method.  That means its this pointer is pointing at a const object (even if the object tree_search() is called on is not really const).
As such, when tree_search() internally calls end(), it calls the overload that is callable on a const object.  That overload returns a const_MyIterator.  Then tree_search() tries to assign that const_MyIterator to a non-const MyIterator, which is where you get the error since there is no conversion defined from const_MyIterator to MyIterator.
You need to make x be a const_MyIterator to match what the const version of end() returns.
You should also make tree_search() return a const_MyIterator as well, instead of returning a non-const iterator.  If you want tree_search() to return a non-const Iterator, then don't declare it as a const method.


text:
Q: Transform for loop to map I have a script written in explicit for loop and I would like to transform it so I can use the map family of functions or the apply family. I would like to do so is to improve on time taken for the script to run. Any leads?
library(dplyr)
library(stringr)

mydata <- tibble(
  a_1 = c(20,22, 13,14,44),
  a_2 = c(42, 13, 32, 31, 14),
  b = c(1, 2, 1, 1, 2),
  c = c(1, 2, 1, 3, 1)
)

dictionary <- tibble(
  variable = c("a", "b", "c"),
  label = c("Age", "Gender", "Education"),
  type = c("mselect", "select", "select"),
  values = c(NA, "1, 2", "1, 2,3" ),
  valuelabel = c(NA, "Male, Female", "Primary, Secondary, Tertiary")

)

factor_vars <- dictionary %>%
  filter(type == "select") %>% pull(variable)

for (var in factor_vars){

  fct_levels <-  dictionary %>% filter(variable == var) %>%
    pull(values)
  fct_levels <- str_trim(unlist(strsplit(fct_levels, split = ",")))

  fct_labels <-  dictionary %>% filter(variable == var) %>%
    pull(valuelabel)
  fct_labels <- unlist(strsplit(fct_labels, split = ","))

  mydata[[var]] <- factor(mydata[[var]],
                          levels = fct_levels,
                          labels = fct_labels)

}

A: You could do something like this. Better provide a clean dictionary (i.e. spaces after commas) instead of using trimws, str_trim, or the like.
v <- c("b", "c")

u <- lapply(v, function(x) {
  d <- dictionary[dictionary$variable == x, c('values', 'valuelabel')] |>
    unlist() |>
    strsplit(', ') |>
    as.data.frame()
  factor(mydata[[x]], levels=d$values, labels=d$valuelabel)
  }) |>
  setNames(v) |>
  as.data.frame()

Result
res <- cbind(mydata[!names(mydata) %in% v], u)
#   a_1 a_2      b         c
# 1  20  42   Male   Primary
# 2  22  13 Female Secondary
# 3  13  32   Male   Primary
# 4  14  31   Male  Tertiary
# 5  44  14 Female   Primary

Where:
str(res)
# 'data.frame': 5 obs. of  4 variables:
# $ a_1: num  20 22 13 14 44
# $ a_2: num  42 13 32 31 14
# $ b  : Factor w/ 2 levels "Male","Female": 1 2 1 1 2
# $ c  : Factor w/ 3 levels "Primary","Secondary",..: 1 2 1 3 1

Note:
> R.version.string
[1] "R version 4.1.2 (2021-11-01)"


text:
Q: wrong description being selected for Pinterest rich-pins I just recently requested Pinterest Rich-Pins on my blogsite which it approved.
However, the description it is providing is crazy long: it is selecting the entire contents of the articles rather than an abbreviation snippet.

example >> http://pin.it/Ov1rvR4 <<

I have tried seeking answers direct with Pinterest CS but have received nothing but a default notice to check my original documentation - which I already did and cannot see where I am going wrong.
I would be extremely grateful for any insight you can offer to a solution on this. My only other course of action is to disable Rich-Pins which I am loathe to do for the affect it will have on my appearance in the Smart Feed algorithm.
Thanks everyone!


text:
Q: How can i center a long string above every button? I would like to keep my text above every circle centered! It takes only 40px width and go to the right and this is not wonderful. I am really confused on how to center the text above the circle.
Thank you in advance! :)

$('.dot:nth-child(1)').click(function() {
  $('.inside', $(this).parent()).animate({
    'width': '10%'
  }, 500);
});
$('.dot:nth-child(2)').click(function() {
  $('.inside', $(this).parent()).animate({
    'width': '20%'
  }, 500);
});
$('.dot:nth-child(3)').click(function() {
  $('.inside', $(this).parent()).animate({
    'width': '30%'
  }, 500);
});
$('.dot:nth-child(4)').click(function() {
  $('.inside', $(this).parent()).animate({
    'width': '40%'
  }, 500);
});
$('.dot:nth-child(5)').click(function() {
  $('.inside', $(this).parent()).animate({
    'width': '50%'
  }, 500);
});
$('.dot:nth-child(6)').click(function() {
  $('.inside', $(this).parent()).animate({
    'width': '60%'
  }, 500);
});
$('.dot:nth-child(7)').click(function() {
  $('.inside', $(this).parent()).animate({
    'width': '70%'
  }, 500);
});
$('.dot:nth-child(8)').click(function() {
  $('.inside', $(this).parent()).animate({
    'width': '80%'
  }, 500);
});
$('.dot:nth-child(9)').click(function() {
  $('.inside', $(this).parent()).animate({
    'width': '90%'
  }, 500);
});
div#timeline {
  background-color: #6ab0de;
  margin-top: 150px;
  height: 10px;
  width: 100%;
  position: relative;
}
div#timeline .inside {
  position: absolute;
  height: 4px;
  background-color: #fff;
  width: 0%;
  top: 3px;
  left: 0;
}
div#timeline .dot {
  z-index: 99;
  -webkit-transition: 0.3s ease-in-out;
  transition: 0.3s ease-in-out;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  position: absolute;
  top: -15px;
  text-align: center;
  cursor: pointer;
}
div#timeline .dot:nth-child(1) {
  left: 10%;
}
div#timeline .dot:nth-child(2) {
  left: 20%;
  background-color: #e74c3c;
}
div#timeline .dot:nth-child(3) {
  left: 30%;
  background-color: #7b3;
}
div#timeline .dot:nth-child(4) {
  left: 40%;
  background-color: #20638f;
}
div#timeline .dot:nth-child(5) {
  left: 50%;
  background-color: #7cdbd5;
}
div#timeline .dot:nth-child(6) {
  left: 60%;
  background-color: #f39c12;
}
div#timeline .dot:nth-child(7) {
  left: 70%;
  background-color: #2c3e50;
}
div#timeline .dot:nth-child(8) {
  left: 80%;
  background-color: #e74c3c;
}
div#timeline .dot:nth-child(9) {
  left: 90%;
  background-color: #7b3;
}
div#timeline .dot:hover {
  -webkit-transform: scale(1.2);
  transform: scale(1.2);
}
div#timeline .dot date {
  font-family: roboto;
  font-size: 1.1rem;
  display: block;
  position: relative;
  top: -60px;
  text-align: center;
}
div#timeline .dot span {
  display: inline-block;
  margin-top: 10px;
  width: 20px;
  height: 20px;
  background-color: #fff;
  position: relative;
  border-radius: 50%;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<link rel='stylesheet prefetch' href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css'>

    <date>Page 1</date>

    <date>Page 2</date>

    <date>Large TEXT HERE</date>

    <date>P4</date>

    <date>P5</date>

    <date>P5</date>

    <date>P5</date>

    <date>P5</date>

    <date>P5</date>

A: You could remove the non-breaking spaces and use a class to bump up multi-line items......

$('.dot:nth-child(1)').click(function() {
  $('.inside', $(this).parent()).animate({
    'width': '10%'
  }, 500);
});
$('.dot:nth-child(2)').click(function() {
  $('.inside', $(this).parent()).animate({
    'width': '20%'
  }, 500);
});
$('.dot:nth-child(3)').click(function() {
  $('.inside', $(this).parent()).animate({
    'width': '30%'
  }, 500);
});
$('.dot:nth-child(4)').click(function() {
  $('.inside', $(this).parent()).animate({
    'width': '40%'
  }, 500);
});
$('.dot:nth-child(5)').click(function() {
  $('.inside', $(this).parent()).animate({
    'width': '50%'
  }, 500);
});
$('.dot:nth-child(6)').click(function() {
  $('.inside', $(this).parent()).animate({
    'width': '60%'
  }, 500);
});
$('.dot:nth-child(7)').click(function() {
  $('.inside', $(this).parent()).animate({
    'width': '70%'
  }, 500);
});
$('.dot:nth-child(8)').click(function() {
  $('.inside', $(this).parent()).animate({
    'width': '80%'
  }, 500);
});
$('.dot:nth-child(9)').click(function() {
  $('.inside', $(this).parent()).animate({
    'width': '90%'
  }, 500);
});
div#timeline {
  background-color: #6ab0de;
  margin-top: 150px;
  height: 10px;
  width: 100%;
  position: relative;
}
div#timeline .inside {
  position: absolute;
  height: 4px;
  background-color: #fff;
  width: 0%;
  top: 3px;
  left: 0;
}
div#timeline .dot {
  z-index: 99;
  -webkit-transition: 0.3s ease-in-out;
  transition: 0.3s ease-in-out;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  position: absolute;
  top: -15px;
  text-align: center;
  cursor: pointer;
}
div#timeline .dot:nth-child(1) {
  left: 10%;
}
div#timeline .dot:nth-child(2) {
  left: 20%;
  background-color: #e74c3c;
}
div#timeline .dot:nth-child(3) {
  left: 30%;
  background-color: #7b3;
}
div#timeline .dot:nth-child(4) {
  left: 40%;
  background-color: #20638f;
}
div#timeline .dot:nth-child(5) {
  left: 50%;
  background-color: #7cdbd5;
}
div#timeline .dot:nth-child(6) {
  left: 60%;
  background-color: #f39c12;
}
div#timeline .dot:nth-child(7) {
  left: 70%;
  background-color: #2c3e50;
}
div#timeline .dot:nth-child(8) {
  left: 80%;
  background-color: #e74c3c;
}
div#timeline .dot:nth-child(9) {
  left: 90%;
  background-color: #7b3;
}
div#timeline .dot:hover {
  -webkit-transform: scale(1.2);
  transform: scale(1.2);
}
div#timeline .dot date {
  font-family: roboto;
  font-size: 1.1rem;
  display: block;
  position: relative;
  top: -60px;
  text-align: center;
}

/* ---------------------------- */
div#timeline .dot date.bump {
  top: -85px; }

/* ------------------ */

div#timeline .dot span {
  display: inline-block;
  margin-top: 10px;
  width: 20px;
  height: 20px;
  background-color: #fff;
  position: relative;
  border-radius: 50%;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<link rel='stylesheet prefetch' href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css'>

    <date>Page 1</date>

    <date>Page 2</date>

    <date class="bump">Large TEXT HERE</date>

    <date>P4</date>

    <date>P5</date>

    <date>P5</date>

    <date>P5</date>

    <date>P5</date>

    <date>P5</date>

Of course, you may also need to word-break or hyphenate long words.

A: The proper way is using CSS transforms. This allows for a fluid layout.
Codepen: http://codepen.io/ovitrif/pen/eBPEVV
What I did is simple, I modified the CSS rule for div#timeline .dot date as follows:
div#timeline .dot date {
  /*
  font-family: roboto;
  font-size: 1.1rem;
  display: block;
  top: -60px;
  text-align: center;
  */
  position: absolute;
  left: 20px; /* This has to be equal with the half of the dot width.*/
  transform: translatex(-50%);
}

A: Finally the solution of Ovi-Trif works fine.
Thank all of members who contributed for this nice help really thanks to stackoverflow too :)


text:
Q: How can I convert a null-terminated string in a byte buffer to a string in Go? This:
label := string([]byte{97, 98, 99, 0, 0, 0, 0})
fmt.Printf("%s\n", label)

does this (^@ is the null-byte):
go run test.go
abc^@^@^@

A: There's this function hidden inside Go's syscall package that finds the first null byte ([]byte{0}) and returns the length. I'm assuming it's called clen for C-Length.
Sorry I'm a year late on this answer, but I think it's a lot simpler than the other two (no unnecessary imports, etc.)
func clen(n []byte) int {
    for i := 0; i < len(n); i++ {
        if n[i] == 0 {
            return i
        }
    }
    return len(n)
}

So,
label := []byte{97, 98, 99, 0, 0, 0, 0}
s := label[:clen(label)]
fmt.Println(string(s))

What that ^ says is to set s to the slice of bytes in label from the beginning to the index of clen(label).
The result would be abc with a length of 3.

A: Note that the first answer will only work with strings that have only a run of zeroes after the null terminator; however, a proper C-style null-terminated string ends at the first \0 even if it's followed by garbage. For example, []byte{97,98,99,0,99,99,0} should be parsed as abc, not abc^@cc.
To properly parse this, use string.Index, as follows, to find the first \0 and use it to slice the original byte-slice:
package main

import (
    "fmt"
    "strings"
)

func main() {
    label := []byte{97,98,99,0,99,99,0}
    nullIndex := strings.Index(string(label), "\x00")
    if (nullIndex < 0) {
        fmt.Println("Buffer did not hold a null-terminated string")
        os.Exit(1)
    }
    fmt.Println(string(label[:nullIndex]))
}

EDIT: Was printing the shortened version as a []byte instead of as a string. Thanks to @serbaut for the catch.
EDIT 2: Was not handling the error case of a buffer without a null terminator. Thanks to @snap for the catch.

A: You can use the sys package:
package main
import "golang.org/x/sys/windows"

func main() {
   b := []byte{97, 98, 99, 0, 0, 0, 0}
   s := windows.ByteSliceToString(b)
   println(s == "abc")
}

Or you can just implement it yourself:
package main
import "bytes"

func byteSliceToString(s []byte) string {
   n := bytes.IndexByte(s, 0)
   if n >= 0 {
      s = s[:n]
   }
   return string(s)
}

func main() {
   b := []byte{97, 98, 99, 0, 0, 0, 0}
   s := byteSliceToString(b)
   println(s == "abc")
}

*

*https://pkg.go.dev/golang.org/x/sys/unix#ByteSliceToString

*https://pkg.go.dev/golang.org/x/sys/windows#ByteSliceToString

A: 1. strings .TrimSpace .TrimRight
//trim tail '\0', but can't handle bytes like "abc\x00def\x00".
can't edit @orelli answer, so wrote here:
package main

import (
    "fmt"
    "strings"
)

func main() {
    label := string([]byte{97, 98, 99, 0, 0, 0, 0})

    s1 := strings.TrimSpace(label)
    fmt.Println(len(s1), s1)

    s2 := strings.TrimRight(label, "\x00")
    fmt.Println(len(s2), s2)
  }

output:
7 abc????
3 abc

// ? is '\0' which can't display here.

So
.TrimSpace can't trim '\0', but
.TrimRight with "\x00" can.

2. bytes.IndexByte
search for first '\0', maybe not support utf-8
package main

import (
    "bytes"
    "fmt"
    "strings"
)

func main() {
    b_arr := []byte{97, 98, 99, 0, 100, 0, 0}
    label := string(b_arr)

    s1 := strings.TrimSpace(label)
    fmt.Println(len(s1), s1)   //7 abc?d??

    s2 := strings.TrimRight(label, "\x00")
    fmt.Println(len(s2), s2)   //5 abc?d

    n := bytes.IndexByte([]byte(label), 0)
    fmt.Println(n, label[:n])  //3 abc

    s_arr := b_arr[:bytes.IndexByte(b_arr, 0)]
    fmt.Println(len(s_arr), string(s_arr)) //3 abc
}

equivalent
n1 := bytes.IndexByte(b_arr, 0)
n2 := bytes.Index(b_arr, []byte{0})

n3, c := 0, byte(0)
for n3, c = range b_arr {
    if c == 0 {
        break
    }
}

A: You can use bytes.SplitN and have it return the first subslice:
import (
    "bytes"
)

func bytesToStr(in []byte) string {
    str := bytes.SplitN(in, []byte{0}, 2)[0]
    return string(str)
}

In go 1.18+, you can also use bytes.Cut:
func bytesToStr(in []byte) string {
    str, _, _ := bytes.Cut(in, []byte{0})
    return string(str)
}


text:
Q: How to execute command in Android Studio? when I build my project on Android Studio. In Build log, it shows

AGPBI: {"kind":"warning","text":"API 'BaseVariant.getApplicationIdTextResource' is obsolete and has been replaced with 'VariantProperties.applicationId'.\nIt will be removed in version 7.0 of the Android Gradle plugin.\nFor more information, see TBD.\nTo determine what is calling BaseVariant.getApplicationIdTextResource, use -Pandroid.debug.obsoleteApi=true on the command line to display more information.","sources":[{}]}

Thus, my question is. how can I execute command -Pandroid.debug.obsoleteApi=true in Android Studio? so that i can see further info. Thank you in advance!.


text:
Q: Gradle stock on build ***** gradle project info enter image description here
I have buy new macbook and I download android studio when I start new project its stock in build ..... Gradle project info
android studio last version 2.3
I try gradle work offline in setting and the same
OS X 10.9.5
java 1.8 (121)
android studio only show Building My Application Gradle project info
Thank you

A: According to this you may just be experiencing a slow network connection. WHen a project is created for the first time there is a lot to be downloaded, and it can take a while on slow connections.
ACcording to this you may be using the wrong version of android studio. If you navigate to the folder where you have Android Studio's files, look for "studio.exe" and "studio64.exe". First though, close the current open Android Studio window. Start by selecting "studio64" and opening it. Create a new project and see if it gets stuck. If it gets stuck,  try with "studio.exe" and create the project again. If it gets stuck agian, try a different solution.
And according to this you could try pressing "cancel" and finding your build.gradle on project-level. IN there you will find something like this:
buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.3.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

Replace 2.3.0 with an earlier version, e.g. 2.0.0. Then press (in the menu bar at the top) build>make project. Gradle will start to build should in theory finish.

If none of these work, leave a comment so I know and can look for other alternatives to these