Xcode - Include a UIView above UITableView

Question: I have a TableViewController, that manages a UITableView. Now I want to make a header menu (different for the one in navigation bar by default) and a search bar (also different from the default one). The problem is that I try to drop a UIView above the TablewView, but I can't, it always goes inside the tableview (in the storyboard).
Is it possible to do what I'm trying to do?
Thanks a lot!
Answer: You will need to use something else than UITableViewController.
Subclass UIViewController and add a tableview into it, but with a y position that is >0. Now, set your UIViewController subclass as the delegate and dataSource of that UITableView and implement all the necessary methods.  ( references here and here )
You will be able to change the layout of that tableView and add whatever view you want to add to the self.view
Comment: Thanks a lot Olotiar! I will have a lot of work until the end of the day reconstructing my controllers :).
Comment: You're welcome. If you are doing that more than once, consider creating a generic `UIViewController` and re-use it several times.
Comment: Hummm Is it possible to do something like. A generic UIView design on storyboard, and save it like a object to reuse? Like a view that is repeated on a list, like a photoview for thumbnails?

Another thing, should I use a costum navigationViewController to costumize my navigationBar, or should I do it inside the genericViewController? (I want that navigation bar to be in everyView, so it's like a template)
Comment: If you want to customize your NavigationBar, and if you target iOS 5 and more, use `UIAppearance`, like `[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"navBar"] forBarMetrics:UIBarMetricsDefault];` (put that code in the `- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{` of your `AppDelegate`. If you want more info on how to further customize (and how to do it for iOS 4-) I recommmend Googling or asking a separate question. And you sound like learning about categories might be a good idea
Comment: Yeah, I've read about categories. Like I'm coming on the first months in IOS dev, and I came from Front End, it's being a little hard to interiorize some concepts. But you gave me some good insights to study more. Tks a lot for your time!


Pushing an application revision using the SDK

Question: To push a revision using CLI, there is a command like :
aws deploy push --application-name WordPress_App --description
"This is my deployment" --ignore-hidden-files --s3-location
s3://CodeDeployDemoBucket/WordPressApp.zip --source
/tmp/MyLocalDeploymentFolder/

How could I do this using the SDK? I couldn't find a method, that will help me push the application to S3 storage, although there is a method to create a deployment (createDeployment)
Answer: The push command in the CLI is a CodeDeploy plugin for AWS CLI, you can find the source code here: https://github.com/aws/aws-cli/blob/develop/awscli/customizations/codedeploy/push.py
It's actually calling several different APIs to create the revision bundle, upload it and create a deployment. With SDK, you can achieve the same thing by creating your own wrapper which will call APIs following the same order.


In a Java 7+ ForkJoinPool, is it possible to cancel a task and all subtasks?

Question: My program searches for a solution (any solution) to a problem through a divide-and-conquer approach, implemented using recursion and RecursiveTasks's: I fork a task for the first branch of the division, then recurse into the second branch: if the second branch has found a solution, then I cancel the first branch, otherwise I wait for its result.
This is perhaps not optimal. One approach would be for any of the launched tasks to throw an exception if a solution is found. But then, how would I cancel all the launched tasks? Does cancelling a task also cancel all sub-tasks?
Comment: http://www.coopsoft.com/ar/CalamityArticle.html
Answer: You can use the simple approach with task manager. For example:
public class TaskManager<T> {

private List<ForkJoinTask<T>> tasks;

public TaskManager() {
    tasks = new ArrayList<>();
}

public void addTask(ForkJoinTask<T> task) {
    tasks.add(task);
}

public void cancelAllExcludeTask(ForkJoinTask<Integer> cancelTask) {
    for (ForkJoinTask<T> task : tasks) {
        if (task != cancelTask) {
            task.cancel(true);
        }
    }
}

public void cancelTask(ForkJoinTask<Integer> cancelTask) {
    for (ForkJoinTask<T> task : tasks) {
        if (task == cancelTask) {
            task.cancel(true);
        }
    }
}

}
And the task:
public class YourTask extends RecursiveTask<Integer> {

private TaskManager<Integer> taskManager;

@Override
protected Integer compute() {
        // stuff and fork
        newTask.fork();
        // do not forget to save in managers list
        taskManager.addTask(newTask);

        // another logic

        // if current task should be cancelled
        taskManager.cancelTasks(this);

        // or if you have decided to cancel all other tasks
        taskManager.cancelAllExcludeTask(this);
}
}

Comment: Are you sure that `RecursiveTask.cancel(true)` really stops the task? Because the `cancel()` implementation in `ForkJoinTask` (from which `RecursiveTask` inherits), simply sets a `cancelled` flag, but does not interrupt the thread. See also http://stackoverflow.com/questions/21320156/forkjoinpool-resets-thread-interrupted-state
Comment: cancel calls setCompletion(int completion) which may issue: synchronized (this) { notifyAll(); } That may have unintended consequences for other tasks and as noted above it does not interrupt the current thread. The only sure/safe way to cancel a task and all its sub-tasks (the original question) is to manually code the logic yourself.
Comment: The problem with cancelAllExcludeTask() is that when a task is holding a resource or has some other dependency there may be an internal problem. It comes down to the same problems as Thread.stop(). No framework can know what any task is doing so it is always dangerous to try to stop a task.
Comment: If you should care about allocated resources with task, it is still possible to extend FutureTask directly and override it's cancel() method. And then sumbit such task to executor.
Answer: The framework cannot cancel a task for the same reason you cannot cancel a thread. See the documentation on Thread.stop() for all the reasons. What locks could the task be holding? What outside resources could it have linkage to? All the same Thread.stop() reasons apply to tasks as well (after all, tasks run under threads.) You need to tell the task to stop just like you tell a thread to stop.
I manage another fork/join project that uses the scatter-gather technique. The way I do a cancel, or short-circuit, is that every task I create is passed an object (PassObject) that has a
protected volatile boolean stop_now = false;

and a method for stopping the task
protected void stopNow() {stop_now = true; }

Each task periodically checks the stop_now and when true it gracefully ends the task.
Unfortunately, the stop_now needs to be volatile since another thread is going to set it. This can add significant overhead if you check it frequently.
How to set this field in another task gets a little tricky. Each task I create also contains a reference to the array of references to every other task
int nbr_tasks = nbr_elements / threshold;
// this holds the common class passed to each task
PassObject[] passList = new PassObject[nbr_tasks];
 for (int i = 0; i < nbr_tasks; i++)
passList[i] = new PassObject( passList,… other parms);

Once the list is formed I fork() each object in passList. Each PassObject contains a reference to the array, passList, which contains a reference to every object that is passed to each task. Therefore, every task knows about every other task and when one task want to cancel the others it simply calls the cancelOthers method with a reference to the passList.
private void cancelOthers (PassObject[] others) {
// tell all tasks to stop
 for (int i = 0, max = others.length; i < max; i++)
others[i].stopNow();

If you're using Java8 then you can do a form of scatter-gather with the CountedCompler class instead of the RecusiveTask. For Java7 or if you still want to use RecursiveTask, then the first task in the recursion needs to create an AtomicBoolean field (AtomicBoolean stop_now = new AtomicBoolean(false);) and include a reference to this field in every new RecursiveTask it creates. With recursion, you don't know how many levels of tasks you'll need in the beginning.
Again, you'll need to check for a true in the boolean periodically in your code and when true, end the task gracefully.
The above is just a hint of how you can do a cancel. Every application is different. What I do works for my application – but the logic is the same. You need something common in every task that a task can set and every other task can see.
I'd add more code but the code insert only is taking one line at a time and it isn't practical.
Comment: How so? A race is irrelevant. As long as the only modification is to set false.
Comment: "Each task I create also contains a reference to the array of references to **every other task**." - Wouldn't it be sufficient when every task only knows its direct sub-tasks (e.g. the tasks that it created itself)?
Comment: I use a scatter-gather technique that creates all the tasks necessary in the beginning. This is not a recursive decomposition technique. If you use recursion to create sub-tasks, that create sub-tasks, then you should use the AtomicBoolean method and pass that reference to each sub-task. But, just cancelling one chain of sub-tasks isn't enough. You need to cancell ALL Tasks.
Comment: the convenience with InterruptedException was that if you call 3rd party methods they obey InterruptedException and stop_now could be supported by your code only
Comment: Third party methods do what they want. There is no guarantee that any third party method will obey any standard procedure. This thread is 16 months old, you're a bit late to the party.


How to read characters from the keyboard until a period is received, and count the number of spaces

Question: I'm very new to C# and OOP and stackoverflow. This is my first scenario (a few questions)
I want the user to enter characters, until a period (.) is received, and to count and report the number of whitespaces.
Can I achieve this?
(Not sure if you always hit to hit enter/return to send)
Can I do this without using strings?
(I haven't covered strings yet, this is a self-learning exercise, and I believe the solution should therefore be very simple, but I'm getting unusual results).
I tried the following, but the program closes before I can see the results, even though I added a Console.Read(); at the end, which usually works...
class CountSpaces
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter characters,finish with a period (\".\"");
            char ch;
            int spaces=0;
            do
            {
                ch = (char)Console.Read();
                if (ch == ' ')
                {
                    spaces++;
                }
            } while (ch != '.');

            Console.WriteLine("Number of spaces counted = {0}",spaces);
            Console.Read();
        }
    }

Comment: One thing you should do is familiarize yourself with the Visual Studio debugger. There are tons of resources online, but the first thing you can try is setting a breakpoint on a line where you know what is happening. You can do this by hitting F9 on that line, click Debug>Toggle breakpoint, or clicking in the left margin. You can use F10 to step through the code, and hover over variables to see what is happening in your program
Answer: Use Console.ReadKey() instead of Console.Read().

Console.ReadKey() returns if a key has been pressed between after you called Console.ReadKey().
Console.Read() reads the character as in a stream (not useful at all in your case).

To get the char received by ReadKey, use : ch = Console.ReadKey().KeyChar;
Answer: You want ReadKey rather than Read. The latter just reads the next character if it exists on the stream and returns -1 if it doesn't as it won't wait (and you probably aren't typing that fast!)
Answer: Use Console.ReadKey() to get ConsoleKeyInfo. Then verify pressed Key. You don't need to work with characters:
int spaces = 0;
ConsoleKey key;
do
{
    key = Console.ReadKey().Key;
    if (key == ConsoleKey.Spacebar)
        spaces++;
}
while (key != ConsoleKey.OemPeriod);

Console.WriteLine("Number of spaces counted = {0}",spaces);

Keep in mind that period key on NumPad has value ConsoleKey.Decimal. So, if you need to handle both period keys, you should write following condition:
while (key != ConsoleKey.OemPeriod && key != ConsoleKey.Decimal);

Answer: If all you want is to see the result you just use ReadKey instead:
class CountSpaces
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter characters,finish with a period (\".\"");
        char ch;
        int spaces = 0;
        do
        {
            ch = (char)Console.Read();
            if (ch == ' ')
            {
                spaces++;
            }
        } while (ch != '.');

        Console.WriteLine("Number of spaces counted = {0}", spaces);
        Console.ReadKey();
    }
}

However I think the program becomes more interesting if you update it to the following:
class Program
{
    static void Main(string[] args)
    {
        while (true)
        {
            Console.WriteLine("Enter characters,finish with a period (\".\"");
            char ch;
            int spaces = 0;
            do
            {
                ch = (char)Console.Read();
                if (ch == ' ')
                {
                    spaces++;
                }
            } while (ch != '.');

            Console.WriteLine("Number of spaces counted = {0}", spaces);
        }
    }
}

Answer: My example uses Console.ReadKey instead of Console.Read:
class Program
{
    static void Main(string[] args)
    {
        int spaces = 0;
        char key;
        while ((key = Console.ReadKey().KeyChar) != '.') {
            if (key == ' ')
                spaces++;
        }
        Console.WriteLine();
        Console.WriteLine("Number of spaces: {0}", spaces);
        Console.ReadKey();
    }
}

Answer: If we create a helper method that creates a sequence of keys from the console:
public static IEnumerable<char> ReadKeys()
{
    while (true)
    {
        yield return Console.ReadKey().KeyChar;
    }
}

It allows us to write a query describing exactly what you want:
var spaces = ReadKeys()
    .TakeWhile(c => c != '.')
    .Count(c => c == ' ');

Take characters until you get a period, and count the number of spaces.
Comment: Lots of presumably valid illustrations of how this can be implemented, and I'm very grateful (and pleasantly surprised! thanks!)

I'd like to develop this concept further in my mind. var is new to me (runtime type declaration?) and I can't quite see how this would fit in with the rest... can you provide the full implementation of this idea? Are Takewhile and Count class methods?


How to create multiple filters in Django?

Question: I want to create multiple filters in Django.
The screen shot below explains it.

The user may opt not to select some criteria.
If the user does not select Available from, Available till and Advance then I will get the value as None in views.py. If he does not select Category or Capacity then I will get an empty list otherwise I will get a list of Category or Capacity.
The problem arises when there is None or empty list.
Although I have written the code and it works fine but I want to know if there is a better way to do it? My code may have problems if the complexity increases.
forms.py
class RoomForm(forms.Form):

    ROOM_CATEGORIES = (
        ('Regular', 'Regular'),
        ('Executive', 'Executive'),
        ('Deluxe', 'Deluxe'),
        ('King', 'King'),
        ('Queen', 'Queen'),
    )

    category = forms.MultipleChoiceField(
        required=False,
        widget=forms.CheckboxSelectMultiple,
        choices=ROOM_CATEGORIES,
    )

    ROOM_CAPACITY = (
        (1, '1'),
        (2, '2'),
        (3, '3'),
        (4, '4'),
    )
    capacity = forms.MultipleChoiceField(
        required=False,
        widget=forms.CheckboxSelectMultiple,
        choices=ROOM_CAPACITY,
        )

    class TimeInput(forms.TimeInput):
        input_type = 'time'
        default=datetime.time()

    available_from = forms.TimeField(
        required=False,
        widget=TimeInput(),
        )

    available_till = forms.TimeField(
        required=False,
        widget=TimeInput(),
        )

    advance = forms.IntegerField(
        required=False,
    )

    """Function to ensure that booking is done for future and check out is after check in"""
    def clean(self):
        cleaned_data = super().clean()
        available_from = cleaned_data.get("available_from")
        available_till = cleaned_data.get("available_till")
        str_available_from = str(available_from)
        str_available_till = str(available_till)
        format = '%H:%M:%S'
        if str_available_from != 'None':
            try:
                datetime.datetime.strptime(str_available_from, format).time()
            except Exception:
                raise ValidationError(
                    _('Wrong time entered.'),
                    code='Wrong time entered.',
                )
        if str_available_till != 'None':
            try:
                    datetime.datetime.strptime(str_available_till, format).time()
            except Exception:
                raise ValidationError(
                    _('Wrong time entered.'),
                    code='Wrong time entered.',
                )
        if available_till is not None and available_from is not None:
            if available_till <= available_from:
                raise ValidationError(
                    "Available till should be after available from.", code='Available till after available from'
                )

views.py
    if categories == []:
        categories = ['Regular', 'Executive', 'Deluxe', 'King', 'Queen']
    if capacities == []:
        capacities = [1, 2, 3, 4]
    if advance is None:
        advance = 0
    if available_from is None and available_till is None:
        room_list = Room.objects.filter(
        category__in=categories,
        capacity__in=capacities,
        advance__gte=advance
    )
    elif available_from is None:
        room_list = Room.objects.filter(
        category__in=categories,
        available_till__gte=available_till,
        capacity__in=capacities,
        advance__gte=advance
    )
    elif available_till is None:
        room_list = Room.objects.filter(
        category__in=categories,
        available_from__lte=available_from,
        capacity__in=capacities,
        advance__gte=advance
    )
    else:
        room_list = Room.objects.filter(
            category__in=categories,
            available_from__lte=available_from,
            available_till__gte=available_till,
            capacity__in=capacities,
            advance__gte=advance
        )
    return room_list

Link to GitHub repo
I wrote the code but I think there should be a better way.
Comment: Writing these types of filters could be a complicated matter as you would have to also care about different edge cases to make sure that you have the correct response. I would suggest using https://django-filter.readthedocs.io/en/stable/guide/usage.html#, which is an excellent package for these types of tasks.
Comment: @rootart Can I do it without using third party packages?
Answer: A simple solution to your problem is to create complex queries with  Q objects.
You can find more information on that matter here.
Otherwise you can try multiple filters at once:
varName = Room.objects.filter(category__in=categories) | Room.objects.filter(capacity__in=capacities) | Room.objects.filter(capacity__in=capacities)...

use the | symbol to separate the queries
Answer: To query multiple things at the same time, use the | symbol to separate them
varName = Room.objects.filter(category__in=categories) | Room.objects.filter(capacity__in=capacities) | Room.objects.filter(capacity__in=capacities)...

I recently used this in a search view like this
object_list = Post.objects.filter(title__icontains=query) | Post.objects.filter(content__icontains=query) | Post.objects.filter(category__icontains=query) | Post.objects.filter(date_posted__icontains=query) | Post.objects.filter(author__username__icontains=query)


Sewer Gas Smell From Shower But P-Trap Is Full

Question: I smell sewer gas every other day or so in my basement bathroom which has a sink, toilet, and shower. The p-trap on all of them are full and when I get down and smell the drain of the shower, it has a slight stench of the sewer.
Is something wrong? How might the gas be getting into the room if the p-trap is full?
My home was built in the 60s and has cast iron drains under the house. The angle of the shower p-trap is too sharp to scope but I had a plumber scope the drain of the toilet next to it and he found no evidence of a leak or larger issue. Water from the toilet and shower seemed to flow easily. But we technically could not see precisely under the shower.
The plumber did replace the wax seal on the toilet and mentioned the seal there is still not the best but when I lean down there, I don't smell a thing.
He also scoped the sewer vents on top of my house and said they were clear.
When I cover the shower drain with a plastic lid, the smell goes away and does not come back so I am pretty sure it is the culprit - but I am trying to keep an open mind as this does not make a lot of sense to the plumber.
I filled the shower drain with vinegar and then got no smell the next day. Then I added baking soda which foamed and the room filled with sewer gas - I assume because the foaming allowed the gas to flow into the house. Does this mean anything?
My only other thing to add is my Radon mitigation. There is a crawlspace near the bathroom, about 12 feet away which has a large plastic tarp over all the dirt and a radon system pulling air up and out. Any chance this is creating enough pressure to occasionally pull sewer gas out of my shower? It sounds silly but I have no idea what it could be.
Comment: Can you tell us how you know the shower trap is full and effective?  It's not easy to see.
 A siphon could pull out just enough water to leave a millimeter of air open in the trap, which is enough to cause your issues.    You should clean the drain as suggeted by RMDMan to rule that out, but I'd be surprised if the buildup on the sides of a shower drain, maybe one or two inches above the trap, could fill a room with stink.  I'd much more suspect the trap is not doing its job.
Comment: I have a flashlight and can clearly see about 6 inches of pipe and then the top of the water level. The plumber who investigated this issue looked at it and also said it's full.
Comment: Sanity check:  Is the vent for that drain stack plugged, perhaps?
Comment: We ran a scope down the vent from the roof all the way to the sewer line and didn't find any obstructions.
Answer: What you are smelling is most likely not sewer gas but the smell of the icky stuff on the walls of the shower drain.
it doesn't mean you are dirty, quite the opposite. Taking showers puts all sorts of dirt and debris and soap down the drain that, over time, collect on the walls of the drain.
Remove the strainer and use one of the drain cleaning tools that have the Velcro type surface to grab the hair and icky stuff.  Then tape a rag to a long screwdriver and use it to clean the sides of the drain pipe.  ( Tape it well, you don't want to lose it down the drain.)
I've had the same type of problem. This cured it and made my wife happier.
Comment: Rather than taping a rag to a screwdriver I would think a cylindrical brush on a twisted wire shaft would be better. Taping a rag onto a screwdriver sounds like too much risk the rag would come loose. https://www.justmanbrush.com/twisted-in-wire-floor-drain-brushes/
Comment: I used drain cleaner and a brush to clean above the water line. If I need to clean further in... I'd probably need a specialized tool. I would say it's been sanitized between the pure vinegar soak overnight and the drain cleaner today. I'll let you know if it got any better.
Comment: Seems to have worked!


how to enable the submit button in real time depending on text validation?

Question: I have a HTML form in list.php that submits the data from text box ("item" in below code) to check.php. This check.php validates the text entered to be not empty or white spaces only. After validation, it redirects to list.php for the entered text to be displayed. list.php is below. I want the "add" button to be enabled only when valid text is entered in the text box. I would like this feature to be done with php and probably not with javascript.
I can use "disabled=\"disabled\" in the form, but this does not work in real-time disabling depending on validation.
<form action="check.php" method="post">

<input name="item" type="text" size="25" autofocus="autofocus" />

<input type="submit" value="Add" id="add" />

</form>

Comment: you cant with php, its server side, its finished before the user can start typing. has to be done with JS\ajax
Comment: PHP can **never** be used for real-time client features. You have to use a client-side scripting system - JS is the way to go then.
Comment: AJAX blurs the line, he can call 'real time' php validation  via AJAX
Answer: You say:

I would like this feature to be done with php and probably not with javascript.

Unfortunately, if you want "real-time" then you're gonna need JavaScript. You'll need it to make AJAX calls to your PHP code to check for validation.
So either A) you don't validate in "real-time" at all, or B) You use JavaScript in one shape or another.
Let's say you opt for B), to use JavaScript, and presuming ALL you need to do is check for an empty string or whitespace, then you can do all of this client-side in JavaScript and not require a server call at all, also making it truly "real-time".
And so, here is my solution, using JavaScript (jQuery) without relying on server calls. This may not be suitable for your current implementation, but just in case it is, this might be helpful.
JSFiddle:
http://jsfiddle.net/VKfrw/1/
JavaScript:
function hasWhiteSpaceOrEmpty(s)
{
  return s == "" || s.indexOf(' ') >= 0;
}

function validateInput()
{
    var inputVal = $("#myInput").val();
    if(hasWhiteSpaceOrEmpty(inputVal))
    {
        //This has whitespace or is empty, disable the button
        $("#add").attr("disabled", "disabled");
    }
    else
    {
        //not empty or whitespace
        $("#add").removeAttr("disabled");
    }
}

$(document).ready(function() {
    $("#myInput").keyup(validateInput);
});

HTML:

<input id="myInput" name="item" type="text" size="25" autofocus="autofocus" />

This implementation uses jQuery.
Answer: As mentioned, if you want this done in real time some javascript will be needed.
However I think this problem is actually more suited to javascript in general.  PHP validation can be useful if you need to cross reference for data with data in your database.
eg. In a sign up form, checking a user is not already registered with the entered email address.
But in your case, depending on what you mean by "valid text" it is probably easier and better to use javascript.
There are some great jQuery plugins which make javascript validation really simple.
http://docs.jquery.com/Plugins/Validation/validate


How does the shared stash work?

Question: In Torchlight 2 you have access to your regular stash, as well as a thing called a "shared stash".
Torchlight 2 also has multiplayer, which is something the first one lacked. This shared stash has me curious.
Do items in your shared stash only go toward your own characters? Or can other players in your game see the same items?
Answer: Another thing to point out, is that the Shared stash is not shared with Hardcore characters.
They have their own stared stash. So anything you put into your shared stash as a Hardcore character is only seen by your other hardcore characters.
Comment: This is an important piece of information... I was wondering where my stash went when I started my first Hardcore char.
Answer: The contents of the Shared Stash are only visible to your characters, other people in your multiplayer game will not be able to see the contents of your shared stash.
It functions in the same way as the stash in Diablo III.

How does the shared stash work?


1969 Square D QO Panel Busbar Rating and Information

Question: What the is highest amp breaker I'm able to put on this QO Load center QO20-40m200 series L1?
My objective is to add a subpanel for more space, and the 125amp subpanels have a lot more space compared to 100amp subpanels, but it seems this panel's busbar might be "rated", if that's the right term, for up to 100amp breakers. There seems to be information on terminals No. 6 to 1, but how about the other breakers No. 7 to 20?
There doesn't seem to be much information from the manufacture on this panel that is original to the home build in 1969. Square D/Schneider Electric tech support mentioned they don't have any product info on this product, and their website product search for this model, doesn't seem to have anything on this specific model.
Is the qo20-40m200 series L1 most similar to the now discontinued "QO120-40M200" model? If so, is there anything in the datasheet or other document that could provide more details on single breaker safe capacity?
Additional information on this project, a few of the breakers from the main panel could be removed but we'd like to have the redundancy. A 35 amp breaker for a 24btu 240v mini split system is the catalyst for the additional space. The soon to be somewhat redundant heating for the home is six 240v 1500 watt electric force fan wall heaters that is taking up a lot of space in this smaller panel. We should saving a good amount of energy and lightening the overall load on the panel, hence wanting more spaces than less.
Comment: I do not think that the copper wire handle ties on the top breaker are allowed in code.
Comment: Some problems with that panel. It looks like extensive use was made of dual singles with approved handle-ties. That is fine for a) MWBCs or b) 240V-only circuits without neutral (white hot wire). However for 120/240V circuits (dryer, range) with neutral, handle ties are not enough, it must be a factory made 2-pole breaker (distinctive in QO for having only 1 handle). That is because common trip is required.
Comment: You can feed a 125 amp or even a 200 amp sub panel with only a small(40 or 60 amp) breaker.  A bigger sub panel does not give more power, just more breaker spaces, so a load calculation might be needed.
Comment: Panels are rated for the maximum amps they can handle.  Usually for the very little cost for big panels compared to the smaller panels, the recommendation is to go big.  The problem is if you can fully power a big panel, but then you just use a smaller breaker to feed it.  It seems from the label that you can only use up to 100amp breakers in the top spaces.  Unless you can find a label for the lower spaces, then that is what you need to go by.  Can consider labels as the word that goes above what code says.
Comment: Labels are part of the manufacturer's instructions, which code says you must follow, actually... If you want **spaces**, put in a 40-42-space 200A panel as a subpanel. Feed it from a 100A breaker here, unless you really want to go through the hassle of swapping the feed over to it and making this the sub-panel. If you're paranoid that you'll run out of power, get two and run BOTH of them from 100A breakers here....
Comment: Yeah, the panel bus rating is a *redline never-exceed maximum*, go look at your car tires and see where it says 130 MPH.  Bet you drive slower than that *all the time* and you haven't had any tires blow. So likewise a 200A bussed subpanel will be happy as a clam fed by a 90A breaker. (90A is a great feeder size since it's popular and cheap - #2 aluminum).
Comment: ty, @crip659

any additional insight on why you're confident in saying 125 amp is suitable?
Comment: @Harper-ReinstateMonica from the label we can see the first one is a wall heater, so indeed this is a 240V load. I bet it doesn't have a neutral though. OP can add a picture to let us sniff around more, or take your advice to heart and check for themselves.
Answer: Your question implies that you suffer a common delusion that "feed breaker must match sub-panel size" - it DOES NOT.
Feed breaker must be sized to protect the wires (but the wires can be oversized - they will still be protected.) Sub-panel must be rated at least as large as the feed breaker. Sub-Panel can also be ANY size larger than the feed breaker.
So, if you want 125A panels "for the spaces" just put in a 100A breaker to feed that and you're good. Or buy a 200A panel for (perhaps) even more spaces. Both of those can very happily and legally be fed from a 100A breaker.
Comment: The issue is that it's a somewhat poorly documented (according to your question, and I'll believe you) 54 year old panel. It's a *good* one, (QO's have a deserved good reputation) but there's a difference between running 200A **into** the full-width bus-bars on those bolted connections to the main breaker and running more than 100A **out of** the small tab on the bus that a breaker connects to by a spring clip. You can see two of those just above the 50A dual with nothing connected to it. Notice how much smaller they are than the bus itself they connect to?
Comment: If you swap the main feed over to a new panel, there is NO reason not to keep this perfectly good (if poorly documented) QO panel as a sub-panel. It could even have full power available to it if your new panel is chosen to have "feedthrough lugs" (large lugs on the bottom of the bus bars to connect 200A wire to an additional panel, protected by the main breaker in the panel with feedthrough lugs, only.)
Comment: Good point. after a conversation with a retired electrian today, I'm leaning toward replacing the panel to a 42 space panel, and scrapping this whole subpanel idea.

Nevertheless, why would the busbar not be able to handle or be rated up to 200 amp, since that is what the panel is rated for? It seems 125amp breakers would work fine for a panel that can handle 200amps. Did 125amp breakers not exist hence not specifically mentioned? Is it common for the best place to place higher amp breakers closer to the main 200 amp breaker shut off?
Answer: A bunch of issues:

6 to 1 is not referring to breaker space locations. Yes, sometimes certain breaker locations have particular preferred uses. That's not what this is about. This is referring to wire sizes for 70A and 100A main breakers. The sizing makes sense. 6 AWG copper is rated for 65A at 75 C, which gets upsized to allow 70A breaker since there are no 65A breakers. 1 AWG aluminum is 100A at 75 C. Everything else you might use (copper or aluminum) will be between 6 AWG and 1 AWG.
Harper pointed out that there are some handle-tied breakers that probably need to be actual common-trip double breakers. In addition, there are some breakers at the top that are handle-tied with bare copper wire - they couldn't even find a right-sized nail! If those breakers are otherwise OK then replace the handle-ties with proper Square D handle ties - they're all of $7.50 for a 3-pack at Home Depot.

The instructions really don't say much about maximum branch breaker sizes. At the time, there weren't generally many larger than 60A. Since this is a 200A panel, I would keep the large loads (HVAC, range/oven, EVSE if you need that, etc.) in the main panel and you could probably get a lot of usage out of running even a 60A feed to a 100A or 125A or even 200A subpanel. Note that a subpanel doesn't have to be "only" a subpanel - it can be a big "main" panel if the price is right (and it often is!). The only thing that really matters is keeping ground and neutral separate. If you put in a large subpanel but populate it with lots of small circuits and do a load calculation that shows it fits in 60A (that's 60A @ 240V, so 120A of 120V circuits, and based on load calculation/usage and not adding up the breaker sizes) then it really doesn't matter if it has a lot of stuff in it.
Comment: The "6 to 1" is more specifically talking about type Q1 main breakers that can optionally be installed instead of the default Q2 200A unit. Branch breakers will come with their own instructions and wire size information.


thor websocket load testing - add custom http header in web socket handshake request

Question: I am using thor for load testing my twisted based autobahn websocket server. For authentication purposes my websocket application need a custom http header (Authorization : Bearer token) in websocket handshake request as part of authentication. How can I do this ?
Answer: It doesn't look like thor supports adding headers so you either need to patch it to add this support or consider another tool like:

Gatling
Apache JMeter
Comment: Thanks @Dmitri. I did the patch as the underlying ws node library which is used by thor support this feature.


Object allocated on stack continues to exist after stack frame is gone

Question: I'm a C++ beginner, although I have some experience with C.  I was looking at this code snippet on operator overloading from this source:
https://www.geeksforgeeks.org/operator-overloading-c/
#include<iostream>
using namespace std;

class Complex {
private:
    int real, imag;
public:
    Complex(int r = 0, int i =0)  {real = r;   imag = i;}

    // This is automatically called when '+' is used with
    // between two Complex objects
    Complex operator + (Complex const &obj) {
         Complex res;
         res.real = real + obj.real;
         res.imag = imag + obj.imag;
         return res;
    }
    void print() { cout << real << " + i" << imag << endl; }
};

int main()
{
    Complex c1(10, 5), c2(2, 4);
    Complex c3 = c1 + c2; // An example call to "operator+"
    c3.print();
}

I do not understand how the "res" object created in the "+" function continues to exist after "+" returns.
Shouldn't the stack frame and all of its contents be deleted after the return statement?  My intuition says that c3 has been assigned to an object that no longer exists, so the call to c3's print function should not work, as the object it refers to has been destroyed.
If this was C, rather than C++, res could be saved by using "malloc" to allocate memory on the heap, meaning it wouldn't live in a stack frame and so would not be deleted.  But it seems that nothing of the sort is done here.
What is wrong with my reasoning?  Is this a difference between C and C++, or have I misremembered some aspect of C?  Or perhaps both?
Comment: It doesn't. `operator+` returns a copy of that object. Works the same way as in C.
Comment: *If this was C, rather than C+* -- You are wrong about `C`.  If you declare a `struct` in C and return it by value, there is absolutely nothing wrong with doing that.  So your entire reasoning is based on faulty logic.
Comment: @Superman - except there is potential that the compiler will implement the return value optimisation and/or elide temporaries.   The C++ standards goes out of their way to permit that (all versions of the standard) or to require it in various circumstances (more recent versions of the standard).
Comment: For an example, [returning an array wrapped in a struct](https://stackoverflow.com/questions/27410943/returning-arrays-from-a-function-in-c/27411483#27411483).  This works in C and C++.
Comment: If you add a copy / move constructor in the `Complex` class you can see how the local object is being returned.
Comment: If I understand correctly, the original res dies, but before that, res is copied into c3.  If I had instead returned a pointer to res, (and c3 was also a pointer rather than an object), the pointer would have been successfully copied, but the res object would have been destroyed, leaving c3 as a dangling pointer.  I think I ran into that problem in the past, and misremembered it as being the case here.  Thanks, everyone.
Comment: @Peter - yes, thanks for mentioning that. So make sure to run with all optimizations disabled
Answer: It doesn't. res is copied into the return value, then res is destroyed, then the function returns.
Then the return value is copied into c3, then the return value is destroyed.


Fault when attempting to jmp after entering protected mode - assembly bootloader

Question: I've been trying all day to figure this out. I'm following a tutorial on writing a bootloader and I'm stuck when it comes to entering protected mode properly. I don't know what I'm doing wrong and I've been googling all day. I'm compiling using NASM
This is the output I get in Bochs dbg:

It is saying that the CPU is indeed entering protected mode, and I am getting errors shortly after that.
This is the second re-writing of this i've done, aiming primarily to get in to protected mode without errors.  I'd love if anyone could tell me what I'm doing wrong.
My code is as follows:
bootloader.asm
global _start

_start:

[bits 16]
[org 0x7c00]

    mov bp, 0x8000
    mov sp, bp

    mov bx, welcomeString
    call print_func

    call print_newline_func

    call switch_to_pm

    jmp $

%include "io.asm"
%include "print.asm"
%include "gdt.asm"

welcomeString:
    db 'Hello. Welcome to OS', 13, 10,0

switch_to_pm:
    cli

    lgdt [gdt_descriptor]
    mov eax, cr0
    or eax, 0x1
    mov cr0, eax

[bits 32]

    jmp CODE_SEG:init_pm

init_pm:

    mov ax, DATA_SEG
    mov ds, ax
    mov ss, ax
    mov es, ax
    mov fs, ax
    mov gs, ax

    mov ebp, 0x90000
    mov esp, ebp

    call BEGIN_PM

BEGIN_PM:
    mov ebx, MSG_PM
    call print_string_pm

    jmp $

MSG_PM:
    db 'success', 0

times 510-($-$$) db 0

dw 0xaa55

io.asm
BOOT_DRIVE:
        db 0

    ReadDisk:                   ; Reads from drive dl amount of sectors to read dh

        push dx                 ; Store dx to stack

        mov ah, 0x02            ; BIOS read sector code
        mov al, dh              ; Read dh sectors
        mov ch, 0x00            ; Select cyl 0
        mov dh, 0x00            ; Select 1st track,
        mov cl, 0x02            ; Select 2nd sector (1st after boot sector)

        int 0x13                ; Read interrupt code

        jc disk_error           ; Jump if error

        pop dx
        cmp dh, al              ; jump if sectors expected != sectors read
        jne disk_error

        ret

    errorString:
        db 'Disk Read Error.',13,10,0

    disk_error:
        mov bx, errorString
        call print_func
    ret

gdt.asm
gdt_start:
    gdt_null:       ; null descriptor
        dd 0x0
        dd 0x0

    gdt_code:           ; the code segment descriptor
                        ; base =0x0 , limit =0 xfffff ,
                        ; 1st flags : ( present )1 ( privilege )00 ( descriptor type )1 -> 1001 b
                        ; type flags : ( code )1 ( conforming )0 ( readable )1 ( accessed )0 -> 1010 b
                        ; 2nd flags : ( granularity )1 (32 - bit default )1 (64 - bit seg )0 ( AVL )0 -> 1100 b
        dw 0xffff       ; Limit (bits 0-15)
        dw 0x0          ; Base (bits 0 - 15)
        db 0x0          ; Base (bits 16 - 23)
        db 10011010b    ; 1st flags, type flags
        db 11001111b    ; 2nd flags, limit (bits 16-19)
        db 0x0          ; Base (bits 24-31)

    gdt_data:           ; the data segment descriptor
                        ; Same as code segment except for the type flags :
                        ; type flags : ( code )0 ( expand down )0 ( writable )1 ( accessed )0 -> 0010 b
        dw 0xffff       ; Limit (bits 0-15)
        dw 0x0          ; Base (bits 0-15)
        db 0x0          ; Base (bits 16-23)
        db 10010010b    ; 1st flags, type flags
        db 11001111b    ; 2nd flags
        db 0x0          ; Base (bits 24-31)

    gdt_end:            ; Put this label to calculate size of GDT

gdt_descriptor:
    dw gdt_end - gdt_start - 1      ; GDT size, always 1 less than true size
    dd gdt_start                    ; start address of GDT

CODE_SEG equ gdt_code - gdt_start
DATA_SEG equ gdt_data - gdt_start

print.asm
print_func:
    push bx
        mov ah, 0x0e
        ;add bx, 0x7c00                 ; calculate correct address
        print_loop:
            cmp byte [bx], 0            ; if char at bx == 0, jump to exit.
            je print_exit
            mov al, [bx]                ; move char at bx into al
            int 0x10                    ; print
            inc bx                      ; increment bx
            jmp print_loop              ; loop to start of func
            print_exit:
            pop bx
                ret

print_newline_func:
    push ax
    mov ah, 0x0e
    mov al, 10
    int 0x10
    mov al, 13
    int 0x10
    pop ax
    ret

print_hex_func:
    push ax
    push bx
    push cx

    mov ah, 0x0e

    mov al, '0'
    int 0x10
    mov al, 'x'
    int 0x10                    ; print 0x

    ;add bx, 0x7c00

    mov cx, [bx]
    shr cx, 12
    call PrintAsciiFromHex

    mov cx, [bx]
    shr cx, 8
    call PrintAsciiFromHex

    mov cx, [bx]
    shr cx, 4
    call PrintAsciiFromHex

    mov cx, [bx]
    call PrintAsciiFromHex

    pop ax
    pop bx
    pop cx

    ret

PrintAsciiFromHex:
    shl cx, 12
    shr cx, 12
    cmp cx, 9
    jg Add55
    add cx, 48
    jmp Skip
    Add55:
        add cx, 55
    Skip:
    mov al, cl
    int 0x10
    ret

AddressPointer:
    dw 0

PrintAddress:                   ; Moves address of bx into value of AddressPointer
    mov [AddressPointer], bx    ; Passes address of address pointer into bs
    mov bx, AddressPointer      ; prints value of address pointer, therefore printing address
    call print_hex_func
    ret

[bits 32]

                                    ; Define some constants
VIDEO_MEMORY equ 0xb8000
WHITE_ON_BLACK equ 0x0f

                                    ; prints a null - terminated string pointed to by EDX
print_string_pm:
    pusha
    mov edx, VIDEO_MEMORY               ; Set edx to the start of vid mem.
    print_string_pm_loop :
        mov al , [ ebx ]                    ; Store the char at EBX in AL
        mov ah , WHITE_ON_BLACK             ; Store the attributes in AH
        cmp al , 0                          ; if (al == 0) , at end of string , so
        je print_string_pm_done             ; jump to done
        mov [edx] , ax                      ; Store char and attributes at current
                                            ; character cell.
        add ebx , 1                         ; Increment EBX to the next char in string.
        add edx , 2                         ; Move to next character cell in vid mem.

        jmp print_string_pm_loop            ; loop around to print the next char.
    print_string_pm_done :
        popa
        ret                                 ; Return from the function

Comment: And that is because you put that jmp into `bits 32` while you are still in a 16 bit code segment (because CS has not been reloaded obviously). Move it up to before the `bits 32`. Actually even your `print.asm` has a `bits 32` so you are already in 32 bit mode due to the include. You need to stick a `bits 16` before `switch_to_pm`. Or clean up your includes. The good news is, it works otherwise :)
Comment: Something wrong with your binary. Note that bochs shows `jmpf 0:7d1d` while `CODE_SEG` should be `8`.
Comment: You're an absolute legend, I didn't even realise that I had left that [bits 32] in there. I added a [bits 16] after the function to return it to 16 bit mode and moved the jmp and it's working exactly how i wanted it to. I can't thank you enough! I can't believe it was something so small
Answer: Solved by returning to [bits 16] after the 32 bit function in print.asm and moving jmp to above the change to [bits 32]


How do you scale an image across planes while retaining perfect tiling?

Question: Scaling up or down a texture is quite simple, modify the UVs.
In my particular scenario though, I have multiple "quads" (it is a patch tessellation shader) each with a tiling texture. Does anyone know of a way to change the texture scale, while retaining the tiling in the shader?
Is precomputing/scaling the uvs on the CPU the only option?
Example of (traditional) tiling problem:
Answer: One solution would be to use repeating texture wrapping, and then use a texture transformation matrix. So let's say you normally set the texture coordinates of your GL_TEXTURE_2D to be 0-1 in u and v. Instead, ensure that your GL_TEXTURE_WRAP_S and GL_TEXTURE_WRAP_T are set to GL_REPEAT or GL_MIRRORED_REPEAT and set the texture coordinates to be the tile number to tile number + 1. So the first one would still be 0 to 1. The second one would be 1 to 2, the third would be 2 to 3, etc.
Next, your vertex shader would have a mat4 uniform called textureMatrix or something like that. The texture matrix you pass in could have scaling in it (and probably other transformations, too). You just multiply the texture coordinates for the polygons by the texture matrix in the vertex shader, and it should apply appropriately.
Comment: Using a transform matrix for UVs is super clever! I'll have to refactor my system a little, since I was (happily) using only 1 uv, but your answer seems like a good solution. Thank you!


php mysql select something and get columns from other tables

Question: I'm using prepared statements and I need to "select" other table, apart from these two, to get data but I get this:
Fatal error: Call to a member function bind_param() on a non-object in C:\xampp\htdocs\views\user\referral.php on line 16

If I add in SELECT table1.* , table.* , "theothertable.*"
$stmt = $mysqli->prepare("SELECT friends.*, rc_usuario.* // or just *
    FROM friends
    INNER JOIN rc_usuario ON rc_usuario.id = friends.friendID
    WHERE friends.userID = ?");

$stmt->bind_param('s', $connectedUserID);

This is working fine, I get what i need, but I also need to get data from another table and I can't make other select because i need it all in a while to print all the data together.
The question is, can I SELECT something like that from 2 tables and also get data from other table/s?
Thank YOU!
EDIT: Add the new statement:
    if ($stmt = $mysqli->prepare("SELECT friends.*, members.*, account_type.*
    FROM friends
    INNER JOIN members ON members.id = friends.friendID
    INNER JOIN account_type ON account_type.name = members.acc_type
    WHERE friends.userID = ? AND members.acc_type = ?")) {

    $stmt->bind_param('is', $connectedUserID, $connectedAcc_type);
    $stmt->execute();
    } else echo $mysqli->error;

Answer: You can join more tables by using another INNER JOIN, like as follows;
INNER JOIN rc_usuario ON rc_usuario.id = friends.friendID
INNER JOIN rc_another ON rc_another.col = friends.coljoin

Just make sure you select all the columns you want in the joined table.
It might also help to run your prepare statement in an if, like this;
if($stmt = $mysqli->prepare("SELECT ...")) { // ... where the rest of your query is
    $stmt->bind_param('s', $connectedUserID);
    $stmt->execute();
}
else {
    echo $mysqli->error;
}

which will give you an idea of any problems with the SQL syntax.
Hope this helps.
Comment: Thanks for the quick response! I added the if and else and is giving me this error: Not unique table/alias: 'members'
Fatal error: Call to a member function get_result() on a non-object in C:\xampp\htdocs\views\user\referral.php on line 25
Comment: Where you edited your question, don't say `FROM friends, members`, just say `FROM friends` as you then join members right afterwards. The second error is because there is no result because of the error in the SQL.
Comment: Ah yes, that's why error reporting is so useful! If this answer worked for you, you can accept it by clicking on the tick on the left.


If a parameter of event handler contains certain characters, JavaScript does not execute properly

Question: php:
$str1 = "AAA\r\nBBBB\\CCC";
echo"<textarea id='aa1' onfocus='erase(\"".$str1."\", \"aa1\");'></textarea>";
$str2 = "AAABBBB\\CCC";
echo"<textarea id='aa2' onfocus='erase(\"".$str2."\", \"aa2\");'></textarea>";
$str3 = "AAABBBB\CCC";
echo"<textarea id='aa3' onfocus='erase(\"".$str3."\", \"aa3\");'></textarea>";
$str4 = "AAABBBBCCC";
echo"<textarea id='aa4' onfocus='erase(\"".$str4."\", \"aa4\");'></textarea>";

javascript:
function erase(str, id)
{
    alert("good");
    var field = document.getElementById(id);
    if(field.value == str)
    {
        field.value = '';
    }
}

If I click on textarea id='aa1', nothing happens.
If I click on textarea id='aa2' or textarea id='aa3', 'good' is printed but nothing happens to field.value.
If I click on textarea id='aa4', 'good' is printed and field.value is ''.
I want a string like AAA\r\nBBBB\\CCC to work like textarea id='aa4.
How can I do that?
I read the post below but it does not seem to help my situation:
Javascript parameter
Javascript Line Break Textarea

update:
I've replaced $str1 with json_encode($str1), So alert(); works fine now. (Thanks to Jordan Running.)
But the field.value part still does not work.
code refactoring is too hard in my situation... Is there any way to handle the field.value problem without code refactoring?
If quotes corrupt my HTML, I can putting $str1 in htmlspecialchars() and displaying it in <textarea>.
Comment: Check the error console?
Comment: JS string cannot handle newlines. You can JSON encode them if you need the crlf
Comment: String building JS from another language is a bad idea. Consider researching unobtrusive JS.
Answer: Generally speaking it's a bad idea to use string concatenation to build JavaScript. Your PHP code produces the following HTML:
<textarea id='aa1' onfocus='erase("AAA
BBBB\CCC", "aa1");'></textarea>

That's valid HTML, but the code in your onfocus attribute is not valid JavaScript. In JavaScript, you can't have a line break in the middle of a string literal. You can have a line break in a template literal (i.e. `one of these`), but that's not the right solution here.
A quick but short-sighted fix
When you need to "inject" some data into a block of JavaScript, you should always use json_encode:
$str1 = "AAA\r\nBBBB\\CCC";
echo "<textarea id='aa1' onfocus='erase(" . json_encode($str1) . ", \"aa1\");'></textarea>";

Make careful note of the quotation marks above. Because json_encode wraps strings in quotation marks, you don't need additional quotes around . json_encode($str1) ..
This will produce the following HTML:
<textarea id='aa1' onfocus='erase("AAA\r\nBBBB\\CCC", "aa1");'></textarea>

...whose onfocus handler works correctly, as you can see in this snippet:

function erase(...args) { console.log('erase called with', args); }
<textarea id='aa1' onfocus='erase("AAA\r\nBBBB\\CCC", "aa1");'></textarea>

A better way
The above is still fragile. What if your data has a ' in it? That'll break your HTML. The correct solution is to move your data out of the HTML entirely. Consider if you refactored your code to look something like this:
<textarea id="aa1"></textarea>
<textarea id="aa2"></textarea>
<textarea id="aa3"></textarea>
<textarea id="aa4"></textarea>
<?php
  $erase_map = [
    'aa1' => "AAA\r\nBBBB\\CCC",
    'aa2' => "AAABBBB\\CCC",
    'aa3' => "AAABBBB\CCC",
    'aa4' => "AAABBBBCCC",
  ];
?>

In the above code, all of the data is in one place—a single associative array—instead of scattered around your HTML. It generates HTML code with a
Comment: If quotes corrupt my HTML, I can putting `$str1` in `htmlspecialchars()` and displaying it in ``.  Is there any way to handle the `field.value` problem without code refactoring? @JordanRunning
Comment: @Saturn It's hard to help you solve a problem if you don't explain what it is. However, I have a feeling the issue is that you're comparing `AAA\r\nBBBB…` to `AAA\nBBBB…`. See this related question: https://stackoverflow.com/questions/14217101/what-character-represents-a-new-line-in-a-text-area If you're still having trouble, post a new question.


Android wear works only on signed .apk

Question: Description:
I've phone app and wear app - which works only with phone app.
I've recently updated target and compile SDK to 27.
I've been testing performance on Android P preview, but accidentally I've found problem on all devices.
Problem:
Wear app can't communicate with phone app (and vice-versa) while installing both apps as "run" from Android Studio.
On the other hand - When I generate signed APK with key both release/debug versions of app communicate with each other (phone app & wear app) - OK
I have same "applicationId" for both apps.
Also it does not seems to be problem related to code, as both app works on signed APKs.
Any idea what can be wrong?
Comment: Try to upload phone app to device/emulator which is connected to another wear device/emulator and let wear app be installed automatically
Answer: Resolved
As mentioned in documentation:
https://developer.android.com/training/wearables/data-layer/

Important: Your phone and Wear APK signatures and the signature schemes must to be identical for the DataLayer API to be able to successfully communicate between devices. This includes your usage of the v1 and/or v2 signature. Ensure the signature scheme is set correctly in build.gradle or when you use the Generate Signed APK wizard

I have added in each (Wearable and phone) build.gradle
<code>android {
        signingConfigs {
        debug {
            storeFile file("myKey.keystore")
        }
    }
...
}
</code>
about keystore.

When running or debugging your project from the IDE, Android Studio
  automatically signs your APK with a debug certificate generated by the
  Android SDK tools. The first time you run or debug your project in
  Android Studio, the IDE automatically creates the debug keystore and
  certificate in $HOME/.android/debug.keystore, and sets the keystore
  and key passwords.

source: https://developer.android.com/studio/publish/app-signing
Comment: Could you add more detailed solution? For example where to get keystores from and where exactly this chunk of code should be placed.

Android wear works only on signed .apk


Regexp with sub-strings depending on previous string

Question: Using regexp, I want to remove a string prefix which starts with a word foo and which is optionally by another pattern: :bar. However, I do NOT want to match any other pattern containing ::

fooHELLO - match and capture foo
foo:barHELLO - match and capture foo:bar
foo:xHELLO - NO MATCH

So how do I make the : optional, but if it's there, it must be followed by bar?
I tried this:
^foo(:bar)?(?!:)

And it almost works, however since there's no relation between the optional accepted string and the optional forbidden string, the last case here doesn't work:
fooHELLO -> ✅ HELLO
foo:barHELLO -> ✅ HELLO
foo:XHELLO _> ✅ no match
foo:bar:HELLO -> ❌ no match, but should be :HELLO

If I use a logical or:
^foo((:bar)|(?:[^:]))

Then instead the first one fails:
fooHELLO -> ELLO ❌ H was consumed
foo:barHELLO -> ✅ HELLO
foo:XHELLO _> ✅ no match
foo:bar:HELLO -> ✅ :HELLO

So how can I make a regexp with "either foo is followed by :bar and then match foo:bar, or foo is followed by something that does not start with : and then match just foo", so that it can be used with JavaScript String.replace(pattern, '') function to get rid of the prefix?
Comment: Maybe something like `^foo(?!:(?!bar))(?::bar)?`? See https://regex101.com/r/pjgJir/1
Answer: Try this: https://regex101.com/r/gJ7PiJ/1
Regex: (?<=foo:bar|foo(?!:)).*$
Rough human translation: look behind to see foo:bar or foo followed by not a colon and then capture till the end from there
Note this captures everything after the foo:bar/foo pattern (so the HELLO part from your examples)


How do I identify similar dynamic elements with same id uniquely with jQuery?

Question: So I have these elements, generated by a PHP loop:
<input id="toggler" data-toggle="toggle" data-id="1" data-size="small" data-on="Yes" data-off="No" type="checkbox" checked="checked">
<input id="toggler" data-toggle="toggle" data-id="2" data-size="small" data-on="Yes" data-off="No" type="checkbox" checked="checked">
<input id="toggler" data-toggle="toggle" data-id="3" data-size="small" data-on="Yes" data-off="No" type="checkbox" checked="checked">

This uses JQuery UI's toggler.
Now what I want to do, is simply, when one of them is checked or unchecked by the user, send through an ajax call to unpublish them in the DB.
var base = "http://whatever.com/";
var id = $(this).data(id);
var formData = {id:id};

$.ajax({
        type: "POST",
        url: base+'unpublish',
        data: formData,
        success: function(data) {
        // data is ur summary
                $('#result').html(data);
            }

        });

Question: How do I uniquely identify each element without having to name each specifically?
Thanks
Comment: Id have to be unique. And I am typing this comment for 3342th time. :)
Comment: your markup is invalid .. **id's must be unique**
Answer: You know you must have one unique id in a single document--remove them from your loop.
var base = "http://whatever.com/";

$('*[data-toggle="toggle"]').on('click', function(){

  var target = $(this),
      action = (target.is(':checked') ? 'unpublish' : 'publish'), // get action type based on checkbox checked attribute.
      id     = target.attr('data-id');

  $.ajax({
      type: "POST",
      url: base+action,
      data: {id:id},
      success: function(data) {
          // data is ur summary
          $('#result').html(data);
          // update checked attribute.
          (target.is(':checked') ? target.prop('checked',false) : target.prop('checked',true));
      }
  });

});

Answer: If you want to have an easy way to access multiple elements they should use a common CLASS not ID.  IDs must be unique within a HTML document so as others have mentioned your HTML is invalid.
You could do something like this:
<input class="toggler" id="1" data-toggle="toggle" data-id="1" data-size="small" data-on="Yes" data-off="No" type="checkbox" checked="checked">
<input class="toggler" id="2" data-toggle="toggle" data-id="2" data-size="small" data-on="Yes" data-off="No" type="checkbox" checked="checked">
<input class="toggler" id="3" data-toggle="toggle" data-id="3" data-size="small" data-on="Yes" data-off="No" type="checkbox" checked="checked">

You can find them all in jQuery by referencing the class:
$( ".toggler" )

Comment: This is an oversimplification of solution .... OP then needs access to data to send also. There isn't much more here than what is mentioned in comments already
Answer:
Question: How do I uniquely identify each element without having to
  name each specifically?

As pointed out at comments and Answers, id of element should be unique. You can remove id from elements and identify each element by its data-id attribute, which are unique at html at Question.
<input data-toggle="toggle" data-id="1" data-size="small" data-on="Yes" data-off="No" type="checkbox" checked="checked">
<input data-toggle="toggle" data-id="2" data-size="small" data-on="Yes" data-off="No" type="checkbox" checked="checked">
<input data-toggle="toggle" data-id="3" data-size="small" data-on="Yes" data-off="No" type="checkbox" checked="checked">

   $("input[data-id=1]") // first `input`
   $("input[data-id=2]") // second `input`
   $("input[data-id=3]") // third `input`


Convert Object type to a DateTimeOffset

Question: I have a dictionary of string and object, for integer part I can use
Convert.ToInt32() , but for DateTimeOffset, I can't seem to find any (there's Convert.ToDateTime() but I'm afraid the Offset part would be trimmed), I tried searching the stackoverflow and web but nothing can be used.
Please help.
Update:
How I initialize the Dictionary and Watch window result.
StoreID is int, the other is DateTimeOffset.

Comment: You can either use DateTimeOffset.Parse() or if the object was originally a DateTimeOffset just cast it to that.
Comment: Have you tried DateTimeOffset.Parse() ?
Comment: @DCCoder I'll try that, but the object needs to be converted with .ToString() first, I wonder if there are any way to directly convert object type to DateTimeOffset type. Thank you for your suggestion.
Comment: @DCCoder I've tried typecasting it, something like DateTimeOffset a = (DateTimeOffset) obj; But I get Specified cast is not valid error.
Comment: Can you show how you are getting the data into the dictionary?
Comment: What is the actual type of the object? (`object.GetType()`)
Comment: If you look at the object in a watch window in the debugger, you will see the type of the object. Then, once you have that (and share it with us by editing your question), there should be a path forward
Comment: @Corey sorry for late reply `Data = new Dictionary()
                {
                    {"ID", Id}, // int
                    {"Date", DateTimeOffset.Now} //DateTimeOffset
                };`
Comment: Is there any specific reason that you are trying to store multiple types in an object like this?  Why not create an object that can store all of that information and then you can store it in a dictionary.
Answer: Firstly, I think that storing multiple types of data like this is probably A Bad Idea - see below for alternatives.  C# is strongly-typed (for the most part) and works best when it knows ahead of time what is going on with the types.  But it does have ways of determining what type is actually stored in an object and let you cast back into proper typed references.
In this case the best fit for your issue seems to be the is operator.  This will let you test whether an object (or reference, or...) is compatible with the specified type:
object val = task.Data["StartDate"];
if (val is DateTimeOffset)
{
    var dto = (DateTimeOffset)val;
    // do something with the DateTimeOffset
}

In C# version 7 they introduced a pattern matching variant that lets you abbreviate the type conversion:
object val = task.Data["StartDate"];
if (val is DateTimeOffset dto)
{
    // do something
}

This works for both reference and value types, and will pass any valid non-converting typecast.  It's handy for testing interfaces on types in generic code too:
if (someobject is IDisposable disp)
{
    disp.Dispose();
}

In general though I would avoid your dictionary of objects as much as possible.  While there are some cases where it is valid, those cases are fairly rare.  The ViewBag in ASP.NET MVC for instance is one case where it kind of works, but there are other ways that could have been done.
The why is simple: boxing and unboxing values takes time.  Testing the types of values takes time that you mostly don't need to waste if you're using static types.  And you don't have to worry about someone sticking a string where you're expecting an int.
For your own code the more normal case would be to define a class to hold the task data and pass that:
public class TaskData
{
    public int StoreID { get; set; }
    public DateTimeOffset StartDate { get; set; }
}

... and use it as:
task.Data = new TaskData { StoreID = storeID, startDate = DateTimeOffset.Now.AddDays(3) };

Now you task will know what it's dealing with directly, no casting required.  And no chance that someone will come along and assign some wacky value that your code doesn't know how to deal with into one of your variables.  Or forget to use DateTimeOffset and use DateTime instead, with no complaint at all from the compiler.
If you're really averse to defining all sorts of classes just for this sort of thing you can use the C#7 Tuple types to do something similar:
// in your task class:
public (int StoreID, DateTimeOffset StartDate) Data { get; set; }

// initialize in other code:
task.Data = (storeID, DateTimeOffset.Now.AddDays(3));

In the above the type is defined at compile time with decorations for the names and such so that you can use them elsewhere in your code, but they are effectively syntactic sugar used by the compiler and not available at runtime via reflection etc.  Think of it as a handy short-hand for simplifying certain things.
Of course if you have a genuine need to use a Dictionary<string, object> for this data then go ahead.  Just ask yourself if the overheads are worth the effort.

Convert Object type to a DateTimeOffset


Is it possible to scope a broadcast to an application?

Question: I want to use sendBroadcast to broadcast an intent that can only be received by that application that originated it.
The use case is for an authentication module I'm planning to use between several projects I've built. Currently when a 401 (authorization failed) response code is received it broadcasts an intent that can then be wired in the manifest to bring the user back to the login page.
So just to be clear I'm wondering if I can do this:
Intent i = new Intent("my.custom.logout.broadcast.path.that.will.be.the.same.in.multiple.apps");
sendBroadcast(i);

And somehow the intent doesn't get picked up by other apps that use exactly the same un-modified code base.
Comment: You could put data in the intent and add logic to each app to only act upon an intent with data specific to that application. Unfortunately this doesn't solve the problem of using existing code.
Answer: Not part of the question, but you should be using permissions for restricting who can send/receive the Broadcasts, especially since you're dealing with authentication.  In fact, I would highly recommend looking into the AccountManager (in API demos)
Moving on.. one solution is to pass the originating application's package name or a particular permission string in an Intent extra, and when you respond, use that package name or permission in the response, the same way.  Unfortunately you can't target a specific package in a Broadcast Intent.
Yet another solution, is using PendingIntent.getActivity() from the originating application, stuff that PendingIntent into the new for-broadcast Intent as an extra (Intent#putExtra()) and broadcast it using the permissions model above (so sender and receiver can handle permissions properly).  When the broadcast receiver has finished doing its thing, it can use the PendingIntent to start the target activity (including the ability to attach additional extras)
Comment: I like the idea of passing an intent extra. Thanks for that. I think it'll fit my solution perfectly.
Answer: For this you can use the LocalBroadcastManager, which is specifically designed for in-app communication.
Comment: But not inter-process


Auto update chrome extension not in web store

Question: I am working on a private extension that I do now want to publish on the web store so I have specified an "update_url" in the manifest. Now the problem is that auto update is only working for extensions that are published on the web store.
Is there a way to keep it not published and be able to have an auto update for my extension ?
This is what I have done :
manifest.json:
<code>"update_url": "https://localhost:44382/updates.xml"
</code>
updates.xml:
<code><?xml version='1.0' encoding='UTF-8'?>
<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>
  <app appid='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'>
    <updatecheck codebase='https://localhost:44382/extension.crx' version='2.0' />
  </app>
</gupdate>
</code>
Answer: Try including some code contained in the extension that will compare version numbers in the manifest and update from a git folder that has continuous integration set up.


ListView Column Resize in Delphi XE4

Question: I face a issue with dynamically resizing the column width of a TJVListview in Delphi XE4 (in Windows 7 environment). Application takes longer time for column resize and sometimes throws access violation if there are huge data on the listview. We are using the below code for resizing the columns.
for i := 0 to LV.Columns.Count -1 do
begin
  if LV.Columns.Items[i].Tag = 0 then
  begin
    LV.Columns.Items[i].Width := ColumnTextWidth;
    LV.Columns.Items[i].Width := ColumnHeaderWidth;
  end;
end;

Previously the same code used to work fine with Delphi 2009. The problem I noticed only when we are using customdrawitem event(Where we are placing images inside the listview). For the normal listview with only text display the above code is working fine.
I tried using the Column AutoSize property by setting it true, but it is of no use.
Any suggestion on how to overcome this issue. Actually, we are using the TJVlistview component in number of places in our application.
Regards,
Siran.
cODE :
1) In my form I have a JVListview, Button and imagelist.  Button for loading into List view.
2) in Advancecustomdrawitem, I try to place a BMP control and also perform alternative row color change...
procedure TForm1.Button1Click(Sender: TObject);
var
  i, ii: Integer;
  ListItem: TListItem;
  strVal : String;
begin
  strVal := 'Test String';
  try
    ListView.Items.BeginUpdate;
    LockWindowUpdate(listview.handle);
    try
      ListView.Clear;
      for i := 1 to 15 do
      begin
        ListItem := ListView.Items.Add;
        ListItem.SubItems.Add(strVal +'_' +IntToStr(i));
        ListItem.SubItems.Add(strVal +'_' +IntToStr(i));
        ListItem.SubItems.Add(strVal +'_' +IntToStr(i));
        ListItem.SubItems.Add(strVal +'_' +IntToStr(i));
        ListItem.SubItems.Add(strVal +'_' +IntToStr(i));
     end;
    finally
      // for resizing the columns based on the text size
      FitToTextWidth(ListView);
      ListView.Items.EndUpdate;
      LockWindowUpdate(0);
    end;
  except
    on E: Exception do
      MessageDlg(PWideChar(E.Message), TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0);
  end;
end;

procedure TForm1.FitToTextWidth(LV: TListView);
var
i : integer;
begin
  // Set the Column width based on based on textwidth and headerwidth
  for i := 0 to LV.Columns.Count -1 do
  begin
    if LV.Columns.Items[i].Tag = 0 then
    begin
      LV.Columns.Items[i].Width := ColumnTextWidth;
      LV.Columns.Items[i].Width := ColumnHeaderWidth;
    end;
  end;
end;

procedure TForm1.LISTVIEWAdvancedCustomDrawItem(Sender: TCustomListView;
  Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage;
  var DefaultDraw: Boolean);
       Var
R   : TRect;
C : TCanvas;
B : TBitMap;
begin
  // Set C
  C := (Sender as TListView).Canvas;
  // Set R
  R := Item.DisplayRect(drLabel);
  B := TBitMap.Create;
  B.Transparent := True;
  B.TransparentColor := clWhite;
  // based on item index set the image and change the row color
  if odd(item.Index) = true then
  begin
     ImageList.GetBitmap(0,B);
     TJvListItem( Item ).Brush.Color := clWhite;
     TJvListItem( Item ).Font.Color  := clBlack;
  end
  else
  begin
    ImageList.GetBitmap(1,B);
    TJvListItem( Item ).Brush.Color := clMoneyGreen;
    TJvListItem( Item ).Font.Color  := clBlack;
  end;
  C.Draw(R.Left + 5 ,R.Top, B);
  B.Free;
end;

The above code works well with Delphi 2009... but currently trying migrating to XE4 in Win 7 environment.. my problem here is, it takes lot of time in loading the list view (When performing column resizing dynamically by calling FitToTextWidth method) .. but without this method it is working fine but without column resizing...
Comment: Why are you setting the `Width` twice? Why not three or four times? Can we have an SSCCE?
Comment: @bs2 - One wonders if there's a typo in your correction of your typo.
Comment: @bs2 - We don't know how you're drawing, we don't know how/where you're resizing, we don't know why you're setting a column width twice (first to something, then to something else). I'd be surprised if you'd get a useful suggestion with this much information.
Comment: *Any suggestion ..*? - Do not use custom draw since it's working fine that way. Otherwise, one thinks, maybe there's something going wrong while you're custom drawing.
Comment: Sorry it was a typo.. it was suppose to be                                                                  LV.Columns.Items[i].Width := ColumnTextWidth;
LV.Columns.Items[i].Width := ColumnHeaderWidth;
Comment: @ Sertack... If we comment the resize code, it is working as usual even with custom drawing... no issues other than column sizing... Please be informed that same code was working fine with Delphi 2009.. currently problem in migrating to Delphi XE4
Comment: Where's the SSCCE? Do you want help or not?
Comment: Try setting Column's Width to -1 and/or -2 and see how that affects it.
Comment: @lightBulb tried with that, the constant holds -1 /-2  ColumnHeaderWidth = LVSCW_AUTOSIZE_USEHEADER; //-2
  ColumnTextWidth = LVSCW_AUTOSIZE; //-1
Comment: @bs2 - I ran your test with 300 items (with XE2, jvcl 3.47). Few observations: (1) Your first call to set the column width is spurious, please remove it. (2)  I don't get any AV (if you're consistently getting an AV, might try locking the canvas). (3) The stock listview is somewhat faster when loading items. After loaded, while scrolling, the stock listview is *infinitely* faster then the jedi control. Change your calls like `TJvListItem(Item).Brush.Color:=clWhite;` to `C.Brush.Color:=clWhite;` and you can use the stock control.
Comment: @ Sertac... thanks for your update.. I will try with the feedback you have provided...(we are using XE4 with JVCL 3.48)..            just an update...the loading of data is better by using LockWindowUpdate on the listview... but scrolling takes lot of time.. I feel the main problem being resizing the column... is there any other way to resize the column.. performance of the loading and scrolling is good(with images or without) if we comment FitToTextWidth method...currently we may not be in position to replace the JVCL component at this stage..
Comment: @bs2 - See my answer for loading time. For scrolling time, I believe, the problem is with the design of the jedi listview. Either don't use it, or you need to search/fix/report what's wrong with it.
Comment: @bs2 - Does my answer help with the unusual load time?
Comment: No. Sertac. there seems some prblm with columnHeaderWitdh / ColumnTextWidth..it takes lot of time. we had come up with one workaround solution by resizing the width using AdvanceCustomDrawSubitem event...                                                          `C := (Sender as TListView).Canvas;
    if SubItem < Item.SubItems.Count then
    begin
       Width := C.TextWidth(Item.SubItems.Strings[SubItem]);
       if width <> 0 then
       begin
       if Width > (Sender as TListView).Column[SubItem + 1].Width then
       (Sender as TListView).Column[SubItem + 1].Width := -2;
      end;
  end`
Answer: When you set the width of a column to any one of the automatic constants, the control have to evaluate the length of the items/subitems to be able to calculate the necessary width. This takes time.
Also, when you set the width of a column, the VCL ListView updates all columns.
You have six columns, setting the width of any one of them involves 6 column updates, together with the spurious call in your FitToTextWidth procedure, your code is causing reading all items/subitems of a column 42 times (due to the code path in VCL: 1 time for 1st col, 2 times for 2nd -> 21 times for setting the width of 6 columns). Enclose your width setting in Begin/EndUpdate calls and remove the extra call, and you'll finish it in 6 rounds.
procedure TForm1.FitToTextWidth(LV: TListView);
var
i : integer;
begin
  // Set the Column width based on based on textwidth and headerwidth
  LV.Columns.BeginUpdate;
  try
    for i := 0 to LV.Columns.Count -1 do
    begin
      if LV.Columns.Items[i].Tag = 0 then
      begin
//        LV.Columns.Items[i].Width := ColumnTextWidth;
        LV.Columns.Items[i].Width := ColumnHeaderWidth;
      end;
    end;
  finally
    LV.Columns.EndUpdate;
  end;
end;

As I don't get any AV with your test case, I cannot comment on that.

ListView Column Resize in Delphi XE4


Best way to replace outdoor spigot

Question: I have to replace a 50 year old backyard bib and I don't know if it screws out or if the faucet was originally soldered on the the 1/2 " tube.
What is the best way to approach this?
Below is a picture of the exterior view. The inside view is just the tube going into a wood sill board.
I haven't done any soldering in 20 years and I'm wondering if there's now an easier way of doing this project.
Should I just cut a 12" length of the existing copper supply tube and solder a new 12" assembly (faucet & soldered 12" replacement) and sliding it through the existing exterior hole and then soldering them with a copper union?
Or is there an easier way to join copper these days (ferruled compression fittings, etc.)?
Comment: Provlima, you have asked [many questions](https://diy.stackexchange.com/users/69802/provlima?tab=questions) and have resolved none of them. Please take the [tour] and respond to your plethora of volunteer helpers with votes and accepts before posting more questions.
Answer: If you have access, I would put in a new frost free (the valve seat is at the end of a rod.

This particular one allows you to thread it on, or solder it on.  Lowes.
If you don't have a frost problem, this is still probably the easiest way to get the connection where you can work on it.
Note:  Whenever I have to repair something, I also put in a shut off valve, figuring that if I have to repair it once, I will likely have to again.

Best way to replace outdoor spigot


Update field in db avg value from other table

Question: UPDATE `users` u
   SET u.`user_rating`= (SELECT avg(rating)
                           FROM `rating` r
                          WHERE (r.prof_id=u.id AND r.is_prof_send=0)
                             OR (r.user_id=u.id AND r.is_prof_send=1))
                            AND u.id in(3)

Hello, I need to update rating in first table using avg value from second. I've added example, which return 1 as avg every time, but inner select returns correct value. What's wrong with it?
Comment: The published query is not syntactically correct - did you transcribe it accurately? Where for example is the table that is being aliased as e (as in e.condition1)? You can improve this question by publishing sample data an expected output.
Comment: I've replaced some conditions with condition+number, but it's good, and user ids - string like (1,2,3,4,5)
Comment: Please publish your actual non working query.
Comment: Added my actual query
Comment: at first glance, stating `AND u.id in(3)` after the second parentheses following `r.is_prof_send=1` is wrong.
Answer: For UPDATE or DELETE statements MySql does not allow references of the target table in subqueries like your code.
What you can use is joins.
Try this way (if this is the logic that you want to apply):
UPDATE `users` u
 INNER JOIN (
             SELECT u.id, avg(r.rating) avgrating
               FROM `users` u INNER JOIN `rating` r
                 ON (r.prof_id=u.id AND r.is_prof_send=0)
                 OR (r.user_id=u.id AND r.is_prof_send=1)
              WHERE u.id IN (3)
              GROUP BY u.id
             ) t ON t.id = u.id
   SET u.`user_rating`= t.avgrating

Answer: I think your u.id in (3) is misplaced.  Does this do what you want?
UPDATE users u
   SET u.user_rating = (SELECT AVG(rating)
                        FROM rating r
                        WHERE (r.prof_id = u.id AND r.is_prof_send = 0) OR
                              (r.user_id = u.id AND r.is_prof_send = 1)
                       )
   WHERE u.id IN (3);

Answer: SELECT returns a table, not a value.
Your query looks like ANSI SQL syntax.

Try adding the same name for avg(rating) as the field you want to update avg(rating) as rating
Pay attention that you placed and u.id in(user ids) after the SELECT, so you have (SELECT...) and u.id in(user ids) - It is boolean

UPDATE `users` u SET u.`rating`=
    (
    SELECT avg(rating) as rating
    FROM `ratings` r
    WHERE
        (r.prof_id=u.id and r.condition1)
        or (r.user_id=u.id and r.condition2)
        and u.id in(user ids)
    )


How to zoom jsPlumb diagram

Question: I'm trying to make available zooming on scroll. I have one #mainDiv with multiple .foo tables inside with jsPlumb endpoints. When the user scrolls, #mainDiv should remain the same size and tables should resize, which actually happens, but table's endpoints don't change their size and place. take a look at this jsFiddle:
https://jsfiddle.net/vaxobasilidze/cg3hkde7/9/
Fiddle is pretty big, but we only need the first javascript function. Drag few items to the right side, add new link and scroll. tables will change size, but endpoints remain the same. How can I fix this problem with endpoints?
Endpoints are not part of these tables, but they are part of jsPlumb library, which has setZoom() function for it's objects. This function does not work and I would like to know why. Connectors should also change their place.
Also, app must be working on touch devices as well. Does setZoom work on pinch zoom for touch devices and how can I implement this?
Comment: If you look at the rendered HTML, the zooming is being applied to the content table, and the endpoints are IMG elements outside of this table.
Comment: @Seano666 Indeed. Endpoints are not part of these tables, but they are part of jsPlumb library, which has setZoom() function for it's objects. This function does not work and I would like to know why. That's my question
Answer: Update:
So based on the question, we can just use the below CSS to either start the scaling from the left or the right depending on the elements position within the parent container.
A CSS change is needed in the parent container, as shown below
#mainDiv {
  display: inline-block;
  width: 82%;
  min-height: 100%;
  box-sizing: border-box;
  float: left;
  position:relative;
  margin: 0;
  padding: 3px;
}

Please checkout the JSFiddle for the solution!
JSFiddle Demo
Old Answer:
I am assuming that the zoom happening at the center is the problem, since we zoom from the middle the table always exceeds the container boundary. I would suggest adding the below CSS class, so that the endpoints are preserved.
.elementTable{
  transform-origin: 0% 0%;
}

Please find below a working JSFiddle with the implementation.
JSFiddle Demo
My assumption may be wrong, please explain what its missing and I'll try to solve it!
Comment: Thank you for your response. I want endpoints to be automatically scaled when table's scale changes (I can implement this manually), but endpoints should change their location, they should always stay on the borders of the table.
Comment: @VaxoBasilidze Made a change, please check it now!

How to zoom jsPlumb diagram


typescript: How would you return a new function with the same arguments but different types for those arguments?

Question: const stringToDate = ( x: string ) => new Date( x )
//    stringToDate: (x: string) => Date

type MapTupleValues<Tuple extends any[], NewValue> = {
    [ index in keyof Tuple ]: NewValue
}

type TestMappedTuple = MapTupleValues<[ a: Date, b: Date ], string>
//   TestMappedTuple = [a: string, b: string]
// works fine

function modifyFn<Fn extends ( ...args: Date[] ) => any> ( fn: Fn ) {
    return ( ...args: MapTupleValues<Parameters<Fn>, string> ): ReturnType<Fn> => {
        //   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error
        //   A rest parameter must be of an array type.

        return fn( ...args.map( x => stringToDate( x ) ) )
    }
}

const daysDifference = ( start: Date, end: Date ) => ( end.getTime() - start.getTime() ) / ( 1000 * 60 * 60 * 24 )
//    daysDifference: (start: Date, end: Date) => number

const modifiedDaysDifference = modifyFn( daysDifference )
//    modifiedDaysDifference: (start: string, end: string) => number

console.log( daysDifference( new Date( '2022-07-29' ), new Date( '2022-08-21' ) ) ) // 23
console.log( modifiedDaysDifference( '2022-07-29', '2022-08-21' ) ) // 23

this seems to be working, even though there is an error in modifyFn

how can I get rid of the error while still getting the same result?
Comment: Is your primary question "how can I get rid of the error while still getting the same result?" from the body of the post? Or is it "how do I return a new function with the same arguments..." from the title?  If it's the question in the body, then [this](https://tsplay.dev/NrnPlN) is how I'd approach it.  If it's the question in the title, then [this](https://tsplay.dev/N913oN) is.  Let me know which if any of those you'd like to see written up as an answer.
Answer: Thanks jcalz
Here's their answer:
const stringToDate = (x: string) => new Date(x)
//    stringToDate: (x: string) => Date

type MapTupleValues<T extends any[], V> = Extract<{
    [I in keyof T]: V
}, any[]>

type TestMappedTuple = MapTupleValues<[a: Date, b: Date], string>
//   TestMappedTuple = [a: string, b: string]
// works fine

function modifyFn<Fn extends (...args: Date[]) => any>(fn: Fn) {
    return (...args: MapTupleValues<Parameters<Fn>, string>): ReturnType<Fn> => {
        return fn(...args.map(x => stringToDate(x)))
    }
}

const daysDifference = (start: Date, end: Date) => (end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)
//    daysDifference: (start: Date, end: Date) => number

const modifiedDaysDifference = modifyFn(daysDifference)
//    modifiedDaysDifference: (start: string, end: string) => number

console.log(daysDifference(new Date('2022-07-29'), new Date('2022-08-21'))) // 23
console.log(modifiedDaysDifference('2022-07-29', '2022-08-21')) // 23

Comment: My intent was to write up my own answer with explanations, once you replied to my comment asking for clarification on your question.  Could you answer that and I could possibly post my own answer?  Or could you add context to this explaining what's going on?


Scroll only in one grid column with semanti-ui-react

Question: In this sandbox I have a two-column grid, that I want to make only the right column scrollable. This means the left column/menu should not go out of the screen by scrolling on the browser.
by giving position: fixed to the left column and marginLeft:somePixels to the right column it somehow works but if the content stacks on the smaller resolution, the layout gets destroyed.
How can I achieve this with semantic css classes or a custom style
Answer: You need to add to every element, from root to the container you want to scroll, the height: 100%.
Because it need to know what is the full dimension you need to scroll.
This is the sandbox fixed.
Comment: Thanks for the effort, But I do not see any fixes, still both columns scroll together.
Comment: @Amir-Mousavi try it now.


Any driver for Lexmark Z845?

Question: Is there a driver for Lexmark Z845 or something compatible with it?
Answer: Officially there is no support as mentioned here.
It is a windows only printer.

Any driver for Lexmark Z845?


How to use numpy.savetxt with a structured array that contains an array

Question: Say I have a structured array as follows:
a = np.zeros(10,dtype=[('label1',np.int32, 4), ('label2', np.float_)])

And I try to save this as a csv file:
np.savetxt('output.csv', a, fmt='%d,%d,%d,%d,%f')

Python will generate this error:
ValueError: fmt has wrong number of % formats:  %d,%d,%d,%d,%f

I haven't been able to create a fmt string that would suit my output. %s won't work for me here as I need the ability specify the format of the float.
Is it possible to create a csv file from this type of structured array?
Answer: In essence what savetxt does is:
for row in arr:
    print(fmt % tuple(row))

So the fmt has to work with a row, or in this case, an element of your array.
In [330]: a = np.zeros(10,dtype=[('label1',np.int32, 4), ('label2', np.float_)])
     ...:
In [331]: a
Out[331]:
array([([0, 0, 0, 0],  0.), ([0, 0, 0, 0],  0.), ([0, 0, 0, 0],  0.),
       ([0, 0, 0, 0],  0.), ([0, 0, 0, 0],  0.), ([0, 0, 0, 0],  0.),
       ([0, 0, 0, 0],  0.), ([0, 0, 0, 0],  0.), ([0, 0, 0, 0],  0.),
       ([0, 0, 0, 0],  0.)],
      dtype=[('label1', '<i4', (4,)), ('label2', '<f8')])
In [332]: a[0]
Out[332]: ([0, 0, 0, 0],  0.)
In [333]: tuple(a[0])
Out[333]: (array([0, 0, 0, 0]), 0.0)

Nesting the 4 ints in label1 makes it difficult to come up with a format that works.  It's a matter of how to Python '%' formatting.
In [334]: '%s, %f'%_
Out[334]: '[0 0 0 0], 0.000000'

If a was 5 fields it would be easier
In [335]: a = np.zeros(10,dtype='i,i,i,i,f')
In [336]: a
Out[336]:
array([(0, 0, 0, 0,  0.),....
       (0, 0, 0, 0,  0.)],
      dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4'), ('f3', '<i4'), ('f4', '<f4')])
In [337]: tuple(a[0])
Out[337]: (0, 0, 0, 0, 0.0)
In [338]: '%d, %d, %d, %d, %f'%tuple(a[0])
Out[338]: '0, 0, 0, 0, 0.000000'

I think you need to either 'flatten' the structure of your array, or write a custom savetxt.  As I indicated savetxt is not fancy.  If you can print the array element by element in the format you want, you can write that format to a file.
Comment: Thanks for the response - that makes a lot of sense. It certainly would be easier to stop using the nested array, but my array is more complicated than the example that I've given - it contains many fields, several of which contain nested ints. Would it make sense in this case to abandon the structured array and use a normal array - keeping track of the columns using some other method?
Comment: Depends on what else you are doing with the array(s).  In SO questions, structured arrays are created most often by `genfromtxt` reading a `csv` with a mix of strings and numbers.  It can even create nested ones like this, though I haven't seen that very often.  But for calculations multiple arrays are usually just as useful as structured ones.  You can't do math across fields.