text:
Q: Problem getting the right return value when validating an user using AJAX I would like to get the proper value for okLogin when the user is incorrect, and stop the form from going forward, but I've noticed that when I call the function the return is executed first than the ajax call, which should be backwards.
I want the ajax function to update my okLogin variable to false anytime a mismatch happens.
<form action="test.html" onsubmit="return loginProcess();">
    Username
    <input class="form-control" type="text" id="usernameLogin" required>
    Password
    <input class="form-control" type="password" id="passwordLogin" required>
    <input type="submit" class="btn btn-primary btn-block" id="loginSubmitBtn" value="Login">
</form>

A: As written, your code will always return true; the value of okLogin, which you define to be true, will never be anything but that.  This is because ajaxCall.send() is asynchronous: it kicks off the AJAX call, but that's all; it doesn't wait for the call to succeed (or fail). So the next thing that happens, every time you call ajaxCall.send(), is that you return the current value of okLogin, which will be true every single time, because any code which might change its value won't have been executed yet.  (It will only be executed after there is a response to your AJAX request.)  Hope that makes sense; this is a common error when dealing with methods like send() which are asynchronous - that start something (in this case an AJAX request) but don't wait for it to finish before returning. (And in your case, returning a value which will be true every time, because every time, the code in your ajaxCall.onreadystatechange function will be executed after you return okLogin.)
One solution would be to make the AJAX call synchronous, by passing false instead of true as the last argument to open().  This will work, but it's a seriously bad idea; doing synchronous AJAX is deeply frowned upon, because it causes the user's browser to hang until a response is received.  That could take a few milliseconds (not a problem) but if the response is slow in arriving, it could take a second (very bad), or several seconds (totally unacceptable).
I'd suggest this approach: change this...
<form action="test.html" onsubmit="return loginProcess();">

...to this:
<form class="main-form" action="test.html" onsubmit="loginProcess(); return false;">

In other words, when the user submits the form, call loginProcess(), which kicks off your AJAX call, then return false (which will, for now, keep the form from being submitted).  We will now also ignore the return value of loginProcess(); it's not relevant. I've also added a class to your form, which we'll use in a minute.
Now, our strategy will be to have your callback (your ajaxCall.onreadystatechange code), which will be executed after a successful response, submit your form, only if okLogin is true.  To do that, change your code as follows:
    ajaxCall.onreadystatechange = function() {

        if (ajaxCall.readyState == 4 && ajaxCall.status == 200) {

            users = JSON.parse(ajaxCall.responseText);

            for (let item in users) {

                if (item === "username") {
                    if (usernameLogin !== users["username"]) {
                        okLogin = false;
                    }
                    console.log("Username: " + okLogin);
                }

                if (item === "password") {
                    if (passwordLogin !== users["password"]) {
                        okLogin = false;
                    }
                }
            }
            // ***** Add the following three lines:
            if (okLogin) {
                document.querySelector('form.main-form').submit()
            }
        }
    }

You could also use Promises (then(), etc.) but it's probably a good idea to understand callbacks before you tackle promises, if you're trying to understand asynchronous concepts.
Final note: you could also use async/await but before doing that, you'd want to understand Promises (and before that callbacks) - but more important, async/await may not be available in all of your target browsers; not IE, but also not earlier Edge versions.
hope this helps!

A: This will not work because ajax requests are asynchronous. In other words, the code within onreadystatechange is only being defined to be executed later, once the ajax call has returned. That is why your method is returning before the ajax call completes.
I would also note that authentication is an important thing to get right, and I think you would do well to look at some examples of proper authentication. From the looks of it, you are returning a list of all usernames and passwords in plaintext in the call. That's a very insecure design. If you have any intentions of using this for anything other than an experiment, you should not do things this way. In fact, even if you are only using this as an experiment, I would suggest trying to do it a different way just to get the experience of doing things how they ought to be done.
At any rate, the way to make this work as it stands would be, instead of returning, take some action within the callback. It's not clear in the code you submitted exactly what will happen when the loginProcess method returns (from the looks of it, nothing happens). You could, perhaps, call some other method with your onreadystatechange function with a true or false, and let that function handle whatever ought to happen based on a successful or unsuccessful login.
Example:
ajaxCall.onreadystatechange = function() {
  if (ajaxCall.readyState == 4 && ajaxCall.status == 200) {
    [your code to check the login here]
    someOtherFunction(okLogin)
  }
}

Also, I would suggest you take a look at a more modern way of doing ajax requests, such as using fetch and promises.

A: Welcome to SO. Your problem is due to the nature of asynchronous JavaScript. Your XMLHTTPRequest takes some time to get a response. Because of that you need to wait before returning a value until the request has been finished. Right now you instantly return okLogin without the request having a chance to change it.
So you need to delay that. You can use async / await to wait for the request to finish and continue with your process. This is all based on Promises, an object that can chain callbacks together with the then method.
Instead of the XMLHTTPRequest constructor, try the Fetch API. It's a more modern version of the same principle, but with a simpler, more powerful workflow and it works with promises.
Now with async / await you can make your function asynchronous, meaning it will take some time to complete, but do something else when it is done. The await keyword can be put in front of any promise returning function, like fetch, to await the function to complete and get the value from it.
In your code it would look like this.
async function loginProcess() {
    let usernameLogin, passwordLogin, response, users;
    let okLogin = true;

    usernameLogin = document.getElementById("usernameLogin").value;
    passwordLogin = document.getElementById("passwordLogin").value;

    response = await fetch("docs/users.json");
    users = await response.json();

    for (let item in users) {
      if (item === "username" && usernameLogin !== item) {
        okLogin = false;
      } else if (item === "password" && passwordLogin !== item) {
        okLogin = false;
      }
    }

    return okLogin;
}

loginProcess().then((loginStatus) => {
  console.log(loginStatus)
});

The function fetches your data with fetch, waits for it to finish, then turn the result from JSON into workable value and continues from there.
And because the loginProcess itself is asynchronous, it returns a Promise. Read up on those how you can use them. They are a very powerful feature of JavaScript.
Also pay attention to @bodacious. He is making some very good points regarding the security concerns in your code. Do your validation server side, where the code is invisible to the user.


text:
Q: Return pointer to the node of the linked list from the function I try to pass the pointer to the linked list node from the function.
Here the pseudo code (I'm using C):
node_t *node = % first node initialization % ; //global

int func(int valueToFind, node_t *parentNode) {
    while(node = node->next()) {
        if(node->value == valueToFind) {
            parentNode = node->prev();
            return 1;
        }
    }
    return 0;
}

int main() {
    node_t *parent;
    EDIT:
       parent = malloc(sizeof(node_t));
    END EDIT
    if(1==func(16, parent)) {//searching for value 16
        printf("%d\n", parent->value);
    }
}

At the line where printf("%d\n", parent->value); the program is crashing.
What am I doing wrong?

A: The parameter parentNode of func() is passed by value, that means even if you changed its value inside the function, it has nothing to do with the outside variable in main(). So when printf("%d\n", parent->value); is called, parent is still an invalid pointer.
You might try passed by pointer (i.e. pointer of pointer) to accomplish it. Such as:
int func(int valueToFind, node_t **parentNode) {
//                               ~~
    while(node = node->next()) {
        if(node->value == valueToFind) {
            *parentNode = node->prev();
//          ~
            return 1;
        }
    }
    return 0;
}

and
if(1==func(16, &parent)) {//searching for value 16
//             ~
    printf("%d\n", parent->value);
}

A: This is because, in your main() function, node_t *parent; is local to main() and you did not allocate any valid memory to it.
That said, in the call, func(16, parent) you have passed the parent using pass by value, so even if the function is intended to make any change to parent, it will not reflect back to main().
So,
 printf("%d\n", parent->value);

is invalid memory access and  invokes undefined behavior.

A: Your problem is here:
parentNode = node->prev();

This pointer variable is local to func().
If you want to keep it, you have to return the pointer value stored in it.
After func() returns, the local parentNode is gone.
What you passed to func() was just a copy of the pointer stored in parent variable.
See this solution:
node_t *node = % first node initialization % ; //global

node_t* func(int valueToFind) {
    while(node = node->next()) {
        if(node->value == valueToFind) {
            return node->prev();
        }
    }
    return NULL;
}

int main() {
    node_t *parent = func(16);
    if(parent) {//searching for value 16
        printf("%d\n", parent->value);
    }
}

Now parent is really holding a pointer, or a 'memory address'.
And parent has a true value, which is, different of 0. Every value different of 0 is true in C. If it's NULL (or 0), it's false.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Your CPU does not support VT-x I have created AVD, but when I try to run android program, it is showing an
error

Your CPU does not support VT-x

I enabled virtualization technology in BIOS, but still this error comes up when I try to run my android program.

A: There are two scenarios:
Using VMware: go to "WM" > "Settings" > "Processors" and Activate VT-x as below:

Using OS installed on HW: as others mentioned if your CPU supports that you should activate it in your BIOS.

A: According to Android Documentation, to run an emulator the development system's CPU should support one of the following virtualization extensions technologies:

*

*Intel Virtualization Technology (VT, VT-x, vmx)

*AMD Virtualization (AMD-V, SVM) -- only supported for Linux

Your CPU is Intel® Core™2 Duo Processor E7300, which according to the manufacturer does not support Intel Virtualization Technology (VT-x). That's the reason for this error.
The workaround is to use an alternative Android Emulator, e.g. Genymotion, as already suggested.

A: I suggest that you Just need to follows steps:
First,Go to Control Panel → Program and Feature.
  Then, Click on Turn Window Features on and off. A window opens.
    Then,Uncheck Hyper-V option and restart your system.
Now, you can Start HAXM installation.
Check this also https://software.intel.com/en-us/android/articles/installation-instructions-for-intel-hardware-accelerated-execution-manager-windows
OR
You can use Genymotion

A: If you have changed settings from BIOS, then you just need a restart of your machine.

A: There couple of solutions you can try

*

*You can Make an AVD With ARM Instead of HAXM.

*Other solutions can be just to enable Intel Virtualization Technology
from BIAS.

*Or you can use an alternative emulator like genymotion to fix this
problem.

If the above solutions bother you then you can use a physical device for testing purposes.

A: If you're
Using VMware: go to "VM" > "Settings" > "Processors" and Activate VT-x as below:

Then go to your Turn Windows feature on or off and uncheck virtual Machine Platform and Windows Hypervisor Platform as below:

Thank me :)

A: For those who might have the problem in these days,
you might try the steps described here:
https://android-developers.googleblog.com/2018/07/android-emulator-amd-processor-hyper-v.html
Also according to other answers, you have to be sure that CPU does
support virtualization, and that the virtualziation is on.

A: There is a couple of solutions to your problem.

*

*You can Make an AVD With ARM Instead of HAXM.

*Other solutions can be just to enable Intel Virtualization Technology
from BIAS.

*Or you can use an alternative emulator like genymotion to fix this problem.

*If the above solutions bother you then you can use a physical device
for testing purposes.


text:
Q: Using LESS with MVC5 in Visual Studio 2013 with Web Essentials I have installed Visual Studio 2013 with Update 2 and installed Web Essentials.
I had thought this was going to make adding LESS to my views a piece of cake, but am missing something.
The editor is great, and I imagine that it is compiling to css on save...
But I don't know where the generated css is, and I don't have any clue as to how to get it reference in my view.
I've tried a lot of searching, but can't get through the web of links about installing this and the features of that.
Any help at all will be greatly appreciated.
Thanks!

A: When you add a .less file and save, the Web Essentials will compile and generate the .css and .min.css files. You will see an arrow in your solution explorer, or you can also confirm in your file system that the files are in the same folder.

A: Haven't used less with vs2013 but I have used sass and my guess would be the same. By default the generated css gets generated in the same directory as the source (as it seemed to me) but you can check via tools>options>web essentials and there should be a set of options for less compile on save, build and directory to name but a few.
If you right click on the solution there should be an option to create a web essentials settings file for the solution - these create and adds a json file of web essentials settings to the solution which means your settings are local to the solution which could be important if you are changing the output directory.


text:
Q: The existence of the set of all functions on A into B I need to prove that the set of all functions on A into B, denoted by $B^{A}$, exists.
I think if $|A| = m$ and $|B| = n$ then $|B^{A}|=n^{m}$ because for each element of $A$ there are $n$ independent ways of mapping it to $B$.
I don't know how to prove this.
the last time I posted this questions it got negative votes and closed.
It is a question, asked in Hrbacek and Jechs book.  I need to answer it.  Please help.

A: Since $A$ and $B$ exist, thus $A \times B$ exists, so $\mathcal{P}(A \times B)$ exists. Thus by the schema of separation (aka the schema of comprehension), we have that $$\{f \in \mathcal{P}(A \times B) : f \mbox{ is a function } A \rightarrow B\}$$
exists. But this is just $B^A$, by definition. So we're done.
Note that I am using the statement
$$f \mbox{ is a function } A \rightarrow B$$
as shorthand for the statement
$$\forall a \in A,\exists! b \in B : (a,b) \in f.$$
This usage, while convenient, is non-standard. In particular, in most other branches of mathematics we take $f : A \rightarrow B$ to mean that $f$ has source $A$ and target $B$.

A: Your argument doesn't explain why the set exists, and it doesn't suggest what to do if one of the sets is infinite.
Now that every function from $B$ to $A$ is a subset of $B\times A$. Show that we can define when a set is a function whose domain is $B$ (where $B$ is a parameter), then you can use separation to conclude the set of functions is a subset of $\mathcal P(B\times A)$.


text:
Q: Display New Mail Desktop Alert not working on Outlook 2007 I have the settings correct - just to make sure:
- Tools | Options | Preferences Tab | Email Options | Advanced Email Options the Display a New Mail Alert is checked.
It doesn't work When I click Preview.
I also use rules for emails delivered in other folders than Inbox to display the alert and I have the same problem. However, the envelop is displayed in the tray.
I think the problem started since I upgraded to SP2, not sure ... (it worked fine until 1-2 months ago).
Is there an workaround for this?

A: Could it be that the alert is being displayed off-screen? If you're comfortable with editing the registry, you can navigate to:
HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Common\DesktopAlerts

and set the "XOffset" and "YOffset" values to zero (or near-zero). If that doesn't help, you may also try to delete the "Corner" value if it exists.


text:
Q: hibernate: change a bean field and then issue a query, query sees changed field I am confused about the behavior of hibernate bean setters within a Session.  I thought that when you set a bean field in a session, hibernate just knows that the bean is dirty, and on session close, this is a pending update, which will be flushed to the database.
However, I ran a test within one hibernate session where I fetched a bean by its id, changed a field from true to false, and then did an HQL query for a list of all such beans where this field was false.  The "dirty" bean showed up in the result set as if hibernate had already made a database UPDATE when I called the setter.  Then I did a session.clear() before leaving the session, to cancel pending updates and evict all beans.  I assumed that this would effectively throw away the dirty changes of the setter calls.  Yet I checked the database and the change from true to false was recorded.  NOTE: never called session.flush() inside this session.
It seems that Hibernate must be issuing a database UPDATE call as soon as I call a bean setter.  But this doesn't seem right?
Andy

A: That's right, Hibernate flushes any pending changes before querying (if it decides that pending change may affect query result). If you don't want to save any changes to DB, you have to rollback the transaction. If you call clear() but commit the transaction, it will be persisted in DB, because clear() is invoked too late (after SQL UPDATE). Or change flush mode as suggested by kamlesh, but make sure you know what you are doing while choosing a particular flush mode.
PS: Welcome to Hibernate world. Expect more such surprises.

A: Just check the session FlushMode of hibernate.
If its an Always or Auto mode , then hibernate will flush the dirty data into database, before executing new query.
java doc for FlushMode


text:
Q: Grab just the number in a string variable? I have multiple strings that are in the following format:

"At Revision ###."

Where ### can be one, two, three, or four digits long.
How do I parse that string in cmd to only grab the number?

A: try this (cmd shell script):

set "string=At Revision ###."
for /f "tokens=3delims=. " %%i in ("%string%") do set "number=%%i"
echo(%number%


text:
Q: Story ID - Lengthy YA Fantasy Novel where a teenager quests through a fictional country to cure his mother I read this book about 8 years ago, before they renovated our library. It is written by an Asian author (Japanese I think), and is heavily influenced by Asian cultures.
The main character's parents are divorced; the father cheated on the mother because she is sick and dying. The main character is upset and wants to cure his mother so much that he makes a wish and is given the opportunity to grant his wish by questing through an alternate world and gathering magical stones. The catch is that he is competing against another character who also has a wish, but only one wish can be granted.
I remember that the only way to enter the fictional country was to go up stairs that lead to nothing (the main character uses a stairway at a construction site), and one of the companions he meets along the way is a lizard person.
Physically, I remember the book being really large and having a teal cover with some cartoonish art of the main character and his companions.

A: You are looking for Brave Story by Miyuki Miyabe.
The novel was rereleased in 2006 matching the release of its anime adaption. This fits your "eight years ago". Miyuki Miyabe is a japanese author, as you remember.
The plot points that match your memories:
Wataru, the protagonist of Brave Story, witnesses his fathers cheating and the subsequent divorce. He learns about the existence of another world named Vision, where one can ask the Goddess of Destiny to change ones fate.
After his mother attempts suicide, Wataru wants to cure his mother and reunite his family, so he travels to Vision via the stairs within an empty and unfinished building. He is tasked with gathering five gemstones.
One friend he makes in Vision is a human-sized lizard. Not long after his arrival in Vision he finds out, that his schoolmate Mitsuru is also in Vision, competing with him for the gemstones.
As I just noticed, the cover shown in Wikipedia matches your description.


text:
Q: How to use scrollStrategy in MatDialog? I tried to make a scroll for a dialog in reposition strategy, but it doesn't work for me.
const scrollStrategy = this.overlay.scrollStrategies.reposition();
const dialogRef = this.dialog.open( DialogOverviewExampleDialog, { scrollStrategy } );

The full example
I expect that during scrolling the whole dialog(element .cdk-overlay-pane) will move
Almost right behavior

A: If you want to scroll the content of the dialog then you have to use the <mat-dialog-content> tag, or use the directive mat-dialog-content in your div element.
In your example try the following instead:

Hi {{data.name}}

<mat-dialog-content>

What's your favorite animal!!!!!!!

What's your favorite animal?

What's your favorite animal?

What's your favorite animal?

What's your favorite animal?

What's your favorite animal?

What's your favorite animal?

What's your favorite animal?

What's your favorite animal?

What's your favorite animal?

What's your favorite animal?

What's your favorite animal?

What's your favorite animal?

What's your favorite animal?

What's your favorite animal?

What's your favorite animal?

What's your favorite animal?

What's your favorite animal?

What's your favorite animal?

What's your favorite animal?

What's your favorite animal?

What's your favorite animal?

What's your favorite animal?

What's your favorite animal?

What's your favorite animal?

What's your favorite animal!!!!!!

  <mat-form-field>
    <input matInput [(ngModel)]="data.animal">
  </mat-form-field>
</mat-dialog-content>

  <button mat-button (click)="onNoClick()">No Thanks</button>
  <button mat-button [mat-dialog-close]="data.animal" cdkFocusInitial>Ok</button>

And now your dialog content should have a scroll on the side.
Read more about the Scrollable content container of a dialog on:
https://material.angular.io/components/dialog/api#MatDialogContent

A: I tried this way,
const dialogRef = this.dialog.open(LoginModalComponent, {
      autoFocus: false,
      maxHeight: '90vh' //you can adjust the value as per your view
});

A: Had a similar issue. Found that this works with Angular 12.
import { ScrollStrategy, ScrollStrategyOptions } from '@angular/cdk/overlay';

scrollStrategy: ScrollStrategy;

constructor(private readonly sso: ScrollStrategyOptions) {
   this.scrollStrategy = this.sso.noop(); // or close()/block()/reposition()
}

And pass it in to MatDialogConfig object as: (See docks ScrollStrategyOptions)
  const dialogRef = this.dialog.open(
    DialogOverviewExampleDialog, {scrollStrategy: this.scrollStrategy }
  );

This stackblitz helped me to understand my problem - ScrollStrategyOptions

A: Since https://github.com/angular/material2/pull/11235, .mat-dialog-container got max-height: inherit which should solve your problem.
Setting maxHeight: window.innerHeight + 'px' on the dialog configuration prevents the dialog from growing bigger than the screen.

A: I was looking for a similar solution as OP. The trick in the provided example is to set overflow:auto on the .cdk-global-overlay-wrapper.
Add this css to your styles (not inside the dialog's css):
Altough there's a slight issue, without auto pointer-events scrolling does not work on current chrome version and with auto pointer-events, closing via backdrop click does not work.
(will update if i find a solution)
.cdk-global-overlay-wrapper {
  overflow: auto;
  pointer-events: auto;  // needed for chrome but prevents backdrop click close
}

If you want to prevent scrolling on the back scenery i.e. parent component you could set overflow: hidden on the parent as long as the dialog is open.
.. just remove the scroll strategy from the example.

A: Hi try to put this on your style.css or style.scss
.cdk-global-overlay-wrapper {
  display: flex;
  position: absolute;
  z-index: 1000;
  overflow: auto;
  pointer-events: auto;
}

A: compare all the files difference.
there is extra css in style.css

.cdk-global-overlay-wrapper {
  pointer-events: auto;
  display: block;
  position: relative;
  overflow: auto;
  text-align: center;
}

.cdk-global-overlay-wrapper::before {
  content: '';
  display: inline-block;
  height: 100%;
  white-space: nowrap;
}

.cdk-overlay-pane {
  display: inline-block;
  position: relative;
  text-align: left;
  white-space: normal;
}

A: Its enough to add the two attributes below.
.cdk-global-overlay-wrapper {
  overflow: auto;
  pointer-events: auto;
}

A: You should use mat-dialog-content selector in order to create a scrollable content container for the dialog.
https://next.material.angular.io/components/dialog/api#MatDialogContent

A: let dialogRef = this.matDialog.open(MyComponent, {
   height: '100%',
   autoFocus: false,
});


text:
Q: Best practices for sharing code between AngularJS applications I'm developing several AngularJS applications and I'm looking for best practices how I can share code, especially directives, between these projects. The biggest problem I'm facing is the following:
Most of my directives contain at least one js file and a html template. The js file often contains a reference to the template. When I include the same js file from two different projects, what's the best way to handle the different paths?
There may be better ways to handle this situation I can't even think of. So, I would like to know if someone has experiences with this situation and how this is handled. Thanks!

A: I find it helpful to use compiled HTML templates using a build tool like https://www.npmjs.com/package/grunt-angular-templates . There are plenty of Gulp/Grunt alternatives if that one doesn't suite your needs.
Then you will need to keep your templates in namespaced directories so that your consumer applications don't collide.
Then you when you just need to consume a single compiled JS file. The templates are compiled into it. If you need to override the templates in your applicatons, just use the template namespace convention to provide the overrides.

A: Maybe you can write your code in nodejs style (with CommonJS), locate your files in different folders and such, and then use browserify to combine your js code into one piece. HTML templates can be also easily transpilled into js files using angular template cache and some tool like this one for gulp or maybe some similiar for grunt.


text:
Q: Android app written by Delphi keeps stopping I'm writing an Android app that receives push notifications using Delphi in RAD Studio 11.0 (Alexandria). But I've got a very strange problem preventing me from going any further than a blank app!
The problem can be easily reproduced by creating a blank Multi-Device application with an Android target. I can run the app (with or without debugging) on my connected (USB or wireless) Android phones without a problem. But if I enabled "Receive push notifications" (setting to TRUE) in the Entitlement List, the app will just close immediately after it's loaded on the phones.
I'm not sure whether it is a bug of Delphi or I'm just missing something. Could any experts please shed some light on me?
Thanks a lot.


text:
Q: Why do vectors appear to transform like rank-2 tensors in the Clifford algebra representation? In Euclidean space with metric $\delta_{ij}$ a Galilean vector rotates via $\hat{V} = \Lambda(\theta) V$ where $\Lambda$ is a member of $O(3)$. This can be represented by having the $V$ be column vectors and $\Lambda$ a $3\times 3$ matrix such that $\Lambda^T=\Lambda^{-1}$. A second rank symmetric tensor $T$ will rotate thus: $\hat{T} = \Lambda(\theta) T\Lambda^T(\theta)$. However we can also represent our vectors in a Clifford algebra (as opposed to the representation in the coordinate bases which is typically used).
Given
$\gamma_1,\gamma_2,\gamma_3$ that satisfy
$$
  \gamma_j\gamma_k+\gamma_k\gamma_j=2\delta_{jk}.
$$
And with $$V= v^i\gamma_i $$
The rotation of $V$ through an angle $\theta$ will be $$
\hat{V}=
\exp\left(\frac{\theta}{2}\gamma_1\gamma_2\right)
V
\exp\left(-\frac{\theta}{2}\gamma_1\gamma_2\right).
$$
However this looks an awful lot like the equation for the rotation of a tensor through an angle as well. A similar question arises as to why spinor transformations now look like vector transformations:
$$
  \hat{\psi}=
\exp\left(\frac{\theta}{2}\gamma_1\gamma_2\right)
\psi
$$
Does employing geometric algebra somehow change our space so that spinors are vectors, and physical vectors, are higher rank tensors in this space?

A: In the Clifford algebra framework, the transformation law of spinor $\psi$ (a rotation along $z$ axis as an example)
$$
\psi \rightarrow
e^{\frac{\theta}{2}\gamma_1\gamma_2}
\psi
$$
is fundamental, while all other transformations are derived.
Accordingly, a vector $V^\mu$ such as fermion current
$$
V^\mu = \bar{\psi}\gamma^\mu\psi =\psi^\dagger\gamma^0\gamma^\mu\psi,
$$
transforms as
\begin{align}
V^\mu &\rightarrow (e^{\frac{\theta}{2}\gamma_1\gamma_2}\psi)^\dagger\gamma^0\gamma^\mu e^{\frac{\theta}{2}\gamma_1\gamma_2}\psi \\
&=\psi^\dagger(e^{\frac{\theta}{2}\gamma_1\gamma_2})^\dagger\gamma^0\gamma^\mu e^{\frac{\theta}{2}\gamma_1\gamma_2}\psi \\
&=\psi^\dagger e^{-\frac{\theta}{2}\gamma_1\gamma_2}\gamma^0\gamma^\mu e^{\frac{\theta}{2}\gamma_1\gamma_2}\psi \\
&=\psi^\dagger \gamma^0(e^{-\frac{\theta}{2}\gamma_1\gamma_2}\gamma^\mu e^{\frac{\theta}{2}\gamma_1\gamma_2})\psi \\
&=\psi^\dagger \gamma^0(\Lambda^\nu_\mu(\theta)\gamma^\mu) \psi  \\
&=\Lambda^\nu_\mu(\theta)\psi^\dagger \gamma^0\gamma^\mu \psi \\
&=\Lambda^\nu_\mu(\theta)V^\mu.
\end{align}
Note that

*

*The fermion current $V^\mu$ is defined as $\bar{\psi}\gamma^\mu\psi= \psi^\dagger\gamma^0\gamma^\mu\psi$ not as $\psi^\dagger\gamma^\mu\psi$.  Bear in mind that for Lorentz boost $(e^{\frac{\theta}{2}\gamma_0\gamma_i})^\dagger\gamma^0 = e^{+\frac{\theta}{2}\gamma_0\gamma_i}\gamma^0 = \gamma^0e^{-\frac{\theta}{2}\gamma_0\gamma_i}$. The additional $\gamma^0$ in $\bar{\psi} = \psi^\dagger\gamma^0$ is essential in guaranteeing the Lorentz covariance of the vector $V^\mu$.

*$\Lambda^\nu_\mu(\theta)$ are just real numbers, so that they can be
moved freely around Clifford algebra elements.

And you can also derive that according to the spinor transformation rule, an antisymmetric tensor $T^{\mu\nu}$ such as
$$
T^{\mu\nu} = \bar{\psi}\gamma^\mu\gamma^\nu\psi  =\psi^\dagger\gamma^0\gamma^\mu\gamma^\nu\psi,
$$
transforms as
\begin{align}
T^{\mu\nu} &\rightarrow (e^{\frac{\theta}{2}\gamma_1\gamma_2}\psi)^\dagger\gamma^0\gamma^\mu\gamma^\nu e^{\frac{\theta}{2}\gamma_1\gamma_2}\psi \\
&=\psi^\dagger(e^{\frac{\theta}{2}\gamma_1\gamma_2})^\dagger\gamma^0\gamma^\mu\gamma^\nu e^{\frac{\theta}{2}\gamma_1\gamma_2}\psi \\
&=\psi^\dagger e^{-\frac{\theta}{2}\gamma_1\gamma_2}\gamma^0\gamma^\mu\gamma^\nu e^{\frac{\theta}{2}\gamma_1\gamma_2}\psi \\
&=\psi^\dagger \gamma^0(e^{-\frac{\theta}{2}\gamma_1\gamma_2}\gamma^\mu\gamma^\nu e^{\frac{\theta}{2}\gamma_1\gamma_2})\psi \\
&=\psi^\dagger \gamma^0(e^{-\frac{\theta}{2}\gamma_1\gamma_2}\gamma^\mu e^{\frac{\theta}{2}\gamma_1\gamma_2} )(e^{-\frac{\theta}{2}\gamma_1\gamma_2}\gamma^\nu e^{\frac{\theta}{2}\gamma_1\gamma_2})\psi \\
&=\psi^\dagger \gamma^0(\Lambda^{\mu'}_\mu(\theta)\gamma^\mu)(\Lambda^{\nu'}_\nu(\theta)\gamma^\nu) \psi  \\
&=\Lambda^{\mu'}_\mu(\theta)\Lambda^{\nu'}_\nu(\theta)\psi^\dagger \gamma^0\gamma^\mu\gamma^\nu \psi \\
&=\Lambda^{\mu'}_\mu(\theta)\Lambda^{\nu'}_\nu(\theta)T^{\mu\nu} .
\end{align}
For related discussions,

*

*See here for how to embed vectors and tensors in a spinor.

*See here for how to correctly define covariant derivatives
with respect to single-sided vs double-sided gauge transformations.


text:
Q: How do you test a spring bean within Grails? This is a follow-on question to that posted here:
How to initialise/wire beans in Grails Spock unit tests?
I haven't managed to find an example of where a spring bean is written in java within src/java and which is then unit tested within Grails using Spock.
Given:
// MyBean.java
// this needs to be in java as it is playing with spring-data-neo4j
package com.me;
public class MyBean {
    @Autowired
    def someNeo4jBeanThatCannotBeTestedByItself

    String readFromDb() {
        // this will execute code to actually read from a DB
        return "Hello from DB";
    }
}

Note that "someNeo4jBeanThatCannotBeTestedByItself" is a bean that is associated with spring-data-neo4j and I want to see that my code actually writes stuff here, so I want my unit/integration test to load spring beans (I don't want to mock this out).
What does the test case look like, is it an Integration test?  I've tried a couple of variations, but can't get the spring beans to be initialised by Grails test-app.

A: I know this is old post. As this is not answered yet, i'm trying to answer. If you figured out already, you can ignore.
I believe for this you can write Unit Test. But if this class is under, src/groovy or src/java spring autowire doesn't work. You need to add bean,someNeo4jBeanThatCannotBeTestedByItself and MyBean, in `resources.groovy' file as shown below:
beans={
      someNeo4jBean (Neo4jBeanClass)
      myBean(MyBean){
      someNeo4jBeanThatCannotBeTestedByItself = ref(someNeo4jBean)
      }
}

You can remove @Autowired annotation in your bean,MyBean
Now for spec to work , you need to add this property to your spec, static loadExternalBeans = true, then it loads beans present in resources.groovy file.
Sample Spec:
@TestMixin(GrailsUnitTestMixin)
class MyBeanSpec extends Specification {
    static loadExternalBeans =true//this loads beans present in resources.groovy
    def myBean

     def setup() {
        myBean= applicationContext.getBean("myBean")
        //now you can use this `myBean` in test cases..
    }

}

I also had similar situation and i got rid of with this approach.
Hope this helps.


text:
Q: ggplot multiple legends multiple plots Using ggplot2 to plot multiple plots for time series from 25 sites (ID) by group (gp).
df3[1:5,]
  year  ID val gp
1 1985 ID1   5  1
2 1986 ID1   5  1
3 1987 ID1  19  1
4 1988 ID1  20  1
5 1989 ID1  21  1

P<- ggplot(df3, aes(as.numeric(year), val, colour=ID)) +
  geom_line() +
  facet_wrap(~gp)+
  theme(strip.background = element_rect("transparent",colour = NA))+
  theme(strip.text.x = element_text(size = 17, face="bold", colour = "black"))+
  ylab( "Frequency                                  Frequency" ) +
  xlab("")+
  theme(axis.text=element_text(size=14, face="bold", color = "black"),
        axis.title=element_text(size=17,face="bold"))
P

As you can see it hard to use the legend to know each plot's sites (IDs).
Is there a way to add a legend to each panel instead of one legend.


text:
Q: Webdriver doesn't find any elements by id or class NoSuchElementException I'm trying to get data from inside a div of a public website.
The Selenium WebDriver doesn't seem to find any elements. I tried to find elements with id and class even with a XPath but still didn't find anything.
I can see the html page code when looking at PageSource, this confirms the driver works. What am I doing wrong here? Selenium V2.53.1 // IEDriverServer Win32 v2.53.1
My code:
    IWebDriver driver = new InternetExplorerDriver("C:\\Program Files\\SeleniumWebPagetester");
    driver.Navigate().GoToUrl("D:\\test.html");
    await Task.Delay(30000);
    var src = driver.PageSource; //shows the html page -> works
    var ds = driver.FindElement(By.XPath("//html//body")); //NoSuchElementException
    var test = driver.FindElement(By.Id("aspnetForm")); //An unhandled exception of type 'OpenQA.Selenium.NoSuchElementException' occurred in WebDriver.dll
    var testy = driver.FindElement(By.Id("aspnetForm"), 30); //'OpenQA.Selenium.NoSuchElementException'
    var tst = driver.FindElement(By.XPath("//*[@id=\"lx-home\"]"), 30); //'OpenQA.Selenium.NoSuchElementException'
    driver.Quit();

Simple HTML page:
<!DOCTYPE html>

        <meta charset="utf-8" />

        <form action="#" id="aspnetForm" onsubmit="return false;">

LEAD DELIVERY MADE EASY

        </form>

Side note, my XPath works perfect with HtmlWeb:
    string Url = "D:\\test.html";
    HtmlWeb web = new HtmlWeb();
    HtmlDocument doc = web.Load(Url);
    var element = doc.DocumentNode.SelectNodes("//*[@id=\"lx-home\"]"); //WORKS

A: It seems IE parses the local file in different way, so you cannot access DOM. Here are your options:

*

*Use Chrome instead of IE

*Keep using IE, move the file to C:\inetpub\wwwroot then change your code to open URL instead of localfile: driver.Navigate().GoToUrl("http://localhost/test.html");


text:
Q: Django - user profile :UNIQUE constraint failed: main_userprofile.user_id I'm trying to build profile model for my existing user model .
models.py
class UserProfile(models.Model):
    first_name = models.CharField(max_length=12,null=True)
    last_name = models.CharField(max_length=12,null=True)
    avatar = models.ImageField(null=True,upload_to='media_file/avatar/')
    user = models.OneToOneField(User,on_delete=models.CASCADE,
    related_name='profile',unique=True)
    bio = models.TextField(max_length=500)
    birthday = models.DateTimeField(
        blank=True, null=True)

    def create_profile(sender, **kwargs):
        user = kwargs["instance"]
        if kwargs["created"]:
            user_profile = UserProfile(user=user)
            user_profile.save()
    post_save.connect(create_profile, sender=User)

    def __str__(self):
       return  self.user.username

so i build forms.py to :
class UserProfileForm(forms.ModelForm):
 birthday = forms.DateField(widget=forms.SelectDateWidget)

 class Meta:
    model = UserProfile
    fields = "__all__"
    exclude =["user"]

and i wrote my views.py like this :
def profile_form_update(request):
    if request.method =="GET":
        form = UserProfileForm()
        return render(request,"profile_form.html",{"form":form})

    if request.method == 'POST':
        instance = get_object_or_404(UserProfile, user=request.user)
        form =UserProfileForm (request.POST or None, request.FILES or None,)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.user = request.user
            instance.save()
        context = {
           "form":form,
           "instance": instance,}
    return render(request, "profile_form.html", context)

first this is working ,when i make profile in django admin panel .and when I'm trying to load the existing form ,form renders with content that stored in database.when any changes to form that comes with an error:
IntegrityError at /profile/update/
UNIQUE constraint failed: main_userprofile.user_id

i know somehow my problem is with existing data stored in user models.and i did some google and someone said :

You are telling UserProfiles that the UserProfiles.u_id is unique, it's not (blanks/null). So you're getting the error. You may want to consider changing u_id to be a AutoField primary_key. And then connect them using models.ForeignKey('UserBase')

A: Try like this in view, you need to pass the instance to the form inorder to update the same,
def profile_form_update(request):
    instance = get_object_or_404(UserProfile, user=request.user)
    if request.method == 'POST':
        form = UserProfileForm(request.POST, request.FILES, instance=instance)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.user = request.user
            instance.save()
    else:
        form = UserProfileForm(instance=instance)
    context = {
       "form":form,
       "instance": instance,}
    return render(request, "profile_form.html", context)


text:
Q: Is hybrid (Cordova) fast enough for simple cross-platform mobile game, or are there better alternatives? I have a simple mobile game in mind that I would really want to make, but I can't decide on how to start. I would really want to make it run on Android and iOS, but I don't know how to accomplish that. I don't really want to use a game engine like Unity, since the game I have in mind is so simple that it would really be an overkill. The only thing I really need is a canvas to draw some shapes on.
So I was thinking about making it a hybrid app with javascript and Cordova, since I already know javascript and I'm comfortable with the javascript canvas. It's also good because you don't need to re-write code for both platforms, and thus programming will be faster and easier.
Now I am wondering if this is actually a good idea. I've never made a hybrid app before, and I don't really know if it's going to perform well.
I've read that hybrid apps run slower than native apps, but is this really that big of a deal? The game really has to run smooth, since it will be a fast-paced dodger style game.
How much slower are hybrid apps in comparison to native apps, and will it be fast enough for making a very basic 2d game run smoothly? Or are there better alternatives to hybrid, that won't make me have to re-write a lot of code for iOS and Android?
Thanks in advance!

A: If you've never done any of it before, then you will still have to solve a couple of problems here and there. I think you are not done just by implementing a canvas part. You will still want to add some UI, maybe some ads, in-app purchases, scoreboards etc. These topics are common in game development circles and there are many 3rd party tools to help you out. If you are really serious about game development, I think it is totally worth investing some time into Unity. It will pay back in a long run.


text:
Q: Stack inner anchor tag on top of nav I have an anchor tag with a hamburger style css that toggles a fly-out menu. The thing I am stuck at is that I always want it to stay on top however at present the flyout menu goes over the anchor hamburger and hides it. The flyout menu has the class called nav-container any help is welcome here as I have tried to solve this for a few hours. Thanks in advance.
HTML -

                        Test page

                                       Sub test page

                                                        Sub sub test page

Flyout HTML -

               <input type="checkbox" id="hc-nav-1-1-0" data-level="1" data-index="0" value="n83m4ogohw-gjximxnm4rq">Test page

Test page

                           <input type="checkbox" id="hc-nav-1-2-0" data-level="2" data-index="0" value="vjoqryeoc9-trdi4kvf59">level 2.1

level 2.1

level 3

level 2.2

Another top level

CSS
.toggle
{
    position: absolute;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    display: none;
    top: 20px;
    z-index: 9980;
    width: 35px;
    min-height: 24px;
    width: auto;
    left: auto;
    float: left;
    display: block;
    cursor: pointer;
    box-sizing: content-box;
    font-size: 20px;
    padding-left: 55px;
    line-height: 24px;
    margin-top: 0
}

.nav-container {
    position: fixed;
    z-index: 9998;
    top: 0;
    width: 350px;
    height: auto;
    max-width: 100%;
    max-height: 100%;
    box-sizing: border-box;
    transition: transform .4s ease;
    padding-bottom: 450px;
}

A: It was a very simple case of giving the class .nav-container a z-index:0
Thanks everyone for posting.


text:
Q: Unable to load R kernel in Jupyter notebook, Kernel Died unable to load shared object '/opt/conda/lib/R/library/stringi/libs/stringi.so'
I am trying to install Anaconda with R-kernal on RHEL 7 docker image,  the file is available (not missing) /opt/conda/lib/R/library/stringi/libs/stringi.so. It's working fine with Ubuntu/debian, but not working in RHEL
[I 07:18:08.758 NotebookApp] KernelRestarter: restarting kernel (2/5)
Error in dyn.load(file, DLLpath = DLLpath, ...) :
  unable to load shared object '/opt/conda/lib/R/library/stringi/libs/stringi.so':
  libicui18n.so.58: cannot open shared object file: No such file or directory
Calls: :: ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous>
Execution halted
[I 07:18:11.765 NotebookApp] KernelRestarter: restarting kernel (3/5)
Error in dyn.load(file, DLLpath = DLLpath, ...) :
  unable to load shared object '/opt/conda/lib/R/library/stringi/libs/stringi.so':
  libicui18n.so.58: cannot open shared object file: No such file or directory
Calls: :: ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous>
Execution halted
[W 07:18:13.631 NotebookApp] Timeout waiting for kernel_info reply from 16378669-1910-4cda-868e-2bb6860f7664
[I 07:18:14.770 NotebookApp] KernelRestarter: restarting kernel (4/5)
kernel 16378669-1910-4cda-868e-2bb6860f7664 restarted
Error in dyn.load(file, DLLpath = DLLpath, ...) :
  unable to load shared object '/opt/conda/lib/R/library/stringi/libs/stringi.so':
  libicui18n.so.58: cannot open shared object file: No such file or directory
Calls: :: ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous>
Execution halted
[W 07:18:17.777 NotebookApp] KernelRestarter: restart failed
[W 07:18:17.778 NotebookApp] Kernel 16378669-1910-4cda-868e-2bb6860f7664 died, removing from map.
kernel 16378669-1910-4cda-868e-2bb6860f7664 restarted failed!
[W 07:18:18.134 NotebookApp] Kernel deleted before session
[W 07:18:18.135 NotebookApp] 410 DELETE /api/sessions/e89223dd-d8e6-4104-b1ef-f161bc69a1b5 (10.66.192.88) 1.86ms referer=http://<Host_name>:8888/notebooks/Untitled2.ipynb?kernel_name=ir
[W 07:18:19.766 NotebookApp] Session not found: session_id=u'e89223dd-d8e6-4104-b1ef-f161bc69a1b5'
[W 07:18:19.767 NotebookApp] 404 DELETE /api/sessions/e89223dd-d8e6-4104-b1ef-f161bc69a1b5 (10.66.192.88) 1.61ms referer=http://<host_name>:8888/notebooks/Untitled2.ipynb?kernel_name=ir
[I 07:18:20.131 NotebookApp] Kernel started: 5e7e650b-6fde-4b3f-ae03-8b8d67a0d4f5
Error in dyn.load(file, DLLpath = DLLpath, ...) :
  unable to load shared object '/opt/conda/lib/R/library/stringi/libs/stringi.so':
  libicui18n.so.58: cannot open shared object file: No such file or directory
Calls: :: ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous>
Execution halted
[I 07:18:23.133 NotebookApp] KernelRestarter: restarting kernel (1/5)
Error in dyn.load(file, DLLpath = DLLpath, ...) :
  unable to load shared object '/opt/conda/lib/R/library/stringi/libs/stringi.so':
  libicui18n.so.58: cannot open shared object file: No such file or directory
Calls: :: ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous>
Execution halted
[I 07:18:26.137 NotebookApp] KernelRestarter: restarting kernel (2/5)
Error in dyn.load(file, DLLpath = DLLpath, ...) :
  unable to load shared object '/opt/conda/lib/R/library/stringi/libs/stringi.so':
  libicui18n.so.58: cannot open shared object file: No such file or directory
Calls: :: ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous>
Execution halted
[I 07:18:29.146 NotebookApp] KernelRestarter: restarting kernel (3/5)
Error in dyn.load(file, DLLpath = DLLpath, ...) :
  unable to load shared object '/opt/conda/lib/R/library/stringi/libs/stringi.so':
  libicui18n.so.58: cannot open shared object file: No such file or directory
Calls: :: ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous>
Execution halted
[W 07:18:31.002 NotebookApp] Timeout waiting for kernel_info reply from 5e7e650b-6fde-4b3f-ae03-8b8d67a0d4f5
[I 07:18:32.151 NotebookApp] KernelRestarter: restarting kernel (4/5)
kernel 5e7e650b-6fde-4b3f-ae03-8b8d67a0d4f5 restarted
Error in dyn.load(file, DLLpath = DLLpath, ...) :
  unable to load shared object '/opt/conda/lib/R/library/stringi/libs/stringi.so':
  libicui18n.so.58: cannot open shared object file: No such file or directory
Calls: :: ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous>


text:
Q: UserControl Inheritance WPF I wanted to implement a base class for my views. This class looks like the following:
public abstract class ViewBase<T> : UserControl, IView where T : ViewModelBase
{
    protected ViewModelBase viewModel;

    public ViewBase(T viewModel) : base()
    {
        this.InitializeComponent();

        this.viewModel = viewModel;
        this.DataContext = viewModel;
    }

    protected abstract void InitializeComponent();

    public void OnViewCalled(object parameters)
    {
        this.viewModel.OnCalled(parameters);
    }
}

This is the usage of the base class:
public sealed partial class LoginView : ViewBase<LoginViewModel>
{
    public LoginView(LoginViewModel viewModel) : base(viewModel)
    {
    }
}

The problem is that when I try the above code, I get the following error:

CS1729  C# 'UserControl' does not contain a constructor that takes 1
  arguments

Why is not the constructor of the ViewBase class called?

A: It appears you inherited from ViewBase in code behind but UserControl in XAML.
LoginView.xaml
<Local.View:ViewBase x:Class="YourNameSpace.View.LoginView"
                     x:TypeArguments="Local.ViewModel:LoginViewModel"
                     xmlns:Local.View="clr-namespace:YourNameSpace.View"
                     xmlns:Local.ViewModel="clr-namespace:YourNameSpace.ViewModel">
</Local.View:ViewBase>

LoginView.xaml.cs
namespace YourNameSpace.View
{
    public partial class LoginView : ViewBase<LoginViewModel>
    {
        public LoginView(LoginViewModel viewModel)
            : base(viewModel)
        {
            InitializeComponent();
        }
    }
}

ViewBase.cs
namespace YourNameSpace.View
{
    public abstract class ViewBase<T> : UserControl
        where T : ViewModelBase
    {
        protected ViewModelBase ViewModel;

        public ViewBase(T viewModel)
            : base()
        {
            ViewModel = viewModel;
            DataContext = ViewModel;
        }
    }
}


text:
Q: Getting intersecting polygons of points using OGR and Python I have multiple files that essentially have anywhere from 2000-5000 points each.
I have a polygon file that has about 10000 polygon shapes.
For each file containing the points, I want to get all the polygons that the file intersected.
Checking each polygon for each point and using Contains() takes too long. 2000 x 10000 iterations for each file essentially.
My current approach is to create a polygon around the points then get the intersections of that one bounding polygon to the 10000. This is fast but leads to me picking up intersecting polygons that don't actually contain the points but intersect the bounding polygon I had made around the points. So I have to go back then and do another check for intersections that don't actually contain points.
#go through files containing points and create a bounding polygon around each
for file in point_files:
        pts_ds = ogr.Open(file)
        pts_lyr = pts_ds.GetLayer()
        geom_collection = ogr.Geometry(ogr.wkbGeometryCollection)
        for feat in pts_lyr:
            geom_collection.AddGeometry(feature.GetGeometryRef())
        bounding_polygon = geom_collection.ConvexHull()
        #then save bounding polygon to file

#open up each of the bounding polygons I had made and intersect it against the comparison polygons
comparison_polygons_ds = ogr.Open(comparison_polygons.shp)
comparison_polygons_lyr = comparison_polygons.GetLayer()
matches = {}
for file in bounding_polygon_files:
    b_polygon_ds = ogr.Open(file)
    b_polygon_lyr = b_polygon_ds.GetLayer()
    for b_polygon_feat in b_polygon_lyr:
        b_polygon_geom = b_polygon_feat.GetGeometryRef()
        for comparison_polygons_feat in comparison_polygons_lyr:
            comparison_polygon_geom = comparison_polygons_feat.GetGeometryRef()
            if b_polygon_geom.Intersects(comparison_polygon_geom):
                matches.setdefault(comparison_polygon_geom.GetField("ID"), []).append(file)

The end result I want is essentially: file1 intersects x,y,z polygons. file2 intersects a,b,c polygons.
How do I achieve that?
I am unfamiliar with GIS and using Python with the OGR package.

A: I aggregated each files points into a MultiPoint and ran Intersects() on that for every comparison polygon and it was a lot faster (immediate). I'm not sure why since I imagine it still has to test every coordinate within the MultiPoint and see which polygons intersect with it. Maybe a MultiPoint object allows OGR to incorporate better spatial indexing algorithms as suggested by @bugmenot123.
Not completely sure how its working under the hood but it gives me the same results as I got with the bounding polygon method after second pass through cleaning, so results appear accurate.


text:
Q: arduino c++ issues regarding class name I am working on connecting my philips hue light bulbs to the arduino and found some resources online.
One of the resources has a file that keeps throwing an error and when I looked at it, I have never seen this syntax used before.
Can anyone help me out?
#ifndef SERIALHUE_H
#define SERIALHUE_H
#include <Arduino.h>
#include <Stream.h>
#include <ArduinoHue.h>

class SerialHue: public ArduinoHue{
 public:
SerialHue(char* ipAddress, Stream* serial);
boolean connect(char* deviceId, char* username);
 protected:
char* _ipAddress;
char* _deviceId;
char* _username;
boolean makePost(char* request, char* data);
boolean waitForResponse();
Stream* _serial;
};

#endif

The error is in this line:
*class SerialHue: public ArduinoHue{*
Giving the error:
SerialHue.h:10: error: expected class-name before '{' token
What is this format and what is wrong here?

A: check the compiler settings...it might be possible that it tries to compile c++ code with a c compiler
about the format:
class X : public Y {
}

is the syntax of extending a class in C++
plus: check that ArduinoHue.h really defines ArduinoHue class
...if you can't figure it out: take a look at the precompiled sourcefile (g++ -E)

A: First, make sure that you are not recursively including a file, like #including a file that #includes other files you have also #included.
Also, Forward declarations instead of #include ArduinoHue.h could solve your problem.  such as:
class ArduinoHue;

I have found similar questions, they might be able to help you:
expected class-name before '{' token
error: expected class-name before '{' token


text:
Q: Ito Integral as time changed Brownian motion Consider a probability space $(\Omega, \mathcal F, \mathbb P)$ with a Brownian motion $B_t$. Let $\mathcal F_t$ be the natural filtration generated by $B_t$. Let $Y_t$ be a $B_t$ measurable process such that $$X_t := \int_0^t Y_s dB_s$$ is well-defined, finite etc.
Define $\theta_t := \int_0^t Y_s^2 ds$.
We know that there exists a Brownian motion $W_s$ such that $X_t = W_{\theta_t}$.
The question I have is the following: Is $W_{\theta_t}$ an $\mathcal F_t$ Brownian motion?
I know that the theorems say that some enlargement of probability space maybe required. So I am a little confused.

A: not necessarily. See here for counterexamples:
https://mathoverflow.net/questions/84216/a-non-degenerate-martingale/84289#84289
eg.

Another counter-example: Let $f:R\to R$ be a non-constant $C^2$ funtion  with $f, f', f''$ all bounded, and such that (i) $f$ vanishes in a non-empty open interval $I$, (ii) $f'>0$ outside the closure of $I$,  and (iii) $E[f(W_1)]=0$. Consider the random variable $Y_1:= f(W_1)$. Clearly $P[Y_1=0]= P[W_1\in I]>0$. The process
$$
\sigma_t(\omega):=h(t,W_t(\omega)),
$$
where
$$
h(t,x) :=\cases{\int_R {1\over\sqrt{2\pi(1-t)}} \exp[-(y-x)^2/2(1-t)] f'(y) dy,& 0\le t<1,\cr
0,&t\ge 1,\cr}
$$
is predictable and bounded, and $\sigma_t(\omega)>0$ fo all $t\in[0,1)$ and all $\omega\in \Omega$. Moreover, by Ito's formula,
$$
Y_1=\int_0^1 \sigma_t dW_t,
$$
almost surely. In fact,
$$
E[f(W_1)|{\mathcal F}_s]=\int_0^s \sigma_t\,dW_t,\qquad\forall s>0,
$$
almost surely.


text:
Q: Shared upload folder in wordpress multisite I have a wordpress multisite, where I would like all the images uploaded through the main site (mysite.com) to be accessible to sub1.mysite.com and sub2.mysite.com. All the images should be in one folder without subdirectory (e.g: wp-content/uploads/image.jpg).
I tried the bellow function, but my images for subdomains are uploaded to wp-content/uploads/sites/#blog_id/
function wpse_16722_upload_dir( $args ) {
    $newdir = '/';

    $args['path']    = str_replace( $args['subdir'], '', $args['path'] ); //remove default subdir
    $args['url']     = str_replace( $args['subdir'], '', $args['url'] );
    $args['subdir']  = $newdir;
    $args['path']   .= $newdir;
    $args['url']    .= $newdir;

    return $args;
}
add_filter( 'upload_dir', 'wpse_16722_upload_dir' );

A: This will force uploads for all sites to the wp-content/uploads directory. Sub-directories (like year/month) will still exist (if the setting is enabled).
/**
 * Force all network uploads to reside in "wp-content/uploads", and by-pass
 * "files" URL rewrite for site-specific directories.
 *
 * @link    http://wordpress.stackexchange.com/q/147750/1685
 *
 * @param   array   $dirs
 * @return  array
 */
function wpse_147750_upload_dir( $dirs ) {
    $dirs['baseurl'] = network_site_url( '/wp-content/uploads' );
    $dirs['basedir'] = ABSPATH . 'wp-content/uploads';
    $dirs['path'] = $dirs['basedir'] . $dirs['subdir'];
    $dirs['url'] = $dirs['baseurl'] . $dirs['subdir'];

    return $dirs;
}

add_filter( 'upload_dir', 'wpse_147750_upload_dir' );


text:
Q: What is this schematic symbol with intersecting triangles?
What is this symbol?  I think it is some kind of amplifier or buffer, but I was unable find any information using search terms like "overlapping triangles," "intersecting triangles," or "double triangle symbol."
For context, I came across it in the ATmega2560 datasheet (pdf), in Figure 13-2 on page 68, reproduced below:

A: It's a MOS pass/transmission gate.


text:
Q: OVER_QUERY_LIMIT API de Google Buenas es la primera vez que estoy usando la API de google maps address. La cuestión es que tengo selectores en los cuales elijo las ciudades por las que quiero filtrar, con eso construyo un arreglo y inicio el mapa, pero se ve que hay un limite de peticiones.
Por más que busco las cosillas que he probado no me funciona ninguna, no se si me podeis arrojar un poco de luz sobre el tema.
Lo máximo que estoy iterando son 21 ubicaciones a la vez.
Uno de los sitios que he buscado soluciones es aquí pero no hay forma
var geocoder;
var map;
function initMap() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(39.4078968, -0.4317228);
    var mapOptions = {
    zoom: 5,
    center: latlng,
    mapId: '6d7bc70ff139bf71',
    disableDefaultUI: true,
    }
    map = new google.maps.Map(document.getElementById('map2'), mapOptions);
    codeAddress()
}

function codeAddress() {
    addressArray.forEach(function (item, index, array){
        geocoder.geocode( { 'address': item}, function(results, status) {
            if (status == 'OK') {
                map.setCenter(results[0].geometry.location);
                map.setZoom(7);
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                    animation: google.maps.Animation.DROP
                });
            } else {
                console.log('Geocode was not successful for the following reason: ' + status);
            }
        });
    });
}

Prueba según la página que puse
var codeAddress = (function() {
        var index = 0;
        var delay = 200;
        const labels = "C";
        function GeocodeCallback(addressArray, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(addressArray[0].geometry.location);
                new google.maps.Marker({
                    map: map,
                    position: addressArray[0].geometry.location,
                });
                console.log(addressArray);
            }
            else console.log("Geocode was not successful for the following reason: " + status);
        };

        return function(vPostCode) {
            if (geocoder) setTimeout(geocoder.geocode.bind(geocoder, { 'address': "'" + addressArray + "'"}, GeocodeCallback), index*delay);
            index++;
        };
    })();

Parece que funciona algo mejor, aunque no queda muy bien el echo de que se vayan añadiendo, además que solo coge como 2 ubicaciones, pero tengo varias dudas:

*

*En este caso no hay que hacer un foreach

*No hay forma de esperar a que cargue todo y una vez listo se muestra?

*Hay otra forma que no sea así que pueda funcionar

A: El bucle forEach no espera lo que ocurre dentro. Corre de una sola vez, gatillando tus 21 peticiones de una sentada. Para evitar esto la solución tradicional sería ir consumiendo tus direcciones en espera de geocodificación (ej haciendo pop() al arreglo) y cada vez que el callback del geocoder responde, decidir si la función se invoca a sí misma con la dirección siguiente o bien (cuando ya no quedan direcciones pendientes) termina el proceso.
Esto, de funcionar, funciona, pero el código es "callback hell". Cognitivamente esa recursión no es intuitiva de leer, te obliga a manejar el estado del arreglo en la función misma o mantener una variable libre en el scope superior, y por último hoy en día hay una solución más fácil: el método  geocoder.geocode(...) es variádico. Si en vez de pasar un callback como segundo parámetro no le pasas nada, te devuelve una promesa. (sujeto a que uses una versión más o menos reciente)
Entonces, en vez de
function codeAddress() {
    addressArray.forEach(item => {
       geocoder.geocode( { 'address': item}, function(results, status) {
         // callback hell y over_query_limit
       })
    });
}

Puedes iterar con un bucle for...of (que a diferencia del forEach sí respeta las promesas) y dentro de éste geocodificar de a uno
// La declaro asíncrona para usar await dentro de ella
async function codeAddress() {
  for(let item of addressArray) {
      try {
        let results = await geocoder.geocode({address:item})
        // y luego haces algo con results[0].geometry.location
      } catch (err) {
        console.warn('no se pudo geocodificar',err)
      }
  }
}

Esa implementación siempre hará las peticiones de a una. Y fíjate que una geocodificación fallida no se reporta en el callback (que no existe) sino que se maneja como excepción.
Si quisieras paralelizar el proceso para geocodificar, por ejemplo, de 2 en 2, una posibilidad sería armar el array de direcciones como un conjunto de  sub-arreglos de 2 elementos, y en cada bucle usar
   await Promise.all([
              geocoder.geocode(...), // dirección 1
              geocoder.geocode(...) // dirección 2
   ])

Pero eso ya son refinamientos de la misma idea general: promesas en vez de callbacks.


text:
Q: Does sizeof(pointer) depend on the object type? I'm trying to understand what a pointer to an object means. I'm wondering if A is an incomplete type, why is a pointer to A a complete type. Consider the following program:
#include <stdio.h>

class B; //B is incomplete type here

int main()
{
    printf("%d\n",sizeof(B*));//4
}

Please explain why does sizeof(B*) return 4? What exactly does a pointer to an object represent in memory?

A: A pointer to an object represents the address of the object in memory. If in your case it is 4 bytes, it means that you have a 32 bit address space (either the OS, or your program is built in 32bits). To maintain the address of an object you don't really need any knowledge of the object, so a pointer to an incomplete type is fine.
Note that none of this applies to pointers to members, which are a completely different beast.

A:
Please explain why sizeof(B*) return 4?

It returns 4 because size of a pointer variable is 4 in your system.

What exactly pointer to object represents in memory?

Objects reside in memory, and pointer to an object contains the starting memory address of that object. For example, if your B object has size 100 Byte, and it is placed in 1024-1123(100 Bytes)  memory location, then a pointer to that object will hold the value `024 (starting address).

Is pointer to sizeof depends on the object type?

I guess you meant does pointer size depends on object type?. No, since  pointers contain  an address, it's size depends on address space of your system, not type of object it points to.


text:
Q: Generating HTML documentation site from "mark down (.md)" files Is there something similar to "maven site plugin (javadoc)" is available for node? To be more specific, we are looking for a node package which can covert .md files in a reactjs project into html files. By convention each folder of our project has a markdown file which holds detailed documentation. We are looking for a tool (cli) which we can fire during the build process to create a documentation folder in the build (destination directory)- specifically interested in static HTML generation.
Thanks,
San

A: What have you looked for so far? Just googling "node MD to HTML" gives plenty of potential modules like this one and this one.
Have you tried some and they haven't worked? What have you looked for?

A: Found https://react-styleguidist.js.org/docs/documenting.html for my project. Awesome tool (though it is not equivalent to Maven Site).


text:
Q: SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed I am writing a test in Laravel to create a pin. When I create a pin, I want to save the link to it's own database table. Here is the test:
/** @test */
function an_authorized_user_can_create_a_pin()
{
    $this->withoutExceptionHandling();
    $user = create(User::class);
    $this->be($user);

    $pin = make(Pin::class);

    $response = $this->post('/pin', $pin->toArray());

    $this->assertDatabaseHas('pins', [
        'user_id' => $user->id,
        'title' => $pin->title,
    ])
    ->assertDatabaseHas('links', [
        'link' => $pin->link,
        'pin_id' => $createdPin->id
    ]);
}

The test is failing with this error:
Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity
constraint violation: 19 NOT NULL constraint failed: links.link (SQL:
insert into "links" ("link", "pin_id", "updated_at", "created_at")
values (, 1, 2018-08-20 21:44:19, 2018-08-20 21:44:19))

This is my controller:
public function store(Request $request)
{
    $pin = new Pin();
    $pin->user_id = auth()->id();
    $pin->title = $request->title;
    $pin->save();

    $pinLink = new Link();
    $pinLink->link = $request->link;
    $pinLink->pin_id = $pin->id;
    $pinLink->save();
}

Here is the factories for both:
<?php

use App\Pin;
use Faker\Generator as Faker;

$factory->define(Pin::class, function (Faker $faker) {
    return [
        'user_id' => function () {
            return factory('App\User')->create()->id;
        },
        'title' => $faker->sentence(20),
    ];
});

and
<?php

use App\Pin;
use Faker\Generator as Faker;

$factory->define(Pin::class, function (Faker $faker) {
    return [
        'user_id' => function () {
            return factory('App\User')->create()->id;
        },
        'title' => $faker->sentence(20),
    ];
});

This is where i'm not quite sure what to do as I am fairly new to PHP and Laravel (amd maybe everything around like Mysql / PDO, eager to learn).


text:
Q: Provisioning AWS Ubuntu using Ansible errors out with permission errors when gathering facts or installing apps regardless of become escalations When provisioning an AWS instance running Ubuntu 20.04.3 LTS (GNU/Linux 5.11.0-1028-aws x86_64) provisioning stops at the following tasks:
TASK [Gathering Facts] task when become:true is set in the playbook. The following error message is displayed: Missing sudo password
apt: update_cache=yes task when become: true is set in the playbook and gather_facts: false. The following error message is displayed: Missing sudo password
apt: update_cache=yes task when become: true is not set in the playbook. The following error message is displayed: Failed to lock apt for exclusive operation: Failed to lock directory /var/lib/apt/lists/: E:Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)"
TASK [geerlingguy.pip : Ensure Pip is installed.]  task when become: true is not set in the playbook. The following error messages are displayed:
"E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)",
"E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root?"
I suspect this is happening because this is a AWS modified OS, being GNU/Linux 5.11.0-1028-aws. I can ssh into the instance and run sudo apt update and sudo apt install python3-pip and it works without a password because I have ALL=(ALL:ALL) NOPASSWD:ALL set in sudoers for my ssh user. However, when I run sudo apt update and sudo apt install python3-pip with become: true is not set in the playbook, the above error messages are displayed.
I have run all versions of these and re-ran the playbook.
sudo rm /var/lib/apt/lists/lock
sudo rm /var/cache/apt/archives/lock
sudo rm /var/lib/dpkg/lock
sudo rm /var/lib/apt/lists/lock
sudo rm /var/lib/dpkg/lock-frontend

I found this stack overflow answer Ansible playbook fails to lock apt and added those tasks but it would fail at this step raw: apt-get -y purge unattended-upgrades.
unattended-upgrades seems to be disabled because I no longer see this message when I login to the instance.
2 updates could not be installed automatically. For more details, see /var/log/unattended-upgrades/unattended-upgrades.log
This is the first time I have had an issue with running these very basic ansible tasks. Given that AWS has its own ansible modules, I am sure I am doing something wrong or missing something obvious. I've had a hard time finding a solution to this problem because Googling has been ineffective. There are too many irrelevant results due to the popularity of the AWS ansible modules. I'm not trying to create or modify any AWS instances. I'm just trying to provision one.
I'm hoping one of the many AWS or Ansible experts here can help me out.
Here's the code: https://github.com/kahunacoder/ansible-wikijs
Here's an example
playbook.yml:
- hosts: all
  gather_facts: true
  become: true
  vars:
    ansible_python_interpreter: /usr/bin/python3
    pip_package: python3-pip
    pip_install_packages:
      - name: docker
  tasks:
    - name: Update apt
      apt: update_cache=yes
  roles:
    - geerlingguy.pip

hosts.yml:
ansible_host: wiki.mydomain.com # dev machine
ansible_ssh_user: wiki
ansible_ssh_private_key_file: "~/.ssh/id_rsa"
ansible_connection: ssh
ansible_python_interpreter: /usr/bin/python3

sudoers:
wiki ALL=(ALL:ALL) NOPASSWD:ALL

A: The fix was two lines of code to my ansible.cfg file.
[sudo_become_plugin]
flags = -H -S

I found the answer here: Ansible: sudo without password


text:
Q: Vo in an RLC circuit So I have this RLC circuit:  And its equations for voltage addition, current conservation, ohm's law and a solution of those equations (Vo).
Then there's this RLC circuit:
With another set of new equations for current conservation and voltage addition, since a capacitor and inductor have been added in series with the resistor.
I want to obtain new equations for the current conservation, voltage addition and the solution (which is the output voltage Vo) to this other RLC circuit,
which is just like the 2nd RLC but with another resistor added in parallel with the capacitor and inductor. Thanks in advance!

A:
i want to obtain new equations for the current conservation, voltage addition and the solution (which is the output voltage Vo) to this other RLC circuit which is just like the 2nd RLC but with another resistor added in parallel with the capacitor and inductor.

Add a term for the conductance of the added resistor into the appropriate equation, and you'll have it.

A: You question was geared towards finding the equations, so this will likely not be accepted as an answer. But you can use the Extra-Element Theorem.
This theorem says that the new transfer function with the resistor, is the transfer function without the resistor (\$H_\infty\$) that you already determined, then modified using:
$$
H(s) = H_\infty(s)\frac{1+\frac{Z_n}{R}}{1+\frac{Z_d}{R}}
$$
Where \$Z_n\$ and \$Z_d\$ are driving point impedances that are much simpler to find than solving a system of equations.

*

*\$Z_n\$ is found by assuming that \$V_i\$ takes on whatever value such that \$V_o=0\$. You usually don't need to know \$V_i\$ to determine \$Z_n\$ though.

simulate this circuit – Schematic created using CircuitLab
\$Z_n = \frac{V_0}{I} = 0\$

*

*\$Z_d\$ is found by applying an input where \$V_i = 0\$. So this is just the impedance you see where you insert the element.

$$
Z_d = \frac{V_o}{I} = (Ls) || \left(\frac{1}{Cs}\right)||\left(R + \frac{1}{Cs} + Ls\right)
$$


text:
Q: Excel VBA: if value in row(x) = value in row (x+1) in column C then sort values in column H I'm very new to Excel VBA.
Every month I import a spreadsheet of multiple customers' data that is already separated by customer in column C (account number).  Within each account number, I need to then sort the rows into alphanumeric order based on column E (service).
In other words, I need a macro that will sort the values in column E only if the values in column C are equal to each other.
Macro must also skip any irrelevant rows, some of which contain merged cells.
FYI - the format of all the values = text, other than column I (charge amount).
Any help greatly appreciated - apologies ahead of time if I haven't made my question clear enough!
Below is a spreadsheet example:

A: Go to the Developer tab and click "Record Macro". Give the macro any name (Excel's suggestion is fine).
Perform the actions to sort the data, such as selct the data, swt the Sort settings etc.
Click "Stop recording" in teh developer tab.
Goto to VB and open the macro you just recorded. Use the code as a basis for your actual macro. You can record anything you want to know in additional recorded macros. The rest I leave to you. Come back when you have problems with your code.


text:
Q: Ipad MasterDetail Template I have a question:
I am on a MasterDetail ipad template, Xcode42 in OSX1068 and loading my MasterDetail with a DYNAMIC tableview data source.
The table´s cell is linked by a Push segue to the DetailView, destination = Detail Split.
My problem is that the DetailViewController keeps looping on load a choice. Here is the code:

In MasterViewController:

    #pragma mark – Table view delegate
    -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
    self.detailViewController.detailItem =[NSString stringWithFormat:@"You choose %@",[_myList objectAtIndex:indexPath.row]];
    }
    //
    -(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
    // create an instance of DetailView
    DetailViewController *dVC = [[DetailViewController alloc] init];
    //sets dVC to the destinationViewController property of the segue
    dVC = [segue destinationViewController];
    //create the index path object
    NSIndexPath * path = [self.tableView indexPathForSelectedRow];
    NSString * theItem = [_myList objectAtIndex:path.row];
    dVC.rowNumber = path.row;
    dVC.itemName = theItem;
    }

And on DetailViewController.h:

    // tracking the items in the table
    @property int rowNumber;
    @property (nonatomic,strong) NSString * itemName;

Nothing fancy anywhere else.
Thanks for any help !


text:
Q: Modelling world in terms of "or" and "and" Thomas user said in the comment:

I think modelling the world in terms of "or" (aka discriminated union) and "and" (aka records) is a very powerful functional trick. Sometimes, functions/interfaces are useful too, but if I tend to stick to "or"/"and" as much as I can :-)

Suppose I'm modelling the world of Animal (open-world assumption), how could I do it by using discriminated unions, records and sometimes functions/interfaces?
For example, with animal types, can I use discriminated union to classify them?
type Type =
    | Phyla of Phyla
    | Chordata of Chordata
    | Arthropods of Arthropods
    | ...

and Chordata =
    | Fish
    | Reptiles
    | Mammals
    | ...

A: Functional and object-oriented programming differ in their emphasis of words. "Function" implies a focus on verbs, while "object" implies a focus on nouns.
You may be struggling due to the absence of verbs in the problem description. You mentioned an animal kingdom simulator in the comments; what kind of things happen in that world? I assume the animals don't sit around motionless :-)


text:
Q: Return ajax response on same jsp I have products with addtocart option against each product in productcatalogue.jsp. I want to add product to cart and show the cart in the same page. This is what i have done.
jsp+script
Add To Cart

$('#cart').click(function() {
            $.ajax({
                url : '/addtocart{id}',
                type : 'GET',
                data : "",
                success : function(response) {
                $('#Content').html(response);
              }
          });
    });

Cart Content(s):

I have added the cart contents in a div in this same jsp like above.
Controller
@Controller
@SessionAttributes("cart")
public class CartController {
    @ModelAttribute("cart")
    public Cart initCart() {
        return new Cart();
    }
    @RequestMapping("addtocart{id}")

    @ResponseBody
    public String addToCart(@PathVariable("id") int id,
                    @ModelAttribute("cart") Cart cart,Model model)
    {
        Product product = productService.getProductById(id);
            if (product != null) {
            CartLine line = new CartLine();
            line.setProduct(product);
            line.setQuantity(1);

            if (product.getQuantity() > 0) {
                cart.add(line);
            }
            }
            if(product.getQuantity() - 1 >= 0) {
                product.setQuantity(product.getQuantity() - 1);
                    }
            else {
                model.addAttribute("message", "Out of Stock!");
                return "error";
                }
                productService.updateProduct(product);

        return "productcatalogue";
    }

It just returns "productcatalogue". If i remove @responsebody i don't get any response on the desired div. Firebug just shows the jsp code in response column. Can someone show me how to do it.

A: Don't try to mix the two methods of attaching handlers. Perform both actions in a single click handler, defined and attached in javascript.
In the HTML, all you need to do is associate each "Add to cart" link with a produce id. A data- attribute is ideal.
Add To Cart

Notice that the id attribute is replaced with class="addTocart", allowing the following code to handle all such links - you can have as many on your page(s) as you like.
$('.addTocart').on('click', function(event) {
    event.preventDefault();
    $.ajax({
        url: '/addtocart/' + $(this).data('productid'),
        type: 'GET'
        dataType: 'json'
    }).then(updateCart);
});

You will probably want to send a quantity as well as productID, thus allowing one or more items to be added (or subtracted) at each hit
updateCart will be a function that accepts the json-decoded server reponse and updates the client-side representation of the cart accordingly.
By defining updateCart in some outer scope, it will be available to be called from elsewhere (other event handlers).


text:
Q: How to create database using SMO and C# I have a program made in WPF with C#, this will be installed on many computers.
The program needs a connection to the local database (SQL Server Express) because it works offline. There is a central server where data is collected after a sync using Sync Framework.
Everything works fine, synchronization is performed successfully and without complications.
The problem arises when wanting to install the program on a new computer; the requirement which calls for the program is that you have installed SQL Server Express with an instance called VYSICO.
When run for the first time, the program should create the database called Vysico, for this I am trying to run a command with SMO; this is my code:
ServerConnection srvConn = new ServerConnection();
srvConn.ServerInstance = ".\\" + instanceName;
srvConn.LoginSecure = false;
srvConn.Login = sqlServerLogin;
srvConn.Password = password;

Server server = new Server(srvConn);

Database db = new Database(server, "Vysico");
db.Create();

Wanting to instantiate Database, throws me the following error:

setparent failed for database Vysico

I searched the net a long time but nothing solves my problem, I hope you can help me. I thank you in advance for your time and help.


text:
Q: Stretch View based on whether keyboard opened In React Native, when the keyboard is closed, I want my <View> to be displayed on the full screen size, but whenever the keyboard is opened, I want it to be displayed only using the screen space that is visible to the user. How do I achieve that?
I've tried a couple of things, such as <KeyboardAvoidingView>, but didn't find a solution yet.
<View>
    ...
</View>

Example

A: post some code how do you construct current layout
in native apps for desired behavior you have to set in manifest:
<activity
    android:windowSoftInputMode="adjustResize"

in HERE some guide for react native and in HERE you have some plugin which handles this

A: I calculated the y position using onLayout, the y position of another <View> with bottom: 0, saved them using states and subtracted the first from the latter to calculate the height using states. The state updates whenever the keyboard is opened or closed.


text:
Q: Need help deciphering protocol over RS232, SPI, or I2C to talk to controller with Arduino I have a motor controller which I want to receive live telemetry from on my Arduino. I have posted screenshots of the registers below and the way the controller uses these protocols. I just can't get any data using either three? If anyone knows how I can get the data using any of these three protocols your help would be much appreciated!! I am willing to try anything :) Any form of help would be much appreciated.

UPDATE
Here is the code for i2c that I have already tried. I was trying to read from register 6. The code simply returns zeroes. Updated code to include Wire.available.
#include <Wire.h>

void setup() {
  // put your setup code here, to run once:
  Wire.begin();
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  int k = readRegister(0x08, 0x06);
  Serial.println(k, DEC);
  delay(500);
}

uint16_t readRegister(uint8_t i2cAddr, uint8_t regAddr) {

    // I2C write sequence to address the given read register
    Wire.beginTransmission(i2cAddr); // Module address
    Wire.write(regAddr);             // Register Address
    Wire.write(0);                   // Command Data = dummy zeroes
    Wire.write(0);
    Wire.write(-regAddr);            // Checksum
    Wire.endTransmission();          // Finish I2C write sequence

    // I2C read sequence to actually get the register value
    Wire.requestFrom(i2cAddr, 3);
    if (Wire.available() == 3) {
    uint16_t regVal = Wire.read();
    regVal <<= 8;
    regVal |= Wire.read();
    if ((Wire.read() + regVal >> 8 + regVal & 0xFF) == 0) {
        return regVal; // Checksum OK
    }
    }
    return 0xFFFF;     // Checksum error
}

EDIT #2
In my attempts to get this device to work I have tried using RS232 with the code below. The serial monitor shows nothing at all but they "Hello" message.
void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial1.write(0x0); //write five zeroes to clear the command buffer
  Serial1.write(0x0);
  Serial1.write(0x0);
  Serial1.write(0x0);
  Serial1.write(0x0);
}

void loop() {
  sendData();
  delay(500);
  serialE1();
}

void sendData() {
  Serial1.write((byte)0x17); //device address
  Serial1.write((byte)0x6); //register address
  Serial1.write((byte)0x0); //zeroes
  Serial1.write((byte)0x0); //zeroes
  Serial1.write((byte)-0x1D); //checksum
}
uint16_t serialE1() {

  Serial.println("Hello"); //just letting myself know it got here.
  while (Serial.available()) {
    uint16_t regVal = Serial1.read();
    regVal <<= 8;
    regVal |= Serial1.read();
    if ((Serial1.read() + regVal >> 8 + regVal & 0xFF) == 0) {
        Serial.write(regVal); // Checksum OK
    }
    else {
      Serial.write(0xFFFF);     // Checksum error
    }
  }
}

A: Probably you will have to WAIT for the bytes to arrive. So, in your code, write
while (Wire.available() != 3);
uint16_t regVal = Wire.read();
regVal <<= 8;
regVal |= Wire.read();
if ((Wire.read() + regVal >> 8 + regVal & 0xFF) == 0) {
    return regVal; // Checksum OK
}

If this does not work, you can try to add also the i2caddr to the initial checksum (shifted by 1 position), since it states that the checksum is Byte0 + Byte1 + ... Byte 3.
One more thing: if you continue getting a checksum error, print directly the bytes and try to figure out what's happening
EDIT:
As for your serial code, there is a bug and some things to improve.
The bug is that you wait for data (call to available) on Serial instead of Serial1.
Then, again you should WAIT for three bytes to arrive, not execute the reading until there are bytes. So.. Try using this code:
uint8_t cmd[5] = {0,0,0,0,0};

void setup() {
    Serial.begin(9600);
    Serial1.begin(9600);

    //write five zeroes to clear the command buffer
    sendWithChecksum(cmd);

    // Initialize the cmd array
    cmd[0] = 0x17;
    cmd[1] = 0x06;
}

void loop() {
    sendWithChecksum(cmd);
    Serial.println("Hello");
    receiveData();
    delay(500); // Wait for some time
}

void sendWithChecksum(uint8_t *array)
{
    uint8_t i;
    array[4] = 0;
    for (i = 0; i < 4; i++)
        array[4] -= array[i];
    Serial1.write(array,5);
}

void receiveData()
{
    // Wait for serial data to become available
    while(Serial1.available() < 3);
    uint16_t regVal = (((uint16_t)Serial1.read()) << 8) | Serial1.read();

    if ((Serial1.read() + regVal >> 8 + regVal & 0xFF) == 0)
    {// Checksum OK
        Serial.print("Received ");
        Serial.println(regVal,HEX);
    }
    else
    {// Checksum wrong
        Serial.println("Checksum wrong");
    }

    // Clear buffer
    while (Serial1.available()) Serial1.read();
}


text:
Q: Замена update на insert sqlite Есть таблица send, в которой есть поля id и name. id обычное поле, не primarykey. В таблице будут всего две записи с id = 1 и id = 2. Данные записи могут быть удалены. Есть 2 sql запроса:
 "UPDATE send SET name = '...' WHERE id = '1'"

и
 "UPDATE send SET name = '...' WHERE id = '2'"

Как переписать данные запросы так, чтобы, если записи с таким id нет (то есть update не произошел), тогда срабатывала команда
 "INSERT INTO send (id, name) VALUES('1', '...')"

и
 "INSERT INTO send (id, name) VALUES('2', '...')"

соответственно для второго запроса.
Хотелось это как-нибудь сделать одним запросом. В MS SQL все было просто: написал хранимку, сделал UPDATE получил @@ROWCOUNT, и, соответственно, на основании его сделал INSERT, а как быть в SQLite вообще не пойму.

A: *

*Создайте уникальный индекс по полю ID.

*Используйте запрос
REPLACE INTO send (id, name) VALUES('1', '...')

Если записи с указанным ID нет - она вставится, если есть - заменится.


text:
Q: Should I capitalize the word "on" in this title? Should it be "Alive on Arrival" or "Alive On Arrival"?

A: No, 'On' shouldn't be capitalized unless it is used adjectivally or adverbially.
'Capitalize the first word of the title, the last word of the title, and all nouns, pronouns, verbs, adverbs, adjectives, subordinating conjunctions, and a few conjunctions. Prepositions are only capitalized if they are used adjectivally or adverbially.'
Grammar Girl : Capitalizing Titles


text:
Q: How to call arrow function in another arrow function in nodejs Hey I have three functions in my javascript file like this
token.js
const function1 = async (token) => {
  .....
};

const function2 = async(token, permission) => {
    // I want to call function1 here like
    function1(token);
};

module.exports = { function1, function2 }

In function2 I want to call function it is giving me an error function1 is not a function
Does anyone know how to resolve this ?

A: It should be working. Check this: working functions

'use strict';

const function1 = async (token) => {
  console.log(token);
};

const function2 = async(token, permission) => {
    // I want to call function1 here like
    function1(token);
};

function2('apple','ball');

A: I think the problem is the way you importing/exporting the functions:
I changed your code a little and it works:
const function1 = async (token) => {
  console.log(token)
};

const function2 = async  (token) => {
    // I want to call function1 here like
     //console.log(token)
    function1(token);
};

export const f= {  function1, function2 }

and code that using the function:
import {f}  from './funcs.ts'

f.function2('ooo')

look at this plunk

A: Below is the solution to use function1 from say file1.js into function2 which is in another different JS file - say file2.js

file1.js

const function1 = async (token) => {
      .....
};

export { function1 }

And inside

file2.js

import { function1 } from './src/utils/file1'

{
...other stuff
function1(token);
}


text:
Q: Collect files from another folder I developed a script to convert all the markdowns files in my folder to ePub and place them in epubs.
Nevertheless I would like to place my files in the markdowns sub-folder and not in the main directory (the one where the makefile is).
.
├── epubs
│   └── blabla.epubs
├── makefile
└── markdowns
    └── blabla.pd

How should I modify my code?
MARKDOWN=$(shell find . -iname "*.pd")
EPUBS=$(MARKDOWN:.pd=.epub)

.PHONY = all clean
all: $(EPUBS)

%.epub: %.pd
        pandoc --from markdown --to epub --smart $< -o epubs/$@

clean:
        rm epubs/*

A: One approach is to explicitly tell make in your pattern rule where the .pd prerequisites for the .epub targets reside:
MARKDOWN_DIR := markdowns
EPUB_DIR := epubs

MARKDOWNS := $(wildcard $(MARKDOWN_DIR)/*.pd)
EPUBS := $(subst $(MARKDOWN_DIR),$(EPUB_DIR),$(MARKDOWNS:.pd=.epub))

$(EPUB_DIR)/%.epub: $(MARKDOWN_DIR)/%.pd
    pandoc --from markdown --to epub --smart $< -o $@

.PHONY: all clean

all: $(EPUBS)

Note two minor additional changes. I replaced your shell find command with make's $(wildcard) function because that is what it's for. Your pandoc command no longer needs epubs/ in front of $@ because that directory is now part of the target. And I reordered a bit according to my liking.


text:
Q: Is there a good "rule of thumb" for translating EXPLAIN cost to (wall-clock) runtime? From time to time, consumers of my database processes will ask for an estimate of when a given task will be done. While I feel like I know how to read an EXPLAIN in most database engines, I have trouble trying to translate this to "ask me again in 15 minutes". Does anyone know a good "rule of thumb" to use for any particular database?
I realize this isn't going to be a hard and fast rule, but even being able to give a ballpark figure could be useful in some instances.

A: I suspect that this is not possible the way you imagine it.  One important reason is that the actual run time is very hardware dependent, and many of the optimization decisions that the database engine does are effectively about balancing the use of the different hardware components (e.g., disk, memory, CPU).
I suggest that you run a bunch of queries relevant to your application, record the cost estimations and the run times, and try to make sense of that data.  You might get a nice linear relationship, or you might learn that the cost numbers are worthless for this purpose.

A: Cost based optimizers all work via a variety of proprietary algorithms (or you can read them for open source databases), but they typically work by assigning a reference operation a value of 1. For example, in SQL Server an operation with a cost estimate of 1 takes 1/320th of a second on a reference computer under some developer's desk in Redmond. The costing is just a relative guess of how expensive a query will be. Many RDBMSes use this cost in establishing priority or, in the case of deadlocks, to kill off cheaper queries (they take less time to run again). But it's all just a guess based on the information that the query optimizer has at its disposal at the time the query is being run.
Peter is correct, the best you can hope for is running some benchmark queries in ideal scenarios and using those to base best guesses on. You have to deal with a lot of different points of contention in an RDBMS, so it's difficult to specifically determine how any given query will perform in the real world.


text:
Q: cocos studio can't be open I am running it on Mac I am on macOS Catalina, Version 10.15.
When I am trying to open Cocos Studio it says

cocos studio can't be open

A: The reason is that 32-Bit Apps 'Not Optimized for Your Mac' No Longer Working on macOS Catalina.
According to https://www.macrumors.com/guide/32-bit-mac-apps/
When macOS Mojave was announced, Apple warned that it would be the last version of macOS that would support older 32-bit apps. Apple has been phasing out 32-bit apps for the last 10 years and is now ready to take the final step, even if Mac users may not be ready to lose access to older apps.


text:
Q: Converting text to image? How do I convert text into an image? The image resolution has to be really small ~30x30 to 100x100 and should only be a single color.
I've tried using GDI to do it but it generates text with multiple colors because of aliasing and whatnot.

A: For an image, render the textblock to a bitmap using the RenderTargetBitmap.Render() as described here.  Here is an example where you render a TextBlock "textblock", and assign the result to an Image "image"
var bitmap = new RenderTargetBitmap();
bitmap.Render(textblock);
image.Source = bitmap;

A: Try this. You can use the GraphicsObject in the code below to set the default type for text rendering which is no antialiasing. You can set the color using any combination of RGB that you want (single or multiple). I have used color brown here
private Bitmap CreateImageFromText(string Text)
{
       // Create the Font object for the image text drawing.
        Font textFont = new Font("Arial", 25, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);

        Bitmap ImageObject = new Bitmap(30, 30);
        // Add the anti aliasing or color settings.
        Graphics GraphicsObject = Graphics.FromImage(ImageObject);

        // Set Background color
        GraphicsObject.Clear(Color.White);
        // to specify no aliasing
        GraphicsObject.SmoothingMode = SmoothingMode.Default;
        GraphicsObject.TextRenderingHint = TextRenderingHint.SystemDefault;
        GraphicsObject.DrawString(Text, textFont, new SolidBrush(Color.Brown), 0, 0);
        GraphicsObject.Flush();

       return (ImageObject);
  }

You can call this function with the string you like and than use Bitmap.Save method to save your image. Please note you will need to use namespaces System.Drawing, System.Drawing.Drawing2D, System.Drawing.Text


text:
Q: space before itemize with enumitem I'm writing a report in which I describe numerous algorithms in the following way:
"[algorithm name]
input: [input]
output: [output]
- step 1
...
- step n"

My problem is that I'm also using the enumitem package to reduce the spacing between items and it adds an unwanted space between the output line and the beginning of the itemize.
\documentclass[a4paper,11pt]{article}
\usepackage[shortlabels]{enumitem}

\setlist[itemize]{noitemsep}

\begin{document}

algorithm name
\textsc{input:} input
\textsc{output:} output
\begin{itemize}
\item step 1
\item step 2
\item step 3
\end{itemize}
\end{document}

I tried making the first two lines part of the itemize by putting "input" and "output" as \item labels, but the difference in length makes them "right-aligned" (relatively to each other) and outside the body box.

A: Use nosep:
\documentclass[a4paper,11pt]{article}
\usepackage[shortlabels]{enumitem}

\begin{document}

algorithm name\\
\textsc{input:} input\\
\textsc{output:} output
\begin{itemize}[nosep]
\item step 1
\item step 2
\item step 3
\end{itemize}

\end{document}