text:
Q: How can I exactly position an image\table in a document? I am trying to insert an image in my LaTex document using either straight ahead the \includegraphics argument or the figure environment. One problem however that I am facing is that I cannot position exactly my image in the document. From what I see using \begin{center} for example sets the image in the center, however I am looking for more precision. Is there any way to exactly determine the position of my image (Determine for example the distance from say the left border of the page)? The same question applies for tables as well. Any help is appreciated.

A: an image (or table) is positioned exactly like a letter:
  \noindent\hspace{3.1cm}\includegraphics{..}

will be 31mm from the left margin


text:
Q: VSCode How to make Terminal RUN THE CODE IN MY PROGRAM A few days ago, when I typed the above command in the Terminal

the Terminal should print out the statement: "Print this test statement"
Now for some reason, when I type that exact same command, it is now giving me the following result:

I tried this with multiple py files and it seems that when I type in the file name into the Terminal, what VSCode does is OPEN/REOPEN the file in the Editor, not run the code (print the test statement) in the Terminal like it did before.
By the way, it's not an apostrophe fault, tried that. This is really frustrating as a few days ago, when I typed in 'hello.py' into the terminal, it would print out the test statement. How do I fix this?

A: Just use the python prefix like this:
python hello.py

A: Follow these instructions:
https://geek-university.com/python/add-python-to-the-windows-path/. Then restart Visual Code
It should work now. But now, you'll have to type:
python program.py

instead of just:
program.py

in the Terminal.

redpajama_set_name: RedPajamaStackExchange


text:
Q: asp.net mvc application down I have a Live website called API Web, build with ASP.NET MVC 4.
This application is to provide a JavaScript files for other websites.
I have 20 websites requesting a JavaScript to it.
But, sometimes this API Web is going down and I have a trouble to make the application live again.
I don't know why this happen, and how can I solve this issue?
EDIT
This is the controller, if the website requesting a path say http://api.example.com/get/js/folderA?js=jquery.js
the application will return a javascript content.
but, the requesting website will load slower. and I think if the API Web had too much request, it will going down (bottleneck issue).
public ActionResult js(string id, string js) {
            string fileLocation = Server.MapPath("~/content/" + id + "/js/" + CryptKeys.Decrypt(js) + "");

            string contentType = "text/javascript";
            var file = System.IO.File.Open(fileLocation, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            var stream = (Stream)(file);

            return new FileStreamResult(stream, contentType);

        }

A: There is a chance that you are not closing the filestream opened by System.IO.File.Open class which may be leading to next call to return the same file in throwing an exception. And because the exception is not handled, this may eventually be leading to site being shutting down.
Did you check for error logs in event viewer?
Based on your inputs below, could you try this piece of code? Notice the using block that I have added
public ActionResult js(string id, string js) {
        string fileLocation = Server.MapPath("~/content/" + id + "/js/" + CryptKeys.Decrypt(js) + "");

        string contentType = "text/javascript";
        using(var file = System.IO.File.Open(fileLocation, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            var stream = (Stream)(file);

            return new FileStreamResult(stream, contentType);
        }

    }


text:
Q: SWT Label/Button not showing up in composite I'm trying to add a Label or a Button to a child Composite but it's not working as expected.
display = Display.getCurrent();
parentShell = display.getActiveShell();
shell = new Shell(parentShell, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
shell.setText(title);

GridLayout layout = new GridLayout(1, false);
shell.setLayout(layout);

// Content composite
contentComposite = new Composite(shell, SWT.BORDER);
GridLayout contentLayout = new GridLayout(2, true);
contentComposite.setLayout(contentLayout);
contentComposite.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));

// Default Version
defaultVersionComposite = new Composite(contentComposite, SWT.BORDER);
defaultVersionComposite.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));

// Versions in Tabs
versionComposite = new Composite(contentComposite, SWT.BORDER);
versionComposite.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
Button button = new Button(versionComposite, SWT.PUSH);
button.setText("Test");

Right now it looks like this.

Any idea what's going on there?
Thanks!

A: Your two sub-composites don't have Layouts assigned to them. Just add these two lines:
defaultVersionComposite.setLayout(new GridLayout());
versionComposite.setLayout(new GridLayout());


text:
Q: UIImage to CIImage to UIImage results in pngData returning nil on iOS 12 I have an UIImage that I snap from the camera.
I want to do some image manipulations so I transform it to a CIImage.
CIImage *ciImage = [CIImage imageWithCGImage:snappedImage.CGImage];
Next I do my thing, and then transform it back to a UIImage:
UIImage *image = [UIImage imageWithCIImage:ciImage];
If now I want to transform this to data to save it into Core Data for example:
NSData *data = UIImagePNGRepresentation(image);
the data ends up being nil on iOS 12. (works on iOS 13, same thing happens with if I try to use the UIImageJPEGRepresentation)
Any idea why and how to fix this?

A: I see a lot of problems emerging when using the [UIImage imageWithCIImage:] API. You see, your CIImage is not actually rendered when you call this method. The resulting UIImage is still just a "recipe" for how to create the result. It's up to the user of the UIImage to know that and trigger the rendering if needed. UIImageViews seem to know that, but I saw a lot of inconsistencies across other APIs.
What you can do instead is to use a CIContext and perform the rendering yourself explicitly:
// ideally you create this context once and re-use it because it's an expensive object
CIContext* context = [CIContext context];

CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);

NSData* data = [context PNGRepresentationOfImage:ciImage format:kCIFormatBGRA8 colorSpace:colorSpace options:nil];

CGColorSpaceRelease(colorSpace);

This should work consistently in any iOS version.


text:
Q: Improving our javascript error reporting So right now we have some generic code to report errors either from our code or third party code.  Our project is a JQM/Phonegap project for iOS.  What is happening is we pretty much always get the same useless error... TypeError: 'undefined' is not a function... with no line number or other helpful information.  Is there a way I could change the code to maybe get WHAT is undefined or WHERE it is?
window.onerror = function myErrorHandler(errorMsg, url, lineNumber) {
    //Handle errors not in a jquery event handler
    //DebugMessage(errorMSg + " "+ url + " " + lineNumber);
    var ex = new Error(errorMsg, url, lineNumber);
    HandleError(ex, "window.onerror");
        //HandleError sends the error object to
        //a webservice to log the error.
    return true;
};

Any tips on debugging javascript errors would help as well.

A: In recent months, browsers have extended the signature of window.onerror to provide more information.
window.onerror = function(msg, file, line, col, error) {

  // backwards compat
  if (!error) {
    error = new Error(msg);
  }

  // send error to your logger

}

This should give you a lot more information. But there are still things where you need better context. You should check out some third-party tools for this like TrackJS that automatically give you this, plus extra information on how the error occurred.
Disclaimer: I am one of the original authors of TrackJS, so I know a bunch about JavaScript errors :)

A: Have you heard of Ripple? It is a mobile emulator for Chrome designed for testing PhoneGap applications.
That might help you find your errors before you debug on the devices.


text:
Q: SyntaxError: Invalid Syntax Estava criando uma ferramenta em Python, porém quando fui rodar ele fica dando esse erro. Trecho do código:
while True:
        opcao = int(input("Digite a opcao desejada: ")
        if opcao == 1:
            arquivo = open("textos.txt", 'w')

Quando eu rodo aparece isso:

A: Faltou fechar um parentese, veja:
while True:
    opcao = int(input("Digite a opcao desejada: "))
    if opcao == 1:
        arquivo = open("textos.txt", 'w')


text:
Q: I keep getting Segmentation Fault when i try to add a new WaitingRoom in my list So basically what my code does is creates a WaitingRoom as the HEAD of a list and then it adds students in it ordered alphabetically, this works just fine, but when i try to add another watiningroom it gives me seg fault at the insertinRoom function at firts if.
This is my code, but when i run it with only one WaitingRoom created it works perfectly but if i add another one then it gives me segfault.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct studenti{
    char name[100];
    struct studenti* next;
}studenti;

typedef struct WaitingRoom{
    int ID;
    char parola[100];
    struct WaitingRoom* next;
    struct studenti* next_S;
}WaitingRoom;

studenti* CreateStudent(char* name)
{
    studenti* S = (studenti*)malloc(sizeof(studenti));
    strcpy(S->name,name);
    S->next = NULL;

    return S;
}

WaitingRoom* createWaitingRoom(int ID, char* parola){
    WaitingRoom* WR = (WaitingRoom*)malloc(sizeof(WaitingRoom));
    strcpy(WR->parola,parola);
    WR->ID = ID;
    WR->next = NULL;

    return WR;
}

void insertinRoom(WaitingRoom* WR,char* name){
    studenti* S;
    S = CreateStudent(name);

    if(WR->next_S == NULL || strcmp(WR->next_S->name,name)>0){
    S->next=WR->next_S;
    WR->next_S = S;
    }
    else{
        studenti* current  = WR->next_S;
        while(current->next !=NULL && strcmp(current->next->name,name)>0)
        {
            current=current->next;
        }
        S->next = current->next;
        current->next = S;

    }
}

void printWaitingRoom(WaitingRoom* WR){
    studenti* current = WR->next_S;
    printf("Waiting Romom este %d cu parola %s\n",WR->ID,WR->parola);
    while(current!=NULL){
        printf("%s\n",current->name);
        current = current->next;
    }

}

void printall(WaitingRoom* WR){
    WaitingRoom* current = WR;
    while(current!=NULL){
        printWaitingRoom(current);
        current = current->next;
    }
}
int main()
{
    WaitingRoom* WR1 = createWaitingRoom(6969,"Muiedinamo");
    insertinRoom(WR1,"BOOm1");
    insertinRoom(WR1,"AOOm2");
    insertinRoom(WR1,"DOOm3");
    insertinRoom(WR1,"COOm4");

/*
    WaitingRoom* WR2 = createWaitingRoom(1234,"AStae ");
    insertinRoom(WR2,"B1");
    insertinRoom(WR2,"AO2");
    insertinRoom(WR2,"D3");
    insertinRoom(WR2,"C4");

    WR1->next = WR2;
    */
    printWaitingRoom(WR1);
    //printall(WR1);

    return 0;
}

I was expecting to created my WaitingRoom and then connecting the waitingrooms and printing them 1 by 1 and the the hole list with "PrintAll" function.


text:
Q: Iimport data in Matlab from Excel with string label I am new in Matlab and I want to import an Excel file in matrix format. My columns are all numerical except the last column, which is a string and it's my labels. When I import my data set Matlab says that label column is unimportable and replaces it to zero! How can I do about it?

A: Please use following code:
[num, txt, raw] = xlsread(excelpath, sheetname, A00:C20)

Excep path, sheetname and A00:C20 are arbitrary. You can find table containing all items in specified cells in raw variable. num contains numeric values and txt contains string values.


text: Q: PivotalTracker and GitHub integration with Python 2.7 I have been looking around for a PivotalTracker to GitHub integration and have found ways to update PT based on changes made to the GitHub (commits, etc). I am trying to go the other direction and update the GitHub Issue Tracker based on changes made to the PT project/epic/story. Specifically I want to close a bug if it has been resolved which can be observed by looking at the updated PT project/epic/story. I would like to code this script in Python 2.7. Any suggestions or guidance is appreciated, thanks!


text:
Q: Overfull hbox with parindent, tcolorbox and witharrows As per the title, I get an overfull hbox whenever I utilize a combination of a tcolorbox with a non-zero parindent and a DispWithArrows environment. I've not tried particularly much as I don't see what could be there to change/influence as the problem persists even with the minimal combination of the three items mentioned above.
Here's a MWE:
\documentclass{minimal}

\overfullrule=1mm

\usepackage{witharrows,tcolorbox}

\begin{document}

\begin{tcolorbox}[before upper*={\setlength{\parindent}{15pt}}]
     \begin{DispWithArrows*}
         & 2 + 2 \\ {}={} & 4
     \end{DispWithArrows*}
\end{tcolorbox}

\end{document}

Thanks in advance for any help.

A: Remark:
witharrows v2.6d 2022-01-01 (see diff in texlive's svn repo) has fixed this issue, so you don't need the following \AtBeginEnvironment patch.
Original Answer:
Prepending a \noindent to \begin{DispWithArrows*} does the trick. You can make it automatically inserted by using
\AtBeginEnvironment{DispWithArrows*}{\ifvmode\noindent\fi}

Full example
\documentclass{article}
\usepackage{witharrows,tcolorbox}

\AtBeginEnvironment{DispWithArrows*}{\ifvmode\noindent\fi}
\overfullrule=1mm

\begin{document}
\begin{tcolorbox}[before upper*={\setlength{\parindent}{15pt}}]
     \noindent\begin{DispWithArrows*}
         & 2 + 2 \\ {}={} & 4
     \end{DispWithArrows*}
\end{tcolorbox}
\end{document}

Btw, it's reproducible with DispWithArrows(*) + minipage but not with align + minipage, so there's some improvements witharrows can do. Perhaps in
% witharrows.sty v2.6c 2021/03/04
\NewDocumentEnvironment { DispWithArrows } { ! d < > ! O { } }
  {
    % ...
    % lines 1093--1101
    \bool_if:NTF \l__witharrows_in_label_or_minipage_bool
      { \c_math_toggle_token }
      {
        \if_mode_vertical:
        \nointerlineskip % <<< possible position
        \hbox_to_wd:nn { .6 \linewidth } { }
        \fi:
        \c_math_toggle_token \c_math_toggle_token
      }
    % ...
  }

\documentclass{article}
\usepackage{amsmath}
\usepackage{witharrows}

\overfullrule=1mm

\begin{document}
\verb|minipage| starts with a \verb|DispWithArrows(*)|:

\noindent\fbox{%
\begin{minipage}{\dimexpr\linewidth-2\fboxsep-2\fboxrule}
  \setlength{\parindent}{15pt}
  \begin{DispWithArrows}
    a + b = c
  \end{DispWithArrows}
\end{minipage}%
}
\bigskip

\verb|minipage| starts with an \verb|align(*)|:

\noindent\fbox{%
\begin{minipage}{\dimexpr\linewidth-2\fboxsep-2\fboxrule}
  \setlength{\parindent}{15pt}
  \begin{align}
    a + b = c
  \end{align}
\end{minipage}%
}
\end{document}

For the extra vertical space before align, see How to make equation spacing consistent in minipage regardless of horizontal alignment.


text:
Q: TPL Parallel For Loop error I'm getting a "one or more errors occurred" exception in my parallel.for loop:
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken            cancellationToken)
at System.Threading.Tasks.Task.Wait()
at System.Threading.Tasks.Parallel.ForWorker[TLocal](Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Func`4 bodyWithLocal, Func`1 localInit, Action`1 localFinally)
at System.Threading.Tasks.Parallel.For(Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body)
at StaticClassLibrary.BLL.StaticClass.StatiMethod(String strExt, Object wTable, Object job, String BSPConnectionString) in c:\Users\FredWAD\Documents\Visual Studio 2010\Projects\PayrollCenterLibrary\BLL\ContributionFileManager.cs:line 218
   at myapp.staticlibrary.staticmethod(String str1, String str2)

The app takes a collection of structs, each object containing metadata, and inserts them into a database.
The offending code is as follows:
Parallel.For(0, recordCnt, pOptions, d =>
               {
                   //flds = wTable.records[d].fields;
                   ssn = wTable.records[d].fields[fieldIndex].Value;
                   //rowId = wTable.records[d].fields[fieldIndex].rowId;
                   currentPerson = PersontManager.GetPerson(string1, string2);
                   hasContributions = WorkTableManager.RowHasContributionsNEW(List<string> lst, wTable.records[d]);
                   LoadRecordParallel(hasLoan, hasScratchpad, fieldIndex, wTable.records[d], object, string, string);
               }
           );

wTable = the collection object.
records = a List of structs containing metadata
fields = a struct within each record. each record contains a list of these.
This is essentially a table, with a struct for a row (which also contains some metadata about each row), and structs for cells. This error appears to be occurring at random. What am I doing wrong here?

A: You will need to look at the InnerExceptions property on the AggregateException.  This is the default behaviour for TPL as multiple threads could throw exceptions at the same time.
See http://msdn.microsoft.com/en-us/library/system.aggregateexception.aspx for more information.
My guess is that you have some type of resource that is not thread-safe; when parallel threads are accessing it, the resource gets into a race condition with another thread, resulting in your exception.  The first task is to figure out which line of your parallel query is causing the problem, the go into that.  It likely has something to do with the database if your database level row locks are not adequate.

A: One way to handle this is to put a try catch block within your Parallel loop.  Handle the exception if you can inside the loop, so it does not break out with an AggregateException.


text:
Q: How do I align a button to the right? How would I align a button to the right?
I've tried text-align: right; and align-content: right;
I would also like the button have display: flex;

#hideShow {
  display: flex;
  text-align: right;
  align-content: right;
}
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<button class="flex" id="hideShow" onclick="hideBtTS()">Hide</button>

A: You should have flex on your parent div. Also, you can try using
{ display: flex; justify-content: flex-end; }
justify-content will align your button with the end of your parent div (right side of the window).

A: You can use margin-left: auto, but you have to display it as a block as follows -
#hideShow {
display: block;
margin-left: auto;
}

If you want it at centre then also add margin-right: auto as follows -
#hideShow {
display: block;
margin-left: auto;
margin-right: auto;
}

A: Here I am assuming that your button container is 100% width.
CSS:
.btn-container {
    display:flex;
    justify-content:flex-end
}
//#hideShow {
//    display: flex;
//    text-align: right;
//    align-content: right;
//}

HTML:

<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>

    <form action="../index.html" id="BtTS">
        <input type="submit" value="<--- Back to Title Screen" />
    </form>

        <button class="flex" id="hideShow" onclick="hideBtTS()">Hide</button>

check the result here

A: You are doing changes on the text inside the button.
You have to put "text-align: right" to the container not the button

#right {
  text-align: right;
}

A: Use:
.btn-container {
   justify-content: flex-end;
   position: relative;
   bottom: 38px;
}

Adjust bottom: ; to whatever you need.
This worked for me.

A: try this
.flex{
 display: flex;
 justify-content: space-between!important;
}


text:
Q: How to add UIBarButton Programmatically to Programmatically created NavBar? I am changing my view controller using the following code:
 [self.slidingViewController performSegueWithIdentifier:@"FindScoresController" sender:self.slidingViewController];

The segue is PUSH
Now I want to add UINavigationBar Programatically. The code i am using for it is:
// Not required if viewController is pushed from previous viewController
UINavigationBar *navbar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
UIColor *barColor = [[UIColor alloc]initWithRed:82/255.0f green:167/255.0f blue:192/255.0f alpha:1.0f];

if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
    // iOS 6.1 or earlier
    navbar.tintColor = barColor;
} else {
    // iOS 7.0 or later
    navbar.barTintColor = barColor;

   navbar.translucent = NO;
}
[self.view addSubview:navbar];

It adds nav bar successfully.
Now I want to add left and right custom buttons with custom Image.
But I am unable to do so.
Code i am using to add right UIBarButton item:
 UIBarButtonItem *flipButton = [[UIBarButtonItem alloc]
                               initWithTitle:@"Flip"
                               style:UIBarButtonItemStyleBordered
                               target:self
                               action:@selector(flipView:)];
self.navigationItem.rightBarButtonItem = flipButton;

But it doesn't show any effect.
I also tried this code:
UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yourimage2.jpg"]]];
self.navigationItem.rightBarButtonItem = item;

All these code i am writing in ViewDidLoad method.


text:
Q: how disable use swap partition by processes , only if its really need My embedded system has 2 GB RAM and 100 MB swap partition.
I recognize, after continues monitoring that average memory usage of RAM is ~50 %.
For some reason system start use SWAP memory and use almost 40 % of it (40 MB).
I want prevent such thing because my device flash has a big problem with number of writes and I need it for ~10 years of use.
After run these set of commands I get to list of processes that use SWAP :
for file in /proc/*/status ; do awk '/VmSwap|Name/{printf $2 " " $3}END{ print ""}' $file; done | sort -k 2 -n -r | less

My  system file /etc/sysctl.conf confiured with parameter : vm.swappiness=1 , so according articles I read it should use SWAP only if it really need.
(I investigated the results with vm.sappiness=0, but didn't have results yet.)
I know that there is a way to prevent from specific processes use swap, but what is a correct one?

A: You can set swappiness per process with cgroups
echo 0 > /sys/fs/cgroup/<your custom group>/memory.swappiness

Anyway my advice is to use zram for compressed swapping in ram.

A: I test on two systems , where I detect previously use of 40% of SWAP option of :
vm.swappiness=0

This option really helped . I didn't see any use of swap for last 4 days


text:
Q: Скрипт не запускает браузер при загрузке системы Есть bash скрипт на raspberry pi, который должен запускать окно браузера и скрипт:
#!/bin/bash
chromium-browser --start-fullscreen <url> &
python3 /home/pi/main.py &

У него стоят права на выполнение. Если запускать его просто в системе, то все работает, открывается окно браузера и запускается python скрипт. Я добавил этот файл в rc.local. Но при запуске системы запускается только python скрипт, а браузер - нет. В чем может быть проблема?

A: Проблему именно этого скрипта я не решил, но нашел другое решение:
$ sudo touch ~/.config/autostart/chromium.desktop
$ sudo nano ~/.config/autostart/chromium.desktop

Добавить в файл строки:
[Desktop Entry]
Encoding=UTF-8
Name=Connect
Comment=Checks internet connectivity
Exec=/usr/bin/chromium-browser -incognito --noerrdialogs --kiosk <url>

Источник


text:
Q: Why uses Scapy different methods to distinguish L2 and L3 packets? Is there any rationale behind the choice to use distinct methods for sending packets at L2 and L3 in Scapy? Could Scapy not just check if the packet being sent is L2 or higher?

A: If Scapy were to detect whether the passed packet was L2 or L3, it would mean it has to hardcode a list of layers that are considered "Layer 3" and "Layer 2".
If you make a custom layer 3, it wouldn't know in what category it falls, thus it leaves you the choice.
Also that's historical, dates back from 2008, you can't break it :-)


text:
Q: How do you properly write a question that contains follow-up questions? For example if you were to write a question like: "Is this something that you would be interested in, and if so: when are you be available?"
How do you structure the sentence with regards to question marks and punctuation?

A: "Is this something that you would be interested in, and if so, when are you be [sic] available?"
The correct punctuation to use is a comma after "if so". The general structure is-

[question], and if so, [other question]?


text:
Q: Calling Method in Operator Method Weird Behavior IntBuf.h
#ifndef CDEVTOOLS_INTBUF_H
#define CDEVTOOLS_INTBUF_H

#include <string>
#include "ArrayTools.h"

class IntBuf {
private:
    int* values_;
    int capacity_;
    int length_ = 0;

public:
    IntBuf(int capacity);

    void Add(int val);

    std::string ToString();
};

void operator+=(IntBuf buf, int val);

#endif //CDEVTOOLS_INTBUF_H

IntBuf.cpp
#include <iostream>
#include <cassert>
#include <sstream>
#include "IntBuf.h"

IntBuf::IntBuf(int capacity) {
    this->values_ = new int[capacity];
    this->capacity_ = capacity;
}

void IntBuf::Add(int val) {
    printf("adding %d, current length: %d\n", val, length_);

    assert(length_ < capacity_);
    values_[length_++] = val;

    printf("added %d, new length: %d\n", val, length_);
    std::flush(std::cout);
}

std::string IntBuf::ToString() {
    return ArrayToString<int>(values_, length_);
}

void operator+=(IntBuf buf, int val) {
    buf.Add(val);
}

I don't understand why the 2 following implementations output different things
Implementation 1 - Using IntBuf::Add
#include "IntBuf.h"

int main() {
    IntBuf buf = *new IntBuf(10);
    buf.Add(34);
    buf.Add(23);
    printf("%s\n", buf.ToString().c_str());
}

output
adding 34, current length: 0
added 34, new length: 1
adding 23, current length: 1
added 23, new length: 2
[34, 23]

Implementation 2 - Using operator+=(IntBuf buf, int val)
#include "IntBuf.h"

int main() {
    IntBuf buf = *new IntBuf(10);
    buf += 34;
    buf += 23;
    printf("%s\n", buf.ToString().c_str());
}

output
adding 34, current length: 0
added 34, new length: 1
adding 23, current length: 0
added 23, new length: 1
[]

ArrayTools implementation:
#include <string>
#include <sstream>

template<typename Type>
std::string ArrayToString(Type* values, int length) {
    std::stringstream ss;
    ss << "[";
    int imax = length-1;
    for(int i = 0; i < imax; i++) {
        ss << values[i] << ", ";
    }
    if(imax >= 0) ss << values[imax];
    ss << "]";
    return ss.str();
}

I'm confused as to how using the operator overloaded function could be different then calling IntBuf::Add, since the overloaded operator should also use IntBuf::Add


text:
Q: How to route all packets through Windows web server 2008? I have the following sitiuation I have dedicated server with IP 85.25.148.23/255.255.255.0 GW 85.25.148.1 running windows web server 2008
I installed VMware on it having linux centos OS I found a limitition on my datacenter that it only accepts traffic from the dedicated server MAC address
now I need to get over this by routing to 85.25.250.21/255.255.255.192 through the 85.25.148.23, so the MAC still the same as dedicated server
I did this before using Linux dedicated, now I need to do the same with windows WEB server 2008.

A: It would depend on how you are using this the CentOS VM if this will work for you are not. But the simplest solution would just be to tell the VMWare VM to use "NAT (Network address translation)" and then all requests coming from that that machine would like they are coming from the .23 machines IP and MAC address (I believe anyways -- would be strange if it wasn't IMO).
Less simple, but still possible would be to configure your Web server as a router. With this, you would use the "Routing and Remote Access Services".
Lastly, I imagine the reason they have this policy is that they want you to be using a router / firewall device as the gateway for all of your servers and services. IF you can't convince them otherwise, your best bet is probably just to give in an set up something like pfsense as a router or get a basic Cisco router or ASA device.


text:
Q: Как внедрить установку Mssql в внутрь Msi расширения InstallerProjects? Есть проект сделанный через расширение VS InstallerProjects, в внутрь которого вставляется установщик Mssql. Однако установщик ловит ошибку, что у него нету доступа к отладке:
The account that is running SQL Server Setup does not have one or all of the following rights: the right to back up files and directories, the right to manage auditing and the security log and the right to debug programs. To continue, use an account with both of these rights.
И не важно через CustomAction или напрямик подзывая данный файл, как действие.
В инете советы есть, но они требуют прямого вмешательства в пк юзера. Идей к сожалению уже нет, буду рад предложениям.
Есть ли вообще возможность сделать в данном расширении ?


text:
Q: Get Berkshelf to resolve cookbook in same repository I have a single chef-repo with 2 cookbooks, say cookbook-A and cookbook-B, and a local Chef server.
cookbook-A depends on cookbooks from Chef Supermarket, berks install and berks upload run happily and the cookbook is now on the server.
E.g.
chef-repo
    /cookbooks
        /cookbook-A
            /cookbook-B

cookbook-B depends on more things from supermarket plus cookbook-A. When running berks install it cannot resolve cookbook-A
How can I tell it to resolve this one cookbook from the same directory?

A: Add this in your Berksfile:
cookbook 'cookbook-A', path: '../cookbook-A'


text:
Q: How to securely save data in a database for a webApp I'm developing a web app with Nodejs, express and MongoDB. In the app, each user can create an account and I have to save the data that the user gives to the app inside the MongoDB database.
I'm using some packages like mongoose for interact with the database, and passport, passport-local, passport-local-mongoose to facilitate the account creation process, but I don't know if this is the best way to do this.
I'm new to this world and I don't know how to achieve a good level of security, thanks to the passport packages i can easily manage the creation of new users,  with an encrypted password in the user object,  and their authentication but is it enough?
Here is my user schema
const passportLocalMongoose = require('passport-local-mongoose'),
      mongoose              = require('mongoose');

// CREATION USER SCHEMA
const userSchema = new mongoose.Schema({
    username: String,
    password: String,
    email: String,
    isAdmin: {type: Boolean, default: false}
});
userSchema.plugin(passportLocalMongoose);

//EXPORT FROM USER SCHEMA
module.exports = mongoose.model('User', userSchema, 'users');

I know that this topic is a very broad topic to talk about, but I would like some tips that can be useful to improve my approach in this area.


text:
Q: Rediculous explorer.exe RAM usage: >18GB with >600'000 handles For a while now I have the problem that explorer.exe sometimes starts using ridiculous amounts of memory. If I wait long enough it can sometimes increase up to 18GB (I have 8GB of RAM total but it uses mostly swap space). I'm using Windows 10 Home 1909 (build 18363.836).
I noticed using Process Hacker that explorer.exe opens literally hundreds of thousands of handles to the following registry key:
Computer\HKEY_CLASSES_ROOT\CLSID\{DFFACDC5-679F-4156-8947-C5C76BC0B67F}\Instance

(Peak today was over 628'000 handles total, almost all to this key, growing in the end with ~100 per second, adding up to almost 13GB until I decided to restart it.)
According to https://winaero.com/blog/clsid-guid-shell-list-windows-10/ this is the CLSID for the "delegate folder that appears in Users Files Folder", but I'm not sure what that means.
The contents are a single string with key CLSID and value {0E5AAE11-A475-4c5b-AB00-C66DE400274E}, which according to the same website is the "Shell File System Folder". (I don't really know how the CLSID system works.)
At first I presumed that it was probably some shell extension that I have installed, but I've already tried to disable most (if not all) of them and I still got a notification that explorer was using multiple GBs of RAM (in the meantime I wrote a simple program that checks for this). (I guess I'll continue trying and keep this updated if I do make a breakthrough.) Or could it be a problem that I gave icons to some folders?
Does anyone know what the cause might be? Or what I could do to further investigate the issue? If some specific useful info is missing, let me know!
I'm not sure if this question has a higher chance of being answered on support.microsoft.com, but I'll try to ask it there if I don't get an answer here.

A: I've had this exact issue since Windows 8.1 and it just got worse in Windows 10 (explorer crashing every hour due to using too much memory). Disabled all shell extensions, disable all visual effects, even disabled thumbnails to no avail.
Your comment contained enough clues for me to finally track down the issue, so thank you!
The problem was that I added my home folder to "This PC" and it caused a slow but seemingly exponential growth of DFFACDC5-679F-4156-8947-C5C76BC0B67F handles. Only the home folder is causing the issue, other custom directories are fine. I'm now using Quick Access instead.


text:
Q: Can an array be a top level JSON object? (in Objective C, Stig Brautaset's library) I'm writing an Objective C / iOS module to parse text files into JSON dictionaries, using Stig Brautaset's JSON library.
Is there a simple way to parse a single JSON file into an array of dictionary objects, or do I have to create a single dictionary object and pull the different objects out of it?
As background I'm currently using multiple files, one per object.  My JSON files look something like this:

{
 "colorname": "red",
 "foos": [
   {
    "type": "cherry",
    "category": "fruit"
   },
   {
    "type": "redvines",
    "category": "bar"
   }
 ]
}

{
 "colorname": "green",
 "foos": [...]
}

{
 "colorname": "blue",
 "foos": [...]
}

etc.
My parsing function goes like this:
NSMutableArray *fooColors = [[[NSMutableArray alloc] init] autorelease]

for (NSString *thisFile in fileList) {
  NSString *entireFile = [NSString stringWithContentsOfFile:thisFile
                              encoding:NSUTF8StringEncoding
                              error:nil];
  NSDictionary *fooList = (NSDictionary*)[entireFile JSONValue];
  [fooColors addObject:dataObject];
}

But I'd rather have all the JSON objects in a single file.  Would I do it all in a single top level dictionary like this?

{
 "colors": [
   {
    "colorname": "red",
    "foos": [
      {
       "type": "cherry",
       "category": "fruit"
      },
      {...}
    ]
   },
   {"colorname": "green",
    "foos":[...]
   },
   {"colorname": "blue",
    "foos":[...]
   },
   *etc.*
 ]
}

Is there a simpler way to dispense with the first two and last two lines of the JSON text and read it in as an array of dictionary objects?  If so, what would the parsing function look like?
Apologies in advance if this is a newbie question.

A: The outermost object in JSON can be an array. It doesn't have to be a record/dictionary. SBJSON will return an NSArray to you.
[
   {
    "colorname": "red",
    "foos": [
      {
       "type": "cherry",
       "category": "fruit"
      },
      {...}
    ]
   },
   {"colorname": "green",
    "foos":[...]
   },
   {"colorname": "blue",
    "foos":[...]
   },
   *etc.*
 ]


text:
Q: unable to import electron modules from the BrowserWindow page I have a angular2/typescript application that I am having loaded into the electron BrowserWindow.  The modules for this are loaded via SystemJS.  But, when I run it via launching electron, I get an error from the SystemJS loader where it is trying to load the electron module from the file system.  Does anyone have any recommendation as what I need to configure in SystemJS to map it such that it can find the electron module?  I did not see any js to map to in electron-prebuilt.
Update
Added the main.js content and the error trace.  I am using maxogden's menubar to launch my code.  So the main process is coming from Javascript, and the page that is loaded in the BrowserWindow is in TypeScript.

index.html
<html>
<head>
<title>IR Toolbox</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="lib/ng2-material/dist/ng2-material.css">
<link rel="stylesheet" href="lib/ng2-material/dist/font.css">

<!-- 1. Load libraries -->
<script src="lib/angular2-polyfills.js"></script>
<script src="lib/system.src.js"></script>
<script src="lib/Rx.js"></script>
<script src="lib/angular2.dev.js"></script>
<script src="lib/router.dev.js"></script>
<script src="lib/http.dev.js"></script>

<!-- 2. Configure SystemJS -->
<script>
  System.config({
    map: {
      'ng2-material': './lib/ng2-material'
    },
    packages: {
      app: {
        format: 'register',
        defaultExtension: 'js',
      },
      'ng2-material': {
        defaultExtension: 'js'
      }
    }
  });
  System.import('app/main')
        .then(null, console.error.bind(console));
</script>
</head>

<!-- 3. Display the application -->
<body>
  <app>Loading...</app>
</body>
</html>

electron.service.ts
The module in question compiles fine with the typescript compiler.
import {Injectable} from 'angular2/core';
import {ipcRenderer} from 'electron';

@Injectable()
export class ElectronService {
  quit() {
    ipcRenderer.send('mb-app', 'quit');
  }
}

main.js
const ipcMain = require('electron').ipcMain;
const menubar = require('menubar');

const appPath = __dirname;

const config = {
  openDevTools: true,
  title: 'Toolbox'
};

const mb = menubar({
  dir: appPath,
  index: appPath + "/index.html",
});

if (config.openDevTools) {
  mb.on('after-create-window', () => {
    mb.window.openDevTools();
  });
}

// Quit when all windows are closed.
mb.app.on('window-all-closed', () => {
  if (process.platform != 'darwin') {
    mb.app.quit();
  }
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
mb.app.on('ready', () => {
  mb.tray.setToolTip(config.title);

  mb.app.allowNTLMCredentialsForAllDomains(true);

  ipcMain.on('mb-app', (event, arg) => {
    if (arg === "quit") {
      console.log('goodbye!');
      mb.app.quit();
    }
  });
});

Error Trace
GET file:///D:/projects/electron/ir-toolbox/dist/electron net::ERR_FILE_NOT_FOUND
  fetchTextFromURL @ system.src.js:1085
  (anonymous function) @ system.src.js:1646Z
  oneAwarePromise @ angular2-polyfills.js:580
  (anonymous function) @ system.src.js:1645
  (anonymous function) @ system.src.js:2667
  (anonymous function) @ system.src.js:3239
  (anonymous function) @ system.src.js:3506
  (anonymous function) @ system.src.js:3888
  (anonymous function) @ system.src.js:4347
  (anonymous function) @ system.src.js:4599
  (anonymous function) @ system.src.js:337
  ZoneDelegate.invoke @ angular2-polyfills.js:322Z
  one.run @ angular2-polyfills.js:218
  (anonymous function) @ angular2-polyfills.js:567
  ZoneDelegate.invokeTask @ angular2-polyfills.js:355Z
  one.runTask @ angular2-polyfills.js:254
  drainMicroTaskQueue @ angular2-polyfills.js:473
angular2-polyfills.js:322 Error: Error: XHR error loading file:///D:/projects/electron/ir-toolbox/dist/electron(…)ZoneDelegate.invoke @ angular2-polyfills.js:322Z
  one.run @ angular2-polyfills.js:218
  (anonymous function) @ angular2-polyfills.js:567
  ZoneDelegate.invokeTask @ angular2-polyfills.js:355
  Zone.runTask @ angular2-polyfills.js:254
  drainMicroTaskQueue @ angular2-polyfills.js:473
  ZoneTask.invoke @ angular2-polyfills.js:425

A: I worked around the solution by running ExpressJS from the main process to handle communication from the code running in the renderer process via XHR.  So now the renderer process never needs to access the electron module directly.


text:
Q: python: calling constructor from dictionary? I'm not quite sure of the terminology here so please bear with me....
Let's say I have a constructor call like this:
machineSpecificEnvironment = Environment(
   TI_C28_ROOT = 'C:/appl/ti/ccs/4.1.1/ccsv4/tools/compiler/c2000',
   JSDB = 'c:/bin/jsdb/jsdb.exe',
   PYTHON_PATH = 'c:/appl/python/2.6.4',
)

except I would like to replace that by an operation on a dictionary provided to me:
keys = {'TI_C28_ROOT': 'C:/appl/ti/ccs/4.1.1/ccsv4/tools/compiler/c2000',
        'JSDB': 'c:/bin/jsdb/jsdb.exe',
        'PYTHON_PATH': 'c:/appl/python/2.6.4'}
machineSpecificEnvironment = Environment(
     ... what do I put here? it needs to be a function of "keys" ...
)

How can I do this?

A: machineSpecificEnvironment = Environment(**keys)

A: You can apply a dict as an argument list by the ** notation
machineSpecificEnvironment = Environment(**keys)


text:
Q: How to remove book cover fold on Google Books API image covers When searching the Google Books API with a basic title search query like this (trillion dollar coach), the results return images that look like the following:

(Notice the page fold at the bottom right of the image)
Does anyone know how to get book covers that never have a fold? Any help is appreciated

A: Remove the Page-curl variable from the image link


text:
Q: Publisshing site, Display web part on every page I am building a publishing site for an Intranet. Every page in my site has a contacts section right under the left navigation, content by query web part is used to fetch data from a SharePoint generic list and display contacts.
What is the right method to add this web part on every page?

*

*Add web part in master page? I am also using OOTB discussion list and that uses system master page, making changes in system master page recommended?

*Create a content page layout, every page in my intranet site will use that page layout and add web part in page layout. What about discussion list that doesn't use my created page layout? Is there any way to change the page layout of discussion list?

A: Adding new masterpage would be the best option if you want the webpart shown on every page. That new masterpage can be either copied from existing masterpage, or you can create a new one. As far as I can see, there's no
Page Layout is good if you only want to show on every page in Pages Library, but as you said, when user navigating to list or library, they won't get it.


text:
Q: High CPU usage due to Microsoft IME (Chinese) I am running Windows 10 Professional on a 3-year old Thinkpad laptop, and the process named as Microsoft IME has been constantly consuming around 30% of my CPU. After looking up what IME means, it seems it is referring to the Input Method Editor. This process is running with high CPU consumption at all times, even when I am not using the Chinese input methods.

Is the IME related to input methods? To avoid this constant energy and CPU consumption, should I uninstall the Chinese input method? The input methods I have installed are as follows:

A: Partial Solution
Acknowledgement
Thanks to @Jon, this riddit post could have potentially solved the exact problem. However, due to the concerns listed under the same Riddit post, I have postponed to practice their solutions on my obsolete laptop.
MY partial solution (not working yet)
Like most bugs on Windows OS, restarting the machine/process should solve the problem. Here goes a piece of AutoHotKey script that does only one thing: "kill the process named ChsIME.exe". My Windows 10 OS have managed to start a new instance of this process right after the termination of the previous process.
; Kill the Windows IME process using keyboard shortcut -- Alt+Ctrl+Shift+I
^!+i::
    process, exist, ChsIME.exe
    pid = %ErrorLevel%
    Process, Close, %pid%
return

I am aware that this is by far not a clean solution, and I will post my system logs of high CPU usage when it happens next time.
System logs when ChiIME.exe is using up to 34% of CPU
https://www.dropbox.com/s/trkl647cbc6epjt/HighCPUUsage.zip?dl=0
Observation: SYSTEM is running that high-CPU ChsIME.exe process

A: Let me post what solved this issue in my case, please notice it might be a very specific interaction of IME, but I thought it might helps others in similar situation.
I was going nuts due to ChsIME.exe getting constant high CPU (kinda loop-buggy), but looking closer I also found my antivirus eating CPU as well. Somebody suggested to disable the antivirus but it would not disable itself [in this case Avast Behaviour Shield] as it keeps looping as well.
I uninstalled the IME keyboard extension temporarily (Win 10, Language and keyboard options), and as soon as I killed the consuming IME process the antivirus stopped itself and the CPU went down to idle - wow so that's interesting, who's fault is it?

A: There is a solution posted on
http://windowsreport.com/fix-microsoft-ime-high-cpu-usage/
I have tried and it is working for my Surface Pro 4.


text:
Q: beamer theorem box overflow
The theorem box in beamer (using the Warsaw theme) overflows on the right. How can I fix this?
\documentclass{beamer}

\usetheme{Warsaw}

\begin{document}

\frame{\frametitle{Test}
\begin{tabular}{p{4cm}p{6cm}}
 \vspace{0cm}\includegraphics[width=\linewidth]{triangle.jpg}&
 \begin{theorem}
 $a^2+b^2=c^2$
 \end{theorem}
\end{tabular}
}

\end{document}

A: beamer has its own means for this situation: columns.
\documentclass{beamer}
\usetheme{Warsaw}
\begin{document}

\begin{frame}
\frametitle{Test}
\begin{columns}
\begin{column}{4cm}
\includegraphics[width=\linewidth]{example-image-duck}
\end{column}
\begin{column}{6cm}
 \begin{theorem}
 $a^2+b^2=c^2$
 \end{theorem}
\end{column}
\end{columns}
\end{frame}
\end{document}

Or
\documentclass{beamer}
\usetheme{Warsaw}
\usepackage{tikz}
\begin{document}

\begin{frame}
\frametitle{Test}
\begin{columns}
\begin{column}{4cm}
\begin{tikzpicture}
 \draw[thick] (3.9,0) -- (0,0) node[midway,below]{$a$} -- (0,2) node[midway,left]{$b$}
 -- cycle node[midway,above]{$c$};
\end{tikzpicture}
\end{column}
\begin{column}{6cm}
 \begin{theorem}
 $a^2+b^2=c^2$
 \end{theorem}
\end{column}
\end{columns}
\end{frame}
\end{document}


text:
Q: Monitoring SFTP for any files and create data extension We currently have a few File Drop triggered automations which monitor a folder in our FTP server, import the file when it's added and populate a data extension.
Is there any way I can set up a folder in the SFTP where I can put files, as above, but instead of updating an existing data extension, it creates a new one, using the filename as the data extension name?

A: You can do this by setting up the File Drop and using a Script activity to control the creation of the data extension. The draw back is you would still need to add them to a master datension , to act as a staging area , then execute the script to create the new data extension based on the name


text:
Q: Why was the time turner never used again? It seems like it would be a very helpful device.
Why was it never used again, regardless of the purpose?

A: Quoting from Rowling's Pottermore article on Time Turners: (one of the many parts not carried over to the new Pottermore)

I solved the problem to my own satisfaction in stages. Firstly, I had Dumbledore and Hermione emphasise how dangerous it would be to be seen in the past, to remind the reader that there might be unforeseen and dangerous consequences as well as solutions in time travel. Secondly, I had Hermione give back the only Time-Turner ever to enter Hogwarts. Thirdly, I smashed all remaining Time-Turners during the battle in the Department of Mysteries, removing the possibility of reliving even short periods in the future.

A: All the Time-Turners, which the Ministry of Magic had full control over, were destroyed in the Battle of the Department of Mysteries in Order of the Phoenix.

Harry stuck his head out of the door and looked around cautiously. The baby-headed Death Eater was screaming and banging into things, toppling grandfather clocks and overturning desks, bawling and confused, while the glass-fronted cabinet that Harry now suspected had contained Time-Turners continued to fall, shatter and repair itself on the wall behind them.
Order of the Phoenix - Page 700 - British Hardcover

Time-Turners at the Leaky Cauldron

A: It was!
The other answers do a very good job of explaining the plentiful dangers of using Time Turners for serious things: erasing people from existence, damaging time itself, and so forth.
From Harry Potter and the Cursed Child:

SCORPIUS: Have you heard me, Albus? This is bigger than you and your
  dad. Professor Croaker's law — the furthest someone can go back in
  time without the possibility of serious harm to the traveler or time
  itself is five hours.

They do make another appearance, though.

In Harry Potter and the Cursed Child, not one but two Time-Turners are integral to the plot.

They were utilized several times, with various effects:

Albus and Scorpius used them to try to right Cedric's death, while the main antagonist, Delphini, tried to save Lord Voldemort.

A: The Ministry regulates their control and usage, to stop people mucking about with them. When the Time-Turner is first introduced, Hermione tells us that

Professor McGonagall made me swear I wouldn't tell anyone. She had to write all sorts of letters to the Ministry of Magic so I could have one. She had to tell them that I was a model student, and that I'd never, ever use it for anything except my studies.
— Prisoner of Azkaban, chapter 21 (Hermione's Secret)

From this, we can assume that the majority, if not all, Time Turners were under Ministry license and control. (It's possible one or two might be elsewhere, cf. unregistered Animagi). They're obviously a subject of intense research in the Dept. of Mysteries, as we see in OotP. In the battle to escape, the Ministry stock is apparently destroyed:

The baby-headed Death Eater was screaming and banging into things, toppling grandfather clocks and overturning desks, bawling and confused, while the glass cabinet that Harry now suspected had contained Time-Turners continued to fall, shatter, and repair itself on the wall behind them.
— Order of the Phoenix, chapter 35 (Beyond the Veil)

Hermione confirms this in the beginning of HBP, when explaining to Hagrid why the trio didn't take Care of Magical Creatures:

"Ar, I always knew yeh'd find it hard ter squeeze me inter yeh timetables," he said gruffly, pouring them more tea. "Even if yeh applied fer Time-Turners—"
"We couldn't have done," said Hermione. "We smashed the entire stock of Ministry Time-Turners when we were there in the summer. It was in the Daily Prophet."
— Half-Blood Prince, chapter 11 (Hermione's Helping Hand)

So that explains why the Time Turner couldn't be used again, from a practical standpoint.

What follows is definitely an out-of-universe explanation, but I include it because I think that it's interesting.
In many ways, once we know about Time Turners and Voldemort is back, we need to write them out of the story. They're an insanely useful tool to have in a wizarding war: you could pre-empt and warn yourself of any duel or attack, wipe your opponents from existence or look forward to see the result of a plan. Introduce time travel, and everything becomes very complicated. (That's not to say that you couldn't make a good story from that; indeed, something like Doctor Who thrives on that, but it doesn't fit in Harry Potter.)
For example, you could go back in time and multiply yourself in a duel. Even Dumbledore would stand little or no chance if facing ten Voldemorts. Sure, there are laws governing their use, but Voldemort would be unlikely to pay attention to them. (Plus, he controls the Ministry, so he could  repeal them if he really wanted.) Once Voldemort obtains a Time Turner, things go downhill fast for the Order. We remedy the potential damage time travel causes by destroying them entirely.
It's possible that any Time Turners not stored at the Ministry were later destroyed separately, for that reason: to stop Voldemort getting his hands on them. And while the Ministry might have been able to create new ones, they may have chosen not to, for the same reason. Or perhaps, behind closed doors, they might have been working on it, even if it never came to fruition.
Time travel provides a very deus ex machina solution, and had to go. It just so happened that Neville was the way that they went.

Finally, there was another Sci-fi SE question about nine months ago about the use of Muggle weapons that's worth reading. The questions are broadly linked. Introducing guns and/or time travel to Harry Potter would have ruined the atmosphere.

A: Because in the 5th book, The Order of Phoenix, in the epic battle that took place in the Ministry, all the time turners were destroyed.

A: I reason that as the time turners were stored in the department of mysteries, they may well have been the invention of a very intelligent wizard or witch. Making replicas possibly involved knowledge that was elusive to even the greatest wizards or witches of that age, hence a mystery.


text:
Q: Изменение фона label с помощью listwidget pyqt5 у меня есть код простенького приложения, в котором натянут label по низ всех слоев - черного цвета.
Еще есть функция - при нажатии на кнопку, на которой написано "меню" открывается listwidget. В "меню"  я попытался сделать такую функцию, чтобы при нажатии "Светлая тема" в lsitwidget фон label на главном окне меняется на белый.
Я хочу сделать так, чтобы после нажатия "светлая тема" этот текст в listwidget заменялся на "темная тема" и после клика на "темная тема" фон изменялся обратно на черный. Как это сделать?
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
from PyQt5.Qt import *

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1098, 600)
        MainWindow.setMinimumSize(QtCore.QSize(1098, 600))
        MainWindow.setMaximumSize(QtCore.QSize(1098, 600))
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(340, 310, 441, 131))
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(0, 0, 61, 23))
        self.pushButton_2.setObjectName("pushButton_2")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(0, 0, 1101, 601))
        self.label.setStyleSheet("background-color: rgb(0, 0, 0);")
        self.label.setText("")
        self.label.setObjectName("label")
        self.frame1 = QtWidgets.QFrame(self.centralwidget)
        self.frame1.setGeometry(QtCore.QRect(-1, -1, 321, 601))
        self.frame1.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame1.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame1.setObjectName("frame1")
        self.frame2 = QtWidgets.QFrame(self.centralwidget)
        self.frame2.setGeometry(QtCore.QRect(0, 0, 1101, 601))
        self.frame2.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame2.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame2.setObjectName("frame2")
        self.label.raise_()
        self.pushButton.raise_()
        self.pushButton_2.raise_()
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "PushButton"))
        self.pushButton_2.setText(_translate("MainWindow", "меню"))

class ListWidget(QtWidgets.QListWidget):
    def itClicked(self, item):
        QtWidgets.QMessageBox.information(
            None,
            "ListWidget",
            "click: {}".format(item.text())
        )

class ExampleApp(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.pushButton_2.setCheckable(True)
        self.pushButton_2.click()
        self.pushButton_2.installEventFilter(self)

        self.listWidget = ListWidget()
        self.listWidget.insertItem(0, "Светлая тема")
        self.listWidget.insertItem(1, "Настройки")
        self.listWidget.insertItem(2, "Справка")

        self.listWidget.itemClicked.connect(self.openWindow)

        self.listWidget.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.listWidget.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.listWidget.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.listWidget.setFont (QFont ("Helvetica", 20));
        self.listWidget.setStyleSheet("QListWidget::item:hover {background: rgba(158, 158, 158, 40);}\n"
"QListWidget::item:selected {background: transparent;}\n"
"QListWidget::item:selected {color: black;}\n"
"")

        lay = QtWidgets.QVBoxLayout(self.frame2)
        lay.addWidget(self.listWidget)
        lay.setContentsMargins(0, 30, 0, 0)

        self._animation = QtCore.QPropertyAnimation(self.frame2, b'size', self)
        self._animation.setStartValue(QtCore.QSize(0, self.height()))
        self._animation.setEndValue(QtCore.QSize(200, self.height()))
        self._animation.setDuration(200)

    def eventFilter(self, watched, event):
        if self.pushButton_2 is watched:
            if event.type() == 2 and self.pushButton_2.isChecked():
                self.frame2.raise_()
                self.pushButton_2.raise_()
                self._animation.setDirection(QtCore.QAbstractAnimation.Forward)
                self._animation.start()
            if event.type() == 2 and (not self.pushButton_2.isChecked()):
                self._animation.setDirection(QtCore.QAbstractAnimation.Backward)
                self._animation.start()
        return super(ExampleApp,self).eventFilter(watched, event)

    def openWindow(self, item):
        self.widget = QtWidgets.QWidget()

        if item.text() == "Светлая тема":
            self.label.setStyleSheet("background-color: white;")

if __name__=="__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = ExampleApp()
    window.show()
    sys.exit(app.exec_())

A: Попробуйте так:
....
    def openWindow(self, item):
# ?        self.widget = QtWidgets.QWidget()

        if item.text() == "Светлая тема":
            self.label.setStyleSheet("background-color: white;")
            self.listWidget.removeItemWidget(item)
            self.listWidget.takeItem(0)
            self.listWidget.setCurrentRow(0)
            self.listWidget.insertItem(0, "Темная тема")

        if item.text() == "Темная тема":
            self.listWidget.removeItemWidget(item)
            self.listWidget.takeItem(0)
            self.listWidget.setCurrentRow(0)
            self.listWidget.setCurrentRow(0)
            self.listWidget.insertItem(0, "Светлая тема")
            self.label.setStyleSheet("background-color: black;")
...

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.Qt import *

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1098, 600)
        MainWindow.setMinimumSize(QtCore.QSize(1098, 600))
        MainWindow.setMaximumSize(QtCore.QSize(1098, 600))
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(340, 310, 441, 131))
        self.pushButton.setObjectName("pushButton")

        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(0, 0, 61, 23))
        self.pushButton_2.setObjectName("pushButton_2")

        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(0, 0, 1101, 601))
        self.label.setStyleSheet("background-color: rgb(0, 0, 0);")
        self.label.setText("")
        self.label.setObjectName("label")

        self.frame1 = QtWidgets.QFrame(self.centralwidget)
        self.frame1.setGeometry(QtCore.QRect(-1, -1, 321, 601))
        self.frame1.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame1.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame1.setObjectName("frame1")

        self.frame2 = QtWidgets.QFrame(self.centralwidget)
        self.frame2.setGeometry(QtCore.QRect(0, 0, 1101, 601))
        self.frame2.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame2.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame2.setObjectName("frame2")

        self.label.raise_()
        self.pushButton.raise_()
        self.pushButton_2.raise_()
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "PushButton"))
        self.pushButton_2.setText(_translate("MainWindow", "меню"))

class ListWidget(QtWidgets.QListWidget):
    def itClicked(self, item):
        QtWidgets.QMessageBox.information(
            None,
            "ListWidget",
            "click: {}".format(item.text())
        )

class ExampleApp(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.pushButton_2.setCheckable(True)
        self.pushButton_2.click()
        self.pushButton_2.installEventFilter(self)

        self.listWidget = ListWidget()
        self.listWidget.insertItem(0, "Светлая тема")
        self.listWidget.insertItem(1, "Настройки")
        self.listWidget.insertItem(2, "Справка")

        self.listWidget.itemClicked.connect(self.openWindow)

        self.listWidget.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.listWidget.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.listWidget.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.listWidget.setFont (QFont ("Helvetica", 20));
        self.listWidget.setStyleSheet("QListWidget::item:hover {background: rgba(158, 158, 158, 40);}\n"
"QListWidget::item:selected {background: transparent;}\n"
"QListWidget::item:selected {color: black;}\n"
"")

        lay = QtWidgets.QVBoxLayout(self.frame2)
        lay.addWidget(self.listWidget)
        lay.setContentsMargins(0, 30, 0, 0)

        self._animation = QtCore.QPropertyAnimation(self.frame2, b'size', self)
        self._animation.setStartValue(QtCore.QSize(0, self.height()))
        self._animation.setEndValue(QtCore.QSize(200, self.height()))
        self._animation.setDuration(200)

    def eventFilter(self, watched, event):
        if self.pushButton_2 is watched:
            if event.type() == 2 and self.pushButton_2.isChecked():
                self.frame2.raise_()
                self.pushButton_2.raise_()
                self._animation.setDirection(QtCore.QAbstractAnimation.Forward)
                self._animation.start()
            if event.type() == 2 and (not self.pushButton_2.isChecked()):
                self._animation.setDirection(QtCore.QAbstractAnimation.Backward)
                self._animation.start()
        return super(ExampleApp,self).eventFilter(watched, event)

    def openWindow(self, item):
# ?        self.widget = QtWidgets.QWidget()

        if item.text() == "Светлая тема":
            self.label.setStyleSheet("background-color: white;")
            self.listWidget.removeItemWidget(item)
            self.listWidget.takeItem(0)
            self.listWidget.setCurrentRow(0)
            self.listWidget.insertItem(0, "Темная тема")

        if item.text() == "Темная тема":
            self.listWidget.removeItemWidget(item)
            self.listWidget.takeItem(0)
            self.listWidget.setCurrentRow(0)
            self.listWidget.setCurrentRow(0)
            self.listWidget.insertItem(0, "Светлая тема")
            self.label.setStyleSheet("background-color: black;")

if __name__=="__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = ExampleApp()
    window.show()
    sys.exit(app.exec_())


text:
Q: Delete button not work bootstrap modal and Laravel I created one table that list items, and I added two buttons(edit and delete) so, the button edit is working, but the button delete is not working, and I'm making me carzy because I don't find the error. this is the table:

            text

        @foreach($Items as $item)

                {{ $item->text }}
                id) }}" class="btn btn-primary btn-fab btn-icon btn-round" title="Edit">

                    id }}" data-toggle="modal"  data-target="#modal-default" data-route="{{ route('ItemsController.destroy', $item->id) }}" data-title="{{ $item->id }}">

        @endforeach

the modal is:

Delete Item

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

Delete?

                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <form class="" action="" method="post">
                    {{ csrf_field() }}
                    {{ method_field('DELETE') }}
                    <button type="submit" class="btn btn-danger" name="button">yes, delete</button>
                </form>

javascript data:

and controller function destroy
public function destroy(Items $item) {
    $item->delete();

    return redirect()->route('items.index')->with('success', 'Deleted Success');
}

I checked it line by line, and I don't know what I'm wrong, please help me
Many times thanks for getting into this.

A: You need to trigger your modal from JS.
If it is bootstrap 4 then just simply open it using,
$('.modal form').attr('action', $(this).data('route'));
$('#ModalLabel').text($(this).data('title'));

//This will trigger modal
$("#modal-default").modal();

If it is bootstrap 5 then just simply open it using,
$('.modal form').attr('action', $(this).data('route'));
$('#ModalLabel').text($(this).data('title'));

//This will trigger modal
modal = new bootstrap.Modal(document.getElementById("modal-default"));
modal.show();


text:
Q: Will NMEA support the GNxx string in future? At the moment there is no problem when using GPS only devices, NMEA string with information about speed, DOP value etc starts with GP.. prefix. But with Glonass included NMEA string has different prefix GN.. and information about DOP and speed are not recognized in Qgis. Is it planned to update this also?
Position is ok, in both cases.
regards,
radek

A: Yes
NMEA supports GNSS string.
It gives Data in different strings like GNGGA , GPGST, etc. According to our requirements we have to mkae NMEA parser to get Data from those Strings.( I tested it in Geode device manufacture by Juniper system)


text:
Q: Count the number of contours I have plotted a ListContourPlot and have not specified the number of contours that are plotted, just the range. Is there a way to count how many contours have been automatically plotted by Mathematica?
EDIT
If I have contours representing different values, is there a way to select the contour relative to a specific value?

A: If you're dealing with multiple contours corresponding to multiple heights, a hacky way is to count the number of Tooltip[] objects being used internally. For instance,
conts = ContourPlot[Cos[x] + Cos[y], {x, 0, 4 π}, {y, 0, 4 π}, ContourShading -> None]

Then,
Count[conts, Tooltip[l : {__} /; MemberQ[l, Line[__]], v_?NumericQ], ∞]
   7

Here, counting Line[] objects would result in a gross overestimate. This is confirmed when one uses the explicit setting Contours -> 7 in ContourPlot[].

A: Original interpretation of the question
cp = ContourPlot[Cos[x] + Cos[y] == 1/2, {x, 0, 4 π}, {y, 0, 4 π}]

Count[cp, _Line, ∞]

9

To understand how this works you need to be familiar with how graphics is represented in Mathematica. Examining FullForm[cp] is a good start in case you don't know this yet.
Here is my take on the extra question using the same kind of approach:
cp = ContourPlot[{Abs[Sin[x] Sin[y]] == 0.5,
   Abs[Cos[x] Cos[y]] == 0.5}, {x, -3, 3}, {y, -3, 3}]

Cases[cp, {Directive[col_, __], lines__Line} :> {col, Length[{lines}]}, ∞]

But I think you are better off plotting the levels one by one and then using the approach here above.
cps = ContourPlot[#, {x, -3, 3}, {y, -3, 3}] & /@ {Abs[
     Sin[x] Sin[y]] == 0.5, Abs[Cos[x] Cos[y]] == 0.5}

Count[#, _Line, ∞] & /@ cps

{4, 9}

Alternative interpretation of the question
J.M. interpreted the question a little differently than I. My version of his code would not count tooltip labels, but would count colors instead. The reason is that it's slightly easier.
cp = ContourPlot[
  Cos[x] + Cos[y], {x, 0, 4 π}, {y, 0, 4 π},
  ContourShading -> None,
  ContourStyle -> (ColorData[97][#] & /@ Range[100])
  ];

Count[cp, _RGBColor, ∞]

7

Note that I did not need to know the number of levels in order to insert the colors, I only had to make sure to generate more colors than I had levels.

A: FindDivisions
The list of automatically selected contours can be obtained using FindDivisions[{#, #2}, #3, Method -> {}] as the setting for Contours.
SeedRandom[123]
data = RandomReal[1, {10, 10}];
lcp1 = ListContourPlot[data, InterpolationOrder -> 3, ImageSize -> 300];

The default list of contours in lcp1 can also be obtained using FindDivisions in the option setting for Contours. (See this answer to a related question.)
lcp2 = ListContourPlot[data, InterpolationOrder -> 3,
   Contours -> ((contoursFD = FindDivisions[{#, #2}, #3, Method -> {}]) &)];

The two graphics objects lcp1 and lcp2 are identical:
lcp1 == lcp2

True

And the list contoursFD captured in lcp2 is identical with the default list of contours in lcp1.
N @ contoursFD

{0., 0.2, 0.4, 0.6, 0.8, 1.}

These contours match the ones produced by @J.M.'s method using Tooltips:
contoursTT = Reverse[Cases[lcp1, Tooltip[a_ /; Not[FreeQ[a, _Line]], t_] :> t, ∞]]

{0, 0.2, 0.4, 0.6, 0.8, 1}

Row[{Show[lcp1, PlotLabel -> Style["contours : " <> ToString@contoursTT, 16]],
  Show[lcp2, PlotLabel -> Style["contours : " <> ToString@N[contoursFD], 16]]}]

Update: FindDivisions also works to find the contour levels for the setting Contours -> {Automatic, atmostn} using  atmostn as the second argument of FindDivisions:
atmostn = 3;
lcp3a = ListContourPlot[data, InterpolationOrder -> 3, Contours -> {Automatic, atmostn}];
contoursTT = Reverse[Cases[lcp3a, Tooltip[a_ /; Not[FreeQ[a, _Line]], t_] :> t, ∞]];
lcp3b = ListContourPlot[data, InterpolationOrder -> 3,
   Contours -> ((contoursFD = FindDivisions[{#, #2}, atmostn, Method -> {}]) &)];
contoursFD == contoursTT

True

Style[Row[{Show[lcp3a, PlotLabel ->
      Pane[Style["contours : " <> ToString@N[contoursTT], 12],
       ImageSize -> {200, Automatic}]],
   Show[lcp3b, PlotLabel ->
     Pane[Style["contours : " <> ToString@N[contoursFD], 12],
      ImageSize -> {200, Automatic}]]}],
 ImageSizeMultipliers -> {1, 1}]

For atmostn = 25 we get
contoursFD == contoursTT

True

Update 2: For the question added in the update:

assume I have a contour plot with 10 contours and their value ranges from 1 to 10. How can I select the contour which represents the value of 7 (without selecting the 7th contour)?

a contour plot with 10 contours and their value ranges from 1 to 10:
lcp10 = ListContourPlot[3 + data, InterpolationOrder -> 3,
  Contours -> Range[10], ContourShading -> None,
  ContourStyle -> (ColorData[63, "ColorList"][[;; 10]])]

How can I select the contour which represents the value of 7?
lcpC7 = ListContourPlot[3 + data, InterpolationOrder -> 3,
  Contours -> {7}, ContourStyle -> Directive[Red, Thick],
  ContourShading -> None]

lines = Cases[Normal@lcpC7, _Line, Infinity];
lines // Short

{Line[{{100., 3.55836}, {99.9841, 3.5646}, <<24>> ,{97.1146, 4.}}], <<29>>, <<1>>}

Show[lcp10, Epilog -> {Blue, Thick, lines}]

A: As mentioned by @JM, ContourPlot by default includes a tooltip for each contour value. The first element of each tooltip includes the Line objects making up the contour, using GraphicsComplex coordinates. So, if you want to have an association tying each contour value with the Line objects making up that contour, you can do the following:
assoc = Association @ Cases[
    Normal @ ContourPlot[Cos[x] + Cos[y], {x, 0, 4 π}, {y, 0, 4 π}],
    Tooltip[x_, y_] :> y -> Cases[x,_Line,Infinity],
    Infinity
];

The total number of contours is:
Length @ assoc

7

and the Line objects associated with the contour 1.5 is:
assoc[1.5] //Short[#,10]&

{Line[{{0.,1.04642},{0.0360218,1.04582},{0.0790736,1.04292},{0.1122,1.03923},{0.137919,1.03552},{0.213951,1.02025},{0.224399,1.01775},{0.249554,1.0098},{0.315379,0.988578},{0.336599,0.980251},<<19>>,{0.980251,0.336599},{0.988578,0.315379},{1.0098,0.249554},{1.01775,0.224399},{1.02025,0.213951},{1.03552,0.137919},{1.03923,0.1122},{1.04292,0.0790736},{1.04582,0.0360218},{1.04642,0.}}],<<7>>,Line[{{<<19>>,<<18>>},<<163>>}]}

A: Expanding on C.E.'s answer to address the extra question, let's do the following. Taking the function
f[x_, y_] = Cos[x] + Cos[y];

as an example consider the contour plot:
cp = ContourPlot[f[x, y],
        {x, 0, 4 Pi}, {y, 0, 4 Pi},
        Contours -> {0.1, 0.5, 1}, ContourShading -> False]

If we do
assoc = GroupBy[Cases[Normal@cp, Line[a_] :> a, Infinity], f @@ #[[1]] &];

then we get an Association object that associates the value of the contour (as computed by f @@ #[[1]] &) to the list of contours with that value. Unfortunately, because of numerical error in the contour values, there are more than just the three (0.1, 0.5, and 1):
Keys@assoc // FullForm
(* List[1.`, 1.0000000000000002`, 0.9999999999999996`, 1.0000438962964133`, 0.4993229505918183`, 0.4993229505918182`, 0.4993229505918185`, 0.4993229505918175`, 0.5006924094447289`, 0.09990244696130435`, 0.09990244696130413`, 0.09990244696130446`, 0.10067337224158247`] *)

Maybe that's okay, because maybe we want to know the values on the contours to machine precision, but probably not. To get around this, we can use Round in our selector function, like so:
assoc = GroupBy[Cases[Normal@cp, Line[a_] :> a, Infinity], Round[f @@ #[[1]], 0.01] &];

The choice of 0.01 is made after examining what we get. Then:
Keys@assoc
(* {1., 0.5, 0.1} *)

To get the contours for a particular value, do, for instance,
assoc[1.]

To see how it works:
ListLinePlot@assoc[1.]


text:
Q: Cannot query Firestore database on multiple values I have a database full with cars. The JSON format is this:
docId: {
        "countries": ["Netherlands"]
        "cities": ["Amsterdam"]
   }

I cannot query both arrays.
db.collection("EU-CARS")
    .whereArrayContains("countries", "Netherlands")
    .whereArrayContains("cities", "Amsterdam");

How to solve this?

A: As you already noticed, Firestore allow you to filter your cars using only one whereArrayContains() method call. If you will use more than one, an error like this will occur:

Caused by: java.lang.IllegalArgumentException: Invalid Query. Queries only support having a single array-contains filter.

There are two ways in which you can solve this. The first one would be to change the structure your car document like this:
docId
  |
  --- filters
       |
       --- "country": "Netherlands"
       |
       --- "city": "Amsterdam"

In this way you can filter your database using:
Query query = db.collection("EU-CARS").
    .whereEqualTo("filters.country", "Netherlands")
    .whereEqualTo("filters.city", "Amsterdam");

Chaining multiple whereEqualTo() methods is permitted in Firestore.
Or if you still want to use arrays, simply concatenate both names into a sigle one:
docId
  |
  --- "countries_cities": ["Netherlands_Amsterdam", "Netherlands_Utrecht"]

The corresponding query should look like this:
db.collection("EU-CARS")
    .whereArrayContains("countries_cities", "Netherlands_Amsterdam");

Edit:
If you have multiple countries/cities, then the structure of your document should look like this:
docId
  |
  --- filters
       |
       --- "Netherlands": true
       |
       --- "Amsterdam": true
       |
       --- "Utrecht": true

In this way you can filter your database using:
Query query = db.collection("EU-CARS").
    .whereEqualTo("filters.Netherlands", true)
    .whereEqualTo("filters.Amsterdam", true);


text:
Q: Email Form Field Variable I am trying to take two form fields and check to see if the user had inputted anything into those two fields. If the fields have been filled in I want to email the value of those fields that the user entered. If the fields are empty or filled with only spaces I want to display a generic text message indicating in the email that states these form fields are empty. I tried empty(), isset() and many different variations of each as well as checking if a variable equals NULL and all do nothing. I am wondering what I am doing wrong and it has to be rather simply.
HTML

Desired UserName: <input type="text" name="userName" style="width:200px;" value="" />

Desired Password: <input type="text" name="userPass" style="width:200px;" value="" />

PHP
$userName = $_REQUEST['userName'];
$userPass = $_REQUEST['userPass'];

if ($userName === NULL ) {
    $userName = "Use Generic Username, No Preference Entered";
}

if ($userPass === NULL ) {
    $userPass = "Use Generic Password, No Preference Entered";
}

$MESSAGE_BODY .= "Desired Username: ".$_POST["userName"]."\r\n";
$MESSAGE_BODY .= "Desired Password: ".$_POST["userPass"]."\r\n";

A: $userName and $userPass are not equal to null, When the user doesn't pass data it is just an empty string.
You can trim before checking:
$userName = isset($_REQUEST['userName'])? trim($_REQUEST['userName']): false;

trim() remove extra white spaces.
Now you can use it in your condition like so:
if (!$userName) { // if no username
    $userName = "Use Generic Username, No Preference Entered";
}

A: Seems to me you want something like this
$userName = !empty($_POST['userName']) ? $_POST['userName'] :
    'Use Generic Username, No Preference Entered';
$userPass = !empty($_POST['userPass']) ? $_POST['userPass'] :
    'Use Generic Password, No Preference Entered';

$MESSAGE_BODY .= sprintf('Desired Username: %s%sDesired Password: %s%s',
    $userName, PHP_EOL, $userPass, PHP_EOL);

Your main problem appears to be that you weren't using $userName and $userPass in your $MESSAGE_BODY string.

A: $userName = $_REQUEST['userName'];
$userPass = $_REQUEST['userPass'];

if (empty(trim($userName))) {
    $userName = "Use Generic Username, No Preference Entered";
}

if (empty(trim($userPass))) {
    $userPass = "Use Generic Password, No Preference Entered";
}

$MESSAGE_BODY .= "Desired Username: ".$_POST["userName"]."\r\n";
$MESSAGE_BODY .= "Desired Password: ".$_POST["userPass"]."\r\n";


text:
Q: Mocking repository method returns null instead expected value public interface IUnitOfWork
{
   ICarRepository CarRepository { get; }
   ...
}

ICarRepository has (besides other methods) GetById(int id) method.
That call I want to mock inside IUnitOfWork mock.

[Test]
public async Task Test()
{
    var unitOfWorkMock = new Mock<IUnitOfWork>();

    unitOfWorkMock.Setup(x => x.CarRepository.GetById(It.IsAny<int>()))
    .ReturnsAsync(new Car(){Name = "test"});

    var car = unitOfWork.Object.CarRepository.GetById(1);
    //returns null

   var car2 = await unitOfWork.Object.CarRepository.GetById(1);
    //returns null

    Any thoughts?
}

UPDATE:
public interface ICarRepository : IRepository<Car, int>
{
}

public interface IRepository<T, TId> where T : Entity<TId>
{
   Task<T?> GetById(TId id);
}
public class Car : Entity<int>
{
}

I'm expecting that car should be populated with whatever I passed in Returns statement in the mock setup but instead I'm getting null.

A: This is not an actual answer; just a lengthy comment to report that this complete code:
public interface IUnitOfWork
{
    ICarRepository CarRepository { get; }
}
public interface ICarRepository : IRepository<Car, int>
{
}
public interface IRepository<T, TId> where T : Entity<TId>
{
    Task<T?> GetById(TId id);                                  // question mark on T? is allowed; T is a reference type; nullable reference types are enabled
}
public class Car : Entity<int>
{
    internal string? Name { get; init; }
}
public class Entity<T>
{
}

public class F
{
    [Test]
    public async Task Test()
    {
        var unitOfWorkMock = new Mock<IUnitOfWork>();          // also works: new Mock<IUnitOfWork>(MockBehavior.Strict)

        unitOfWorkMock.Setup(x => x.CarRepository.GetById(It.IsAny<int>()))
            .ReturnsAsync(new Car { Name = "test", });

        Car? car2 = await unitOfWorkMock.Object.CarRepository.GetById(1);

        // car2 is nonnull and instance has 'Name' equal to "test"
    }
}

together with Moq version 4.18.4, does not reproduce the problem. car2 is as expected at the bottom of Test().
So the asker must supply more details in the question. Try to prepare a complete reproduction code (with no types implicit).


text:
Q: Salesforce as Identity Provider throwing Insufficient Privileges error We are implementing a SSO integration, where Salesforce act as the Identity Provider and a NodeJs application in Heroku act as the Service Provider.
We are following this Github project to build the NodeJs application.
Whenever we try to login the NodeJs app with SSO we are facing the following eror from Salesforce.

Insufficient Privileges
You do not have the level of access necessary to perform the operation you requested. Please contact the owner of the record or your administrator if access is necessary.

We deployed the Github project in heroku and still this error is occuring.
What should be the cause for this error?
Edit:
These are the settings I'm passing to Salesforce from my NodeJs app.

path: '/login/success'
issuer: 'passport-saml'
entryPoint: 'https://melbin-dev-ed.my.salesforce.com/idp/endpoint/HttpRedirect'
cert: 'MIIErDCCA ... hNZGSaxWWn'
identifierFormat: 'urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified'

A: Finally I found what caused this issue.
Actually, I entered a wrong URL in ACS URL field of Connected Apps Setup screen in Salesforce. I entered the URL of my NodeJs app and now it is working.


text:
Q: new javascript array from returned JSON I've got some JSON data being returned from a REST call that I want to parse, add totals, then spit out arrays with new data. I've got the parsing, looping, and adding figured out, and can write the results on the page (see post: json sibling data), but I want to further break down the totals. Here's the JSON I'm starting with:

{"ResultSet":{

    "Result":[

    {
        "file_size":"722694",
        "desc":"description1",
        "format":"GIF"
    },

    {
        "file_size":"19754932",
        "desc":"description1",
        "format":"JPEG"
    },

    {
        "file_size":"778174",
        "desc":"description2",
        "format":"GIF"
    },

    {
        "file_size":"244569996",
        "desc":"description1",
        "format":"PNG"
    },

    {
        "file_size":"466918",
        "desc":"description2",
        "format":"TIFF"
    }

  ]

}}

I've got it returning the totals for each different "desc" (see answer: https://stackoverflow.com/a/13016615/1766026), but now I want to break it down one step further and show totals for each "desc" with each "format" so the new output would look like:
description1: 444MB (222MB TIFF, 111MB GIF, 111MB JPEG)
description2: 333MB (111MB PNG, 111MB TIFF, 111MB JPEG)
where not all returned items have the same kinds of file formats.
(yes, I know these numbers do not add up from the JSON - it's just an example)
I'm thinking this can be done by pushing the results to a new array(s) based on matching elements then iterating over that and spitting out to the page.
Maybe the new array(s)/object(s) would look like this?

{
    "desc":"description1",
    "TIFF":"222",
    "GIF:"111",
    "JPEG:"111"
},
{
    "desc":"description2",
    "PNG":"111",
    "TIFF:"111",
    "JPEG":"111"
}

I just saw this: How do I create JavaScript array (JSON format) dynamically? I guess that would be one place to start?
(please pardon possible improper terminology - I do mostly front-end work and this kind of stuff is pretty new to me - polite constructive criticisms gladly accepted)

A: Yes. Iterate the array and build your objects from it.
var arr = parsedObj.ResultSet.Result;

var byDesc = {}; // an object as a key-value-map
for (var i=0; i<arr.length; i++) {
    var desc = arr[i].desc,
        format = arr[i].format;
    if (! (desc in byDesc))
        byDesc[desc] = {};
    if (! (format in byDesc[desc]))
        byDesc[desc][format] = 0;
    byDesc[desc][format] += (+arr[i].file_size); // parseInt
}

now we've got an object with filesizes by format and description:
{"description1":{"GIF":722694,"JPEG":19754932,"PNG":244569996},"description2":{"GIF":778174,"TIFF":466918}}

to get the desired output, we just enumerate this object:
var output = [];
for (var desc in byDesc) {
    var total = 0,
        formats = [];
    for (var format in byDesc[desc]) {
        formats.push(Math.round(byDesc[desc][format]/1000)+"MB "+format);
        total += byDesc[desc][format];
    }
    output.push(desc+": "+Math.round(total/1000)+"MB ("+formats.join(", ")+")");
}
return output.join("\n");

and we get
description1: 265048MB (723MB GIF, 19755MB JPEG, 244570MB PNG)
description2: 1245MB (778MB GIF, 467MB TIFF)


text:
Q: How do I automate removing lines from a multiline textbox while moving it to another multiline textbox in Visual Basic .NET I have two multiline textboxes; txtInputList and txtComplete. I can manually move a line from txtInputList to txtComplete while removing the line from txtInputList as the desired result. However, I am having difficulty in automating this for every line. Here is the manual way clicking the button for each line:
Private Sub btnProcessItems_Click(sender As Object, e As EventArgs) Handles btnProcessItems.Click
    Dim strText() As String
    strText = Split(txtInputList.Text, vbCrLf)
    txtInputList.Text = String.Join(vbCrLf, strText, 1, strText.Length - 1)
    txtComplete.AppendText(strText(0) + vbCrLf)
End Sub

That works as desired. I've tried a For-loop, but I can't get it to work.
Private Sub btnProcessItems_Click(sender As Object, e As EventArgs) Handles btnProcessItems.Click
    Dim strText() As String
    strText = Split(txtInputList.Text, vbCrLf)
    For x As Integer = 0 to strText.Length
        txtInputList.Text = String.Join(vbCrLf, strText, 1, strText.Length - 1)
        txtComplete.AppendText(strText(0) + vbCrLf)
    Next
End Sub

Can someone please help? Thank you!

A: Don't keep your data on your UI. Use a data structure to keep your data so you can operate on it directly (off the UI thread) then update the UI with the state of your data. If your data is just a list of strings then use List(Of String) or if it is more than just strings, use a List(Of someClass).
My answer will fix a number of issues for you.

*

*Keep data in a list

*Process data off the UI thread

*Use Async/Await to ensure no UI blocking

First, a class to hold the data. You have the option for a nice name for display, and a Url or whatever other property you want to use in your processor
Public Class Data
    Public Property Name As String
    Public Property Url As String
    Public Sub New(name As String)
        Me.Name = name
    End Sub
    Public Overrides Function ToString() As String
        Return Name
    End Function
End Class

Make lists of input items and complete items, and I will initialize inputs with 10 items, with letters A ... J. Also define a method to put both lists into your TextBoxes
Private inputs As List(Of Data)
Private completes As List(Of Data)

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ' initialize our fake data
    inputs = Enumerable.Range(65, 10).Select(Function(i) New Data(New String({Chr(i)}))).ToList()
    completes = New List(Of Data)()
    bindTextBoxes()
End Sub

Private Sub bindTextBoxes()
    txtInputList.Text = String.Join(Environment.NewLine, inputs)
    txtComplete.Text = String.Join(Environment.NewLine, completes)
End Sub

Add an Async button handler to process all items, and Task function to process each item. The button handler doesn't process anything, rather it's handled in the Awaited task. After each item is handled, you rebind the TextBoxes to update the UI.
Private Async Sub btnProcessItems_Click(sender As Object, e As EventArgs) Handles btnProcessItems.Click
    While inputs.Any()
        Await processFirstItem()
        bindTextBoxes()
    End While
End Sub

Private Function processFirstItem() As Task
    Return Task.Run(
        Sub()
            Dim item = inputs.First()
            inputs.RemoveAt(0)
            processItem(item)
            completes.Add(item)
        End Sub)
End Function

Private Sub processItem(item As Data)
    ' do whatever you need to do on the item, emulate a delay with thread sleep
    Threading.Thread.Sleep(250) ' remove this in production
End Sub

You may notice if you try this code that it runs off the UI so your app will run smoothly. You are just acting on a data structure instead of the UI. This is one good way to do what you are trying to do.

If your processing can be done in parallel, then you should look into Task Parallel Library, and your work will probably be performed much faster depending on the resources being used.

A: Try this, you'll need to change the names of the textboxes.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim sb As New System.Text.StringBuilder
    For Each line As String In TextBox1.Lines
        sb.AppendLine(line)
    Next
    TextBox1.Clear()
    TextBox2.Text = sb.ToString
End Sub

A: Totally agree with djv's answer, but here's one way to do it directly with the UI:
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If TextBox1.Text.Trim.Length = 0 Then
        Exit Sub
    End If

    Button1.Enabled = False
    TextBox1.Enabled = False
    TextBox2.Enabled = False
    TextBox2.Clear()

    Dim lines As New List(Of String)(TextBox1.Lines)
    Dim processed As New List(Of String)
    While (lines.Count > 0)
        Dim current As String = lines(0)
        lines.RemoveAt(0)
        TextBox1.Lines = lines.ToArray

        ' ... do something with "current" ...
        Label1.Text = "Processing: " & current
        Await Task.Delay(2000)

        processed.Add(current)
        TextBox2.Lines = processed.ToArray
    End While
    Label1.Text = ""

    TextBox1.Enabled = True
    TextBox2.Enabled = True
    Button1.Enabled = True
End Sub

Here it is in action:


text:
Q: Update text in other Sheets based on text in Sheet 1 I have got a workbook with 62 worksheets. I would like to place the word Red, Blue or Green on Sheet 1, and when I do I would like a formula to automatically update the other worksheets with the words Red, Blue or Green.
So the worksheets are in order like this (Sheet1, Blue Sheet 1N, Red Sheet2, Blue Sheet 2N, Red Sheet3, Blue Sheet3N, Red Sheet 4, Green etc).
If Sheet 1 cell A1 = Blue then Sheet 1N cell A1 = Red and so on.

A: So just put a variant of this formula in A1 on each worksheet:
=IF(Sheet1!A1 = "Blue", "Red", "")


text:
Q: Marching Cubes Terrassing/Ridge Effect I am implementing a marching cubes algorithm generally based on the implementation of Paul Bourke with some major adjustments:

*

*precalculation of the scalarfield (floating point values)

*avoiding duplicated vertices in the final list using a std::map

*vertex storing to visualize the final mesh in Ogre3D

Basically I changed nearly 80% of his code. My resulting mesh has some ugly terrasses and I am not sure how to avoid them. I assumed that using floating points for the scalar field would do the job. Is this a common effect? How can you avoid it?

calculating the vertex positions on the edges. (cell.val[p1] contains the scalar value for the given vertex):
//if there is an intersection on this edge
        if (cell.iEdgeFlags & (1 << iEdge))
        {
            const int* edge = a2iEdgeConnection[iEdge];

            int p1 = edge[0];
            int p2 = edge[1];

            //find the approx intersection point by linear interpolation between the two edges and the density value
            float length = cell.val[p1] / (cell.val[p2] + cell.val[p1]);
            asEdgeVertex[iEdge] = cell.p[p1] + length  * (cell.p[p2] - cell.p[p1]);
        }

You can find the complete sourcecode here: https://github.com/DieOptimistin/MarchingCubes
I use Ogre3D as library for this example.

A: As Andy Newmann said, the devil was in the linear interpolation. Correct is:
float offset;
float delta = cell.val[p2] - cell.val[p1];

if (delta == 0) offset = 0.5;
else offset = (mTargetValue - cell.val[p1]) / delta;

asEdgeVertex[iEdge] = cell.p[p1] + offset* (cell.p[p2] - cell.p[p1]);


text:
Q: Using bgiFrame (ie6 plugin) to overlay flash content which does not use wmode crossbrowser I have a site which contains flash and a menu, and I need to be able to overlay the flash with the menu but can't use wmode:transparent or opaque as it affects the performance too much.
I found the following plugin which allows this by using as iframe, but this falls over in newer browsers. (seemed to work out of the box in ie6/7)
http://plugins.jquery.com/project/bgiframe ( Change the z index of flash content )
I found a post here Invalid Character DOM Exception in IE9 where someone explains why it doesn't work but I haven't been able to get it working.
the original plugin code is
$.fn.bgIframe = $.fn.bgiframe = function(s) {
    // This is only for IE6
    if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
        s = $.extend({
            top     : 'auto', // auto == .currentStyle.borderTopWidth
            left    : 'auto', // auto == .currentStyle.borderLeftWidth
            width   : 'auto', // auto == offsetWidth
            height  : 'auto', // auto == offsetHeight
            opacity : true,
            src     : 'javascript:false;'
        }, s || {});
        var prop = function(n){return n&&n.constructor==Number?n+'px':n;},
            html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
                       'style="display:block;position:absolute;z-index:-1;'+
                           (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
                           'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+
                           'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+
                           'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+
                           'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+
                    '"/>';
        return this.each(function() {
            if ( $('> iframe.bgiframe', this).length == 0 )
                this.insertBefore( document.createElement(html), this.firstChild );
        });
    }
    return this;
};

A: In the end I managed to rewrite the plugin which enabled content to be overlayed in all versions of IE but wasn't very successful in other browsers. Firefox overlayed content without the need for the plugin.


text:
Q: How to set title and publish content created by the transmogrifier folders section? I'm using collective.transmogrifier.sections.folders pipeline section to create parent folders of content I'm importing into Plone.
My problem is those folders are created without a title and are not being published.
How can I solve that?

A: Try adding this sections to your pipeline (you may already have the second one):
# Publish all folders
[publish_all_folders]
blueprint = collective.transmogrifier.sections.inserter
key = string:_transitions
value = string:publish
condition = python:item.get('_type') == "Folder"

# Actually run the given transition to update the workflow state
[workflowupdater]
blueprint = plone.app.transmogrifier.workflowupdater


text:
Q: GCP: Generic routine to create IAM Policy Binding given a resource, member, and role I have a dump of IAM Policies and I want to add a new member to all of them.  The problem is that each resource has its own API for setting IAM policies, and so I would need to handle each type of resource individually.  So much toil.  I want a generic "IAM API" that takes a resource & policy as inputs, and creates the binding.  Is such a thing possible?
For reference, the format for my policy dump is:
- policy:
    bindings:
    - members:
      - user:tom@email.com
      role: roles/compute.networkUser
    etag: BwWfgKQuAFg=
  project: projects/800307802527
  resource: //compute.googleapis.com/projects/foo-proj/regions/us-central1/subnetworks/sub1

I have a very long list of these records, and I want to iterate through them adding a member "new-member@email.com" to each one.  Is there a generic IAM API I can call to add a policy binding to a resource?

A: As mentioned in the comment, each resource has its own API. There is no "Generic" IAM API to handle your use case. You can however create a feature request through the Public Issue Tracker to make a request for this feature to be implemented.