text:
Q: Node.js to c++ client: not receiving message from socket.emit I'm trying to communicate between a c++ client and a node.js server. I can send data to the server, but I'm unable to send any messages back to the client. My simple understanding of socket.emit is that it should send a message that's retrievable by calling recv() on the FD_READ message in a basic windows message loop. I might be missing something there.
Here's the relevant client code:
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET)
{
    MessageBox(hwnd, TEXT("3"), TEXT(""), MB_OK | MB_ICONEXCLAMATION);
    return 0;
}

long hostname = inet_addr("192.168.1.70");
target.sin_family = AF_INET;
target.sin_port = htons(server_port_num);
target.sin_addr.s_addr = hostname;

if (connect(s, (SOCKADDR *)&target, sizeof(target)) == SOCKET_ERROR)
{
    MessageBox(hwnd, TEXT("999"), TEXT(""), MB_OK | MB_ICONEXCLAMATION);
    return 0;
}

WSAAsyncSelect(s, hwnd, CUST_MSG, FD_READ | FD_CONNECT | FD_CLOSE);

I send data, which is received and output on the server console:
int nret = send(s, buffer, strlen(buffer), 0);

Then I attempt to send some data back in the same server event that receives the data:
this.socket.on('data', function (buffer) {
    try {
        logger.warn(buffer + "\n");
        socket.emit('message', 'psst, wanna buy some macaroni?');
        //that.messageHandler(that, buffer);
    } catch (err) {
        logger.warn('Protocol ' + err + ' ' + that.socket.remoteAddress);
        that.dispose();
    }
});

I have a message loop, but it doesn't detect a message sent from socket.emit():
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
    if (numBytes > 0) {
        wchar_t buffer[256];
        wsprintfW(buffer, L"%d", numBytes);
        MessageBox(hwnd, buffer, TEXT(""), MB_OK | MB_ICONEXCLAMATION);
    }

    TranslateMessage(&msg);
    DispatchMessage(&msg);

}

//MESSAGE LOOP FUNCTION:
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message) //handle the messages
{
case CUST_MSG: //Is a message being sent?
{
    switch (lParam) //If so, which one is it?
    {
    case FD_ACCEPT:
        MessageBox(hwnd, TEXT("accept"), TEXT(""), MB_OK | MB_ICONEXCLAMATION);
        accept(wParam, NULL, NULL);
        break;
    case FD_CONNECT:
        MessageBox(hwnd, TEXT("connect"), TEXT(""), MB_OK | MB_ICONEXCLAMATION);
        break;
    case FD_READ:
        char buffer[80];
        int byte_num;
        memset(buffer, 0, sizeof(buffer));
        byte_num = recv(wParam, buffer, sizeof(buffer) - 1, 0);
        MessageBox(hwnd, TEXT("READING"), TEXT(""), MB_OK | MB_ICONEXCLAMATION);

        numBytes += byte_num;
        break;
    case FD_CLOSE:
        //MessageBox(hwnd, TEXT("close"), TEXT(""), MB_OK | MB_ICONEXCLAMATION);
        break;
    }
}

The same loop correctly detects messages when I change the program a bit and send data from the client to the client. I've tried messing around bind(), listen(), recv(), but I can't ever get an FD_READ message using node. I've tried with the client and server running on the same computer, as well as different computers on the same local network.

A: To write data to a socket in Node.js, use socket.write().
See https://nodejs.org/api/net.html#net_socket_write_data_encoding_callback


text:
Q: Using lock, Monitor Pulse and Wait to synchronize threads I have read the official documentation and about 25 tutorials, but I'm still struggling with how I might synchronize say, 3 threads with Monitor Pulse() and Wait() methods and using lock objects.
(Yes, I know there are other techniques of synchronization, but this should be doable and it's frustrating me)
Here's my simple "proof of concept" idea I came up with.
Let's say I have three threads, each with a task:

*

*Thread1 runs a task that prints out all integers divisible by 3

*Thread2 runs a task that prints out all integers whose remainder is
1 when divided by 3

*Thread3 runs a task that prints out all integers whose remainder is
2 when divided by 3

I'd like ultimately the output to be:  0,1,2,3,4,5,6,... up to whatever integer limit I might choose but we can say 50 or 100 - it doesn't matter.
I'd like to more fully understand the mechanism of lock vs Monitor.Wait() and Monitor.Pulse() and how they can work together.
If I understand correctly, when a thread encounters a lock(someObject) { ... }, it gains exclusive access to that critical area if it's the first one there.  Any other thread that encounters a lock on the same object is stuck on that line (i.e., lock(someObject)) in its respective code, correct?
If thread 1 has the lock(someObject) calls Monitor.Wait(someObject), then the thread 1 releases the lock and enters the waiting queue, correct?  Then if any other thread (e.g., thread 2) calls Monitor.Pulse(someObject), it would move the thread1 into the ready queue?
No matter what I try, it seems like the code keeps just waiting/blocking infinitely.
I guess my summary questions are:

*

*Do I need more than one lock object to synchronize three threads using Pulse and Wait?

*Where would the Wait and Pulse go in this code?  Inside a lock around the loop that is being used to iterate over the values that we want to print?  Inside a lock, placed only inside a condition (e.g., if (i % 3 == 2)) ?  Etc.

I'm thankful for any helpful input!
UPDATE (8/7/2021):
It turns out making the locks static was necessary given the way I had it set up in a single file. I'm irritated that I didn't notice that earlier, but the online documentation suggested (from the Website of Joe Albahari) was immensely helpful.

A: Here is a relatively simple Wait/PulseAll example:
object locker = new();
int i = 0;
bool finished = false;
Thread[] threads = Enumerable.Range(0, 3).Select(remainder => new Thread(() =>
{
    lock (locker)
    {
        try
        {
            do
            {
                while (!finished && i % 3 != remainder) Monitor.Wait(locker);
                if (finished) break;
                Console.WriteLine($"Worker #{remainder} produced {i}");
                Monitor.PulseAll(locker);
            } while (++i < 20);
        }
        finally { finished = true; Monitor.PulseAll(locker); }
    }
})).ToArray();
Array.ForEach(threads, t => t.Start());
Array.ForEach(threads, t => t.Join());

Three worker threads are created, identified by the remainder argument, that takes the values 0, 1, and 2. Each worker is responsible for producing numbers whose module 3 equals the remainder.
The int i is the loop variable, and the bool finished is a flag that becomes true when any worker is finished. This flag ensures that in case of an error in any worker, the other workers will not deadlock.
Each worker enters a critical section that encloses a do-while loop, which is the number-producing and incrementing loop. Before emitting a number it has to wait for its turn. Its turn comes when the i % 3 == remainder. Otherwise it Waits. When its turn comes, it emits the number, it increments the i, it Pulses all waiting workers, and continues with the next iteration. When the loop ends, it Pulses one last time before releasing the lock.
The PulseAll has been chosen instead of the Pulse, because we don't know whether the next worker in the waiting queue is the correct one for the current i, so we just wake them all.
Output:
Worker #0 produced 0
Worker #1 produced 1
Worker #2 produced 2
Worker #0 produced 3
Worker #1 produced 4
Worker #2 produced 5
Worker #0 produced 6
Worker #1 produced 7
Worker #2 produced 8
Worker #0 produced 9
Worker #1 produced 10
Worker #2 produced 11
Worker #0 produced 12
Worker #1 produced 13
Worker #2 produced 14
Worker #0 produced 15
Worker #1 produced 16
Worker #2 produced 17
Worker #0 produced 18
Worker #1 produced 19

Try it on fiddle.

Note: the example in the 1st revision of this answer was problematic, because it was creating an initial busy-wait phase until all workers were ready.

redpajama_set_name: RedPajamaStackExchange


text:
Q: can't move grid to the center of page using flexbox how can i move grid to the center of the page? I managed to move it horizontaly to the center using display:grid on grid div but i cant move it vertically. please explain why this is the case, also why flexbox justify-content is not working as well

for (let i = 0; i < 16; i++) {
  let row = document.createElement('div');
  row.className = 'row';
  for (let j = 0; j < 16; j++) {
    let box = document.createElement('div');
    box.className = 'box';
    row.appendChild(box);
  }
  document.getElementById('grid').appendChild(row);
}
#container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

#grid {
  display: grid;
  align-items: center;
}

.box {
  border: black 1px solid;
  width: 18px;
  height: 18px;
  margin: 0 auto;
  margin-top: 0;
  display: inline-block;
  float: left;
}

.row {
  display: block;
  float: left;
  width: 100%;
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Etch-a-Sketch</title>
    <link rel="stylesheet" href="style.css" />

Etch-a-Sketch

A: You need to set the body min-height to 100vh to take the full-screen height, and the #container element height to 100% to take the full body height.

for (let i = 0; i < 16; i++) {
  let row = document.createElement('div');
  row.className = 'row';
  for (let j = 0; j < 16; j++) {
    let box = document.createElement('div');
    box.className = 'box';
    row.appendChild(box);
  }
  document.getElementById('grid').appendChild(row);
}
body {
  height: 100vh;
}

#container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

#grid {
  display: grid;
  align-items: center;
}

.box {
  border: black 1px solid;
  width: 18px;
  height: 18px;
  margin: 0 auto;
  margin-top: 0;
  display: inline-block;
  float: left;
}

.row {
  display: block;
  float: left;
  width: 100%;
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Etch-a-Sketch</title>
    <link rel="stylesheet" href="style.css" />

Etch-a-Sketch


text:
Q: Inheritance in Slim template language With PHP using Twig I can do something like this:
layout.twig

{% block content %}{% endblock %}

form.twig
{% extends "layout.twig" %}
{% block content %}

{% block form %}{% endblock %}

{% endblock %}

login.twig
{% extends form %}
{% block form %}
<form>
    <input type="text" name="email" />
    <input type="submit">
</form>
{% endblock %}

This way I have a layout for all pages, a layout for pages with forms and login page.
But with Slim I can specify only main layout that is parent for all templates:
layout.slim
html
  body ==yield

and special layouts for every page on my site:
login.slim
div.form
  form
    input type="text" name="email"
    input type="submit"

Is there a simple way to realize Twig-like inheritance with more than one level in Slim?

A: It looks that I found the solution for Slim with Sinatra:
layout.slim
html
  body
    == yield

form.slim
== slim :layout
  div.form
    == yield

login.slim
== slim :form
  form
    input type="text" name="email"
    input type="submit"

A: I believe that in Rails it doesn't exist something like template inheritance, but I believe that it isn't necessary with yield and content_for methods.
For example, you can have a _form.html.slim layout:
.form
  = yield

A _login.html.slim partial:
form
  input type="text" name="email"
  input type="submit"

And when you want to display a login with the form layout, you should do something like:
= render partial: "login", layout: "form"

A: login.html.slim
= render layout: 'form' do
  form
    input type="text" name="email"
    input type="submit"


text:
Q: Is inheritance a special case of embedded struct in Go? In Go, is type Txt string simply a shortcut for type Txt struct {string}?

A: The answers to all your questions is a loud "No!".

*

*Embedding a string into a struct is basically a useless example of embedding as string has no methods which could get promoted to the embedding type.

*The construct type Txt string defines a new type named Txt and the underlying type is a string. Txt has different method set as it is a different type. But as its underlying type is string you may freely type convert them.

*type T string is not a shortcut for type S struct { string }, e.g. you cannot do
t := T{"foo"}, only t := T("foo") works and for S it is the other way around.

*Embedding has absolutely no relation to inheritance. These are two different things. Mimicking inheritance with embedding is doomed to fail as you cannot do inheritance in Go. (This is a general advice, it is a very useful advice; but some specific inheritance problems might be doable with embedding. Just forget about inheritance and you will be happier.)

*Embedding is useful if two types have common data and methods in which case embedding provides some nice syntactic sugar: Instead of type T struct { c common; r rest }; t := T{...}; t.common.method() you can do type T struct { common; r rest }; t := T{...}; t.method() which saves typing but is basically the same code. Package testing contains nice examples.

A: No
type Txt string
type StringStruct struct {
    string
}

func main() {
    var txt Txt = "abc"
    fmt.Println(len(txt))

    var str string = "abc"
    fmt.Println(len(str))

    // Uncomment me to get a compiler error!
    /* var ss StringStruct = StringStruct{"abc"}
    fmt.Println(len(ss)) */
}

You can't call len on the embedded one. You have to call len(ss.string), thus it's safe to say that type Txt string is not shorthand for type Txt struct{ string }.

A: No,string is a native type, like int, uint, float, etc.
Internally it's a slice of sorts.
Quoting http://blog.golang.org/strings

In Go, a string is in effect a read-only slice of bytes.
It's important to state right up front that a string holds arbitrary
bytes. It is not required to hold Unicode text, UTF-8 text, or any
other predefined format. As far as the content of a string is
concerned, it is exactly equivalent to a slice of bytes.


text:
Q: Uncheck radio button if it is not visible The first set of buttons toggle the second set.
However if someone checks rbtn1 and then checks rbtn3 but then changes their mind clicks rbtn2 but leaves rbtn4 blank,  rbtn3 is still clicked even though it isn't visible.  I'm trying to uncheck the second set of ratio buttons if there is a change in the first set but the code I have in the onclick has no effect.  Can code like that be in the onclick?
  <asp:RadioButton ID="rbtn1" onclick="$('#spanOne').show(); onclick="$('#spanTwo').hide();
  $('rbtn3').checked = false; "/>

  <asp:RadioButton ID="rbtn2" onclick="$('#spanOne').hide(); onclick="$('#spanTwo').show();
  $('rbtn4').checked = false;"/>

<asp:RadioButton ID="rbtn3" />

<asp:RadioButton ID="rbtn4" />

A: Please delegate - wrap the radios in a static container.
Also give all the radios the same name or they won't be radios.
const rads = $("#staticContainer input[type=radio]"); // or [name=rbtn] if you give them that name
$("#staticContainer").on("click","input[type=radio]",function() {
  $(rads).each(function() {
    if (!$(this).is("visible")) $(this).val("")
  })
})

A: If you define asp controls it requires runat attribute for that control. If control have runat the id will be generated dynamically . To access that dynamic id you can write "[id$={your acual control name}]" . If you treat the rbtn1,rbtn2 as group its better to add GroupName to select only one out of these two. Finally use the below code as a solution.
<asp:RadioButton ID="rbtn1" GroupName="firstset" Text="rbtn1" onclick="$('#spanOne').show();$('#spanTwo').hide(); $('[id$=rbtn3]').prop( 'checked', false);" runat="server" />

<asp:RadioButton ID="rbtn2" GroupName="firstset" Text="rbtn2" onclick="$('#spanOne').hide(); $('#spanTwo').show(); $('[id$=rbtn4]').prop( 'checked', false);" runat="server" />

    <asp:RadioButton ID="rbtn3" runat="server" Text="rbtn3" />

    <asp:RadioButton ID="rbtn4" Text="rbtn4" runat="server" />


text:
Q: Calculating Arc Hyperbolic CoSecant faster than using a standard power series I have used the standard Power-Series to calculate Arc Hyperbolic Co-Secant trig function. But as with my other posts before, it is very slow. Here is the standard Power-Series, taken from https://en.wikipedia.org/wiki/Inverse_hyperbolic_functions#Series_expansions
$$ \operatorname{arcsch} x = \operatorname{arsinh} \frac1x  = x^{-1} - \left( \frac {1} {2} \right) \frac {x^{-3}} {3} + \left( \frac {1 \cdot 3} {2 \cdot 4} \right)  \frac {x^{-5}} {5}  - \left( \frac {1 \cdot 3 \cdot 5} {2 \cdot 4 \cdot 6} \right)  \frac {x^{-7}} {7} \pm\cdots \\
                      = \sum_{n=0}^\infty \left( \frac {(-1)^n(2n)!} {2^{2n}(n!)^2} \right) \frac {x^{-(2n+1)}} {2n+1} , \qquad \left| x \right| > 1 $$
I have used a different form to speed it up, which it did not.
$$ \operatorname{arcsch} x = \frac {1}{x} - \left( \frac {1} {2} \right) \frac {1} {3 x^{3}}+ \left( \frac {1 \cdot 3} {2 \cdot 4} \right)  \frac{1} {5x^{5}}  - \left( \frac {1 \cdot 3 \cdot 5} {2 \cdot 4 \cdot 6} \right)  \frac {1} {7x^{7}} \pm\cdots \\
                      = \sum_{n=0}^\infty \left( \frac {(-1)^n(2n)!} {2^{2n}(n!)^2} \right) \frac {x^{-(2n+1)}} {2n+1} , \qquad \left| x \right| > 1 $$
But it is easier to reproduce in my calculator program. The part that is taking so long are terms
$$ \left ( \frac {1} {7x^{7}} \right ) $$
and higher. The time spent dividing  $$  {7x^{7}} $$ into $$ 1 $$  is huge. At this iteration, it takes about 15 seconds. The next ones just keep growing, using more time.
And yes, this post is just my last post Calculating Arc Hyperbolic CoTangent faster than using a standard power series. Here, 2 persons showed me the Horner's method and a programming procedure. It was really fast, compared to what I was using before.
I am hoping that there is a Horner-like form that a person, you people, can show me. I have read the Wiki page that explains the Horner's method, but that does not mean I can create the method.
Thank you very much for your time.

A: Fundamentally, Horner form involves nothing more than convenient parenthesization and factoring to avoid re-powering the variable with each term. For instance,
$$\begin{align}
a_0 + a_1 z + a_2 z^2 + a_3 z^3 + a_4 z^4 &\quad\to\quad
a_0 + z\left(a_1 + a_2 z + a_3 z^2  + a_4 z^3 \right) \\
&\quad\to\quad
a_0 + z\left(a_1 + z \left( a_2 + a_3 z + a_4 z^2 \right)\; \right) \\
&\quad\to\quad
a_0 + z\left(a_1 + z \left( a_2 + z \left( a_3 + a_4 z \right)\; \right)\; \right) \\
\end{align} \tag{1}$$
That's all there is to it, really, although sometimes (especially with power series) we can exploit the specific nature of the coefficients.
So, a first pass at the hyperbolic arccosecant series would look like this (in stages):
$$\begin{align}
\operatorname{arcsch}(x) &= x^{-1}\left(\;1
- \frac12\cdot\frac13 x^{-2}
+ \frac{1\cdot 3}{2\cdot 4}\cdot \frac15 x^{-4}
- \frac{1\cdot 3\cdot 5}{2\cdot 4\cdot 6}\cdot\frac17 x^{-6}
+ \cdots \right. \tag{2a}\\[4pt]
&= x^{-1}\left(\;1
+ x^{-2}\left(- \frac12\cdot\frac13
+ \frac{1\cdot 3}{2\cdot 4}\cdot \frac15 x^{-2}
- \frac{1\cdot 3\cdot 5}{2\cdot 4\cdot 6}\cdot\frac17 x^{-4}
+ \cdots \right.\right. \tag{2b}\\[4pt]
&= x^{-1}\left(\;1
+ x^{-2}\left(- \frac12\cdot\frac13
+ x^{-2}\left(\frac{1\cdot 3}{2\cdot 4}\cdot \frac15
- \frac{1\cdot 3\cdot 5}{2\cdot 4\cdot 6}\cdot\frac17 x^{-2}
+ \cdots \right.\right.\right. \tag{2c}\\[4pt]
&= x^{-1}\left(\;1
+ x^{-2}\left(- \frac12\cdot\frac13
+ x^{-2}\left(\frac{1\cdot 3}{2\cdot 4}\cdot \frac15
+ x^{-2}\left(- \frac{1\cdot 3\cdot 5}{2\cdot 4\cdot 6}\cdot\frac17
+ \cdots \right.\right.\right.\right. \tag{2d}
\end{align}$$
All I did was add parentheses and pull out powers of $x$ as I went along. I made no changes to coefficients.
We can clean this up a little, though. First, define $y := 1/x$ and $z:=1/x^2$ (which you can compute once and store), so that we have
$$\operatorname{arcsch}(x) = y\left(\;1
+ z\left(-\frac12\cdot\frac13
+ z\left(\frac{1\cdot 3}{2\cdot 4}\cdot \frac15
+ z\left(-\frac{1\cdot 3\cdot 5}{2\cdot 4\cdot 6}\cdot\frac17
+ \cdots\right.\right.\right.\right. \tag{3}$$
Now, notice that the coefficients are accumulating factors. We can avoid re-calculating them by factoring-out at appropriate levels. Again doing this in stages ...
$$\begin{align}
\operatorname{arcsch}(x) &= y\left(\;1
+ z\cdot \frac12 \left(-\frac13
+ z\left(\frac{3}{4}\cdot \frac15
- z\left(\frac{3\cdot 5}{4\cdot 6}\cdot\frac17
+ \cdots\right.\right.\right.\right. \tag{4a} \\[4pt]
&= y\left(\;1
+ z\cdot \frac12 \left(-\frac13
+ z\cdot \frac34 \left(\frac15
+ z\left(-\frac56\cdot\frac17
+ \cdots\right.\right.\right.\right. \tag{4b} \\[4pt]
&= y\left(\;1
+ z\cdot \frac12 \left(-\frac13
+ z\cdot \frac34 \left(\frac15
+ z\cdot \frac56 \left(-\frac17
+ \cdots\right.\right.\right.\right. \tag{4c}
\end{align}$$
We can even factor-out negatives as we go, to get
$$\begin{align}
\operatorname{arcsch}(x) &= y\left(\;1
- z\cdot \frac12 \left(\frac13
- z\cdot \frac34 \left(\frac15
- z\cdot \frac56 \left(\frac17
- \cdots\right.\right.\right.\right. \tag{5}
\end{align}$$
I'll leave it to OP to implement the corresponding programmatic computational algorithm.
In any case, conversion to Horner form is entirely mechanical, at least at the first-pass level. Optimizing for factorable coefficients is relatively straightforward, as well, although it isn't always possible. (Factorials and double-factorials are well-suited to this.) For practice, OP can revisit his past fast-calculation questions, convert each series to Horner-form on his own, and then compare to answers and/or comments he's received. And, of course, he should be able to apply this procedure to new series, too.


text:
Q: item.setTitle(a_variable) method displays nothing I'm trying to display the name of my current user inside an menu item, I am getting the username like this
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
DatabaseReference name =
ref.child("Users").child(mCurrentUser.getUid()).child("name");

name.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String username = dataSnapshot.getValue(String.class);

username2 = username; //should i be doing this? how can i pass username
                      //directly to other other methods in the code?

}

and it works fine because i have tested it with toasts, however when i pass username2 to the setTitle method it does not display it. If i pass anything else inside it, it works just fine. If i pass username2 + something else it displays nullsomething else
NavigationView navigationView = (NavigationView)
findViewById(R.id.navmenuffs);
Menu menu = navigationView.getMenu();
MenuItem nav_profile = menu.findItem(R.id.nav_profile);
nav_profile.setTitle(username2);

username2 is just a String I have declared public so i can use username in other methods


text:
Q: How to get URLs for all products in woocommerce store in csv? I am trying to links / URLs for all products listed on my woo-commerce store. I tried export plugins & some SQL queries but didnt got it. Can anyone help me?
Eg. For Product- Iphone 13 Pro
I need: www.example.com/shop/iphone-13-pro
There are more than one thousand products on store.


text:
Q: Could the metric be a tensor product of a 4-vector with itself? I am really keen on the idea of geometrizing all of physics using the spacetime manifold, so I was happy to find this paper:
https://doi.org/10.1088/1742-6596/1956/1/012017
As I understand it, they demonstrate that Maxwell's equations are a consequence of the vacuum Einstein equation, IF you suppose that the following relation between the metric and the electromagnetic 4-potential:
$g_{\mu\nu} = A_{\mu}A_{\nu}$
They further identify 4-current with $\nabla_{\mu}\nabla^{\nu}A_{\nu}$ and explain how this relates to Weyl curvature.
Now I am eager to subscribe to a theory like this, but I'm not convinced that it is valid to build the metric from a self-tensor-product like that.  My reasoning is this: take a local orthonormal coordinate frame in which the $A$ 4-vector lies along the $x^0$ direction.  Then $A_1$, $A_2$, and $A_3$ are all zero, so when you take the tensor product, the resulting metric will only have one non-zero component, ie. it will be degenerate.  Maybe if it were only one point that would be fine, but as I see it this will happen at every point in the spacetime.
Am I missing something?  In general the authors seem to be well versed in tensor calculus and so forth, and it is certainly an alluring hypothesis.

A: OP is correct, this object, $A_μA_ν$, could not be the pseudo-Riemmanian  metric of the usual formulation of electromagnetism in special or general relativity. However, I would not be so quick to completely dismiss the theory without studying it in more details.
First, within the more established way of geometrization of electomagnetism, Kaluza–Klein theory, the object $A_μA_ν$ does crop up as a part of the metric. Specifically: the 5-dimensional metric when restricted to 4-dimensions is not the inverse of "inverse 5-dimensional metric" restricted in turn to 4-dimensions, and the difference is proportional to $A_μA_ν$.
Second, geometrization of Newtonian gravitation, Newton–Cartan theory uses rank 1 temporal metric, $t_{μν}$ to measure time/temporal lengths. This object could be thought of as a tensor product of covector with itself $t_{μν}=τ_μ τ_ν$. The second metric of the Newton–Cartan theory is rank-3 spatial metric to measure distances/spatial lengths.
So, without reading the paper I would not be surprised that one can indeed use $A_μA_ν$ as some sort of a metric in some geometric formulation of electromagnetism.

I am really keen on the idea of geometrizing all of physics using the spacetime manifold …

As an advise, I would recommend to familiarize yourself with more traditional routes of geometrizing physics (such as mentioned above Kaluza–Klein and Newton–Cartan theories) before studying more radical/lesser known ideas.

A: No, here's why. The outer product of a vector with itself is a projection operator with a scaling of the vector's Euclidian length squared, and it projects down to the space parallel to the vector. It is not, therefore, invertible. The metric tensor must be invertible, so a single outer product of a vector with itself cannot be the metric tensor.
You could produce a metric tensor by summing the outer product of 4 linearly independent 4-vector fields with themselves, but that is basically the vielbein formalism.


text:
Q: Why I can't see New project Web Template for Visual Studio 2015 preview? I have installed Visual Studio 2015 preview successfully. Unfortunately, I am not getting New project Templates to create Web Apps (asp.net). I am looking under C# -> Web.
Please note that I tried this locally and on an Azure machine which is having Visual Studio 2015.

A: I found the solution of the issue, stated above. I am sharing here, so that others can get benefited, who might be wondering for the solution of similar issues.
I resolved it after re-installing/Update the setup. Here are the step(s):
-Restart the setup for VS2015 Preview
-Selected the required components to install

After these steps, I received the desired templates.
P.S. Whenever anyone is installing VS2015 Preview first time, should Select the features under 'Optional features to install' to get the desired installation.

A: I had this issue with the Web templates not showing up in Visual Studio 2015 Update 2.  I uninstalled and reinstalled "Microsoft Web Developer Tools" from the update menu, tried repair, installed various related templates, and it wouldn't come back.
I know it's normally in the Visual Studio 2015 installer, but for me I finally got it back by clicking and installing whatever the ASP.Net 4.6 "Install For Windows" link does at https://get.asp.net/.  No idea why, hope it helps someone.

A: I was also facing the same issue. I first installed the VS2015 community edition and then uninstalled it and installed the VS2015 Professional edition. Professional edition didn't had any Web Templates.
Issue was resolved by installing DotNetCore.1.0.0-VS2015Tools.Preview2.
I faced some issue while installing the DotNetCore.1.0.0-VS2015Tools.Preview2, which was resolved by following the steps mentioned here.


text:
Q: Singleton property access in objective C I'm using a standard, modern singleton class with a singleton holding a CTFontRef, like so:
@interface MySingleton : NSObject {
    CTFontRef paintingFont;
}

@property (readonly) CTFontRef paintingFont;

@end

@implementation MySingleton

+ (MySingleton*)sharedInstance
{
    static dispatch_once_t once;
    static MySingleton *sharedInstance;
    dispatch_once(&once, ^{
        sharedInstance = [[self alloc] init];

        //NB
        sharedInstance->paintingFont =
           CTFontCreateWithName(CFSTR("Helvetica"), 80.0, nil);
    });
   return sharedInstance;
}

@end

Then elsewhere I call [[MySingleton sharedinstance] paintingFont].
However, this call returns nil until I insert an underscore before paintingFont like so:
        sharedInstance->_paintingFont =
           CTFontCreateWithName(CFSTR("Helvetica"), 80.0, nil);

Why is this?  Shouldn't the compiler require me to include the underscore?  If not what is the  purpose of the earlier version?  And where did this underscore come in?  I never declared the property with an underscore to begin with, I just see these seemingly random insertions of them into variable names in the debugger window.

A: Since Xcode 4.4, when you declare a @property, the compiler will automatically create an ivar for you and @synthesize the accessor methods. The default ivar is one with an underscore.
Using the -> syntax you access ivars directly and not the property. So, in your sharedInstance method you set your own ivar (without the underscore). However when you later try to access it, you use the [ ] which will use the automatically synthesized getter method to access your property (and the automatically generated ivar with an underscore).
You should use the . notation instead of the -> to access the property. Or simply use the automatically generated ivar called _paintingFont.
You can also make a property readwrite in your implementation file by adding the code below. This will allow you to use the dot syntax in your implementation to set the property, but still leave it readonly for other classes.
@interface MySingleton ()
@property (readwrite) CTFontRef paintingFont;
@end

If you want a different ivar, you can use @synthesize to override it. In both cases, you don't have to declare an ivar anymore.
@implementation MySingleton
@synthesize paintingFont;
....
@end

A: This is because in declaring a property paintingFont the Obj C compiler creates an instance variable _paintingFont.
In general the setting of a property/variable can either be done by

*

*The instance as in your solution sharedInstance->_paintingFont = ...

*Using the property and . notation sharedInstance.paintingFont = .... This calls the generated method setPaintingFont which then assigns to the instance variable.

However in this case the property is readonly so method 2 cannot be used.


text:
Q: Problem with ffplay from webcam stream using complex filters I'm trying to stream video from a webcam (at /dev/video2) through ffplay to scale and recolor it, add some text, and then reduce the number of colors with palettes. I don't get any errors, but running the ffplay command:
ffplay -i /dev/video2 -vf "hflip,\
  colorbalance=\
    rs=0.4:\
    bs=-0.4\
  ,\
  scale=\
    trunc(iw/8):\
    trunc(ih/8)\
  ,\
  drawtext=\
    text=\
      'efelbar':\
      fontcolor=white:\
      fontsize=10:\
      box=1:\
      boxcolor=black:\
      boxborderw=5:\
      x=(w-text_w)/2:\
      y=(h-text_h)/2\
  ,\
  split[s0][s1];\
  [s0]palettegen=\
    max_colors=16\
  [p];\
  [s1][p]paletteuse"

seems to stall, and fails to produce video output.
Running the simpler command ffplay -i /dev/video2 -vf "split[s0][s1];[s0]palettegen=max_colors=16[p];[s1][p]paletteuse", which takes a stream from a webcam and (should) reduce the number of colors, results in it just sitting there without showing the actual output stream. This might just be a performance issue because I'm on older hardware, but it doesn't give output relfective of that.
The output of that command is as follows:
ffplay version n5.0 Copyright (c) 2003-2022 the FFmpeg developers
  built with gcc 11.2.0 (GCC)
  configuration: --prefix=/usr --disable-debug --disable-static --disable-stripping --enable-amf --enable-avisynth --enable-cuda-llvm --enable-lto --enable-fontconfig --enable-gmp --enable-gnutls --enable-gpl --enable-ladspa --enable-libaom --enable-libass --enable-libbluray --enable-libdav1d --enable-libdrm --enable-libfreetype --enable-libfribidi --enable-libgsm --enable-libiec61883 --enable-libjack --enable-libmfx --enable-libmodplug --enable-libmp3lame --enable-libopencore_amrnb --enable-libopencore_amrwb --enable-libopenjpeg --enable-libopus --enable-libpulse --enable-librav1e --enable-librsvg --enable-libsoxr --enable-libspeex --enable-libsrt --enable-libssh --enable-libsvtav1 --enable-libtheora --enable-libv4l2 --enable-libvidstab --enable-libvmaf --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxcb --enable-libxml2 --enable-libxvid --enable-libzimg --enable-nvdec --enable-nvenc --enable-shared --enable-version3
  libavutil      57. 17.100 / 57. 17.100
  libavcodec     59. 18.100 / 59. 18.100
  libavformat    59. 16.100 / 59. 16.100
  libavdevice    59.  4.100 / 59.  4.100
  libavfilter     8. 24.100 /  8. 24.100
  libswscale      6.  4.100 /  6.  4.100
  libswresample   4.  3.100 /  4.  3.100
  libpostproc    56.  3.100 / 56.  3.100
Input #0, video4linux2,v4l2, from '/dev/video2':B sq=    0B f=0/0
  Duration: N/A, start: 254970.739108, bitrate: 147456 kb/s
  Stream #0:0: Video: rawvideo (YUY2 / 0x32595559), yuyv422, 640x480, 147456 kb/s, 30 fps, 30 tbr, 1000k tbn

I'm running this on a thinkpad t420s, so I definitely wouldn't be surprised if my laptop just can't process video that quickly. If that is the case, suggestions for optimizations would be great!

A: palettegen, by default, computes a global palette for the entire stream. For a live input, that can only happen at the end of the input. So paletteuse won't be fed any frames till then.
You have to tell palettegen to generate a palette per frame.
palettegen=max_colors=16:stats_mode=single


text:
Q: Form filters failing fast and furious As a precursor, I am a newbie to Access and Stackoverflow, so any errors in context, statements, verbiage, etc., are purely unintentional. I have a good heart, good intentions, and mean no offense.
I have 5 forms in my unsplit, DAO 2013 Access db that all use identical coding regarding this specific issue. On opening, all forms are set to open to a new, blank record.
When a customer record is searched and the record is opened, all forms have a subform container which is tabbed and contains the bulk of the customer's record information.
On 1 of these forms, the navigation bar states "no filter" and shows the customer's record information in the subform container. Regardless of the filter state, the customer record information should show, so this is what should happen.
On 4 of these forms, the form navigation bar states "Unfiltered" and displays none of the customer's record information in the subform container. If I click the filter button on the bottom of the form (or the filter toggle in the ribbon) twice the customer record information will display on the second click - and the form moves to "Filtered" and then again "Unfiltered". All Subforms then behave normally in the second "Unfiltered" state.
There are -0- manual VBA filters (i.e., me.customer.filter = false) currently set in my db, -0- queries used to find records - everything is built using VBA to locate records.
End users will not be able to use the filter controls once the db goes live. This is my final bug. I appreciate any suggestions or solutions that may be offered.
These are the solutions I have attempted:

*

*used Me.FilterOn = False and Me.Filter = "" to turn off all filters on the 4 affected forms on opening, but this caused the filter toggle to become unavailable and the subform container to not display any customer record information on the 4 forms

*used Me.FilterOn = False and Me.Filter = "" to turn off all filters on the 4 affected forms on current, but this caused the filter toggle to become unavailable and the subform container to not display any customer record information on the 4 forms

*used VBA above to turn off all filters on all 5 forms on opening, this caused the filter toggle to become unavailable and the subform container to not display any customer record information on all 5 forms

*decompiled, repaired/compressed, and rebuilt into a new db a couple of times

*using VBA to force the unfiltered/filtered/unfiltered state to occur on opening, but subforms interfered and my deadline doesn't leave me time to figure it out.

*attempting to base everything off queries instead of tables, but as these subforms must be editable and the queries must be unique, this was not an option

*compared the one form against the others to see what is different vs. what is the same on opening/searching. in this, they are identical.
As a final wrap up, if anyone would like to look at my setup, just let me know, I have a stripped down version ready. I did not post any code here as I'm not sure what you'll want to look at.
Thank you again,
Trapper

A: After a lot of searching, I found the cause of your problem.
Form 'sfSiteAnalyst' has the property 'Data Entry' set to Yes. Change to No and it works just fine.
Just comparing the 3,889 properties for that form and controls led to finding 58 that were different -- but the other differences were meaningless (top, border, etc.)
Also, I notice there are many places where you issue a 'DoCmd.Save acForm, ...' that caused me problems with testing. Are they really necessary?


text:
Q: Wald's General Relativity, section 6.3 Page 144 I cannot understand how he reaches the conclusion in equation 6.3.36 and 6.3.37; even the terminology is somewhat confusing. This is a problem of bending of light under gravitational field.
This is what he mentioned in the page: we have, for Schwarzschild metric,
\begin{equation}
\frac{d\phi}{dr}=\frac{L}{r^2}\left[E^2-\frac{L^2}{r^3}(r-2M)\right]^{-1/2}.\tag{6.3.35}
\end{equation}
We wish to find $\Delta\phi$ of light ray in Schwarzschild geometry, traversing a path near the spherical star.
In order to not be captured, the impact parameter $b$ must be greater than the critical impact parameter $$b_c=3^{3/2}M.\tag{6.3.33}$$ In that case, the orbit of the light ray will have a "turning point" at the largest radius, $R_0$, for which $V(R_0)=E^2/2$, i.e. at the largest root of $$R_0^3-b^2(R_0-2M)=0,\tag{6.3.36}$$ which is
\begin{equation}
R_0=\frac{2b}{\sqrt{3}}\cos\left[\frac{1}{3}\cos^{-1}\left(-\frac{b_c}{b}\right)\right].\tag{6.3.37}
\end{equation}
I am lost at this point:

*

*What does he mean by "largest radius" $R_0$?

*How does he suddenly make the cosine conclusion?

I could understand the rest of this section but these two remarks are too obscure to me. Any help is greatly appreciated.

A: Let's start with the Schwarzschild geodesic
$$
\frac{1}{2}\dot{r}^2 + V(r) = \frac{1}{2}E^2,
$$
with $V(r)$ the effective potential
$$
V(r) = \frac{L^2}{2r^3}(r-2M).
$$
Consider light rays that are deflected in the Schwarzschild geometry, i.e. photons that start at a large distance ($r$ large, $\dot{r}<0$), propagate until they reach a distance of closest approach at coordinate $r=R_0$ (where $\dot{r}=0$), and propagate outward again. Therefore, $R_0$ is a solution of the equation
$$
\frac{1}{2}E^2 = V(r) = \frac{L^2}{2r^3}(r-2M),
$$
or
$$
r^3 -b^2(r-2M) =0,
$$
with $b=L/E$. If $b<b_c = 3^{3/2}M$ then this equation has no positive roots, which means that the photon will continue to spiral towards the centre. If $b>b_c$, the equation has two positive roots and one unphysical negative root. We're only interested in the largest of the positive roots, since we started at a very large radius ($r \gg R_0$) and the photons will never reach any distance smaller than $R_0$.
The solution
$$
R_0 = \frac{2b}{\sqrt{3}}\cos\left[\frac{1}{3}\cos^{-1}(-b_c/b)\right]
$$
can be verified by using $4\cos^3x =\cos 3x + 3\cos x$. One can also verify that it is the largest root, since $b>b_c$ and
$$
\cos^{-1}(-b_c/b) < \cos^{-1}(-1) = \pi\\
\cos\left[\frac{1}{3}\cos^{-1}(-b_c/b)\right] > \cos(\pi/3) = 1/2\\
R_0 > \frac{b}{\sqrt{3}} > \frac{b_c}{\sqrt{3}} = 3M,
$$
and $3M$ is the coordinate where $V(r)$ has a maximum. The other root (let's call it $R_1$) will lie between $2M< R_1 < 3M$. This root applies to photons that start at very small radii $(2M < r < R_1)$ and try to escape, but cannot move beyond the turning point $R_1$, after which they spiral towards the centre.

A: I don't know why he uses the name "largest radius" but physically it is the radius of closest approach, which is the minimum distance to the center of the star at the point of reflection of the orbit. Since it is a point of reflection $\dot{r}=0$ in the equation 6.3.14
$$
\frac{1}{2}\dot{r}^2 + V_{\text{eff}}(r) = \frac{1}{2}\dot{r}^2 + \frac{L^2}{2r^2} \left( 1 - \frac{2M}{r}\right) = \frac{E^2}{2}
$$
this gives $V_{\text{eff}} (R_o) = E^2/R$ which is
$$
\frac{L^2}{2R_o^2} \left( 1 - \frac{2M}{R_o}\right) = \frac{E^2}{2}
$$
which is just
\begin{align}
&R_o^3 - b^2 (R_o - 2M) = 0 \\
&R_o^3 - b^2 (R_o - \frac{2b_c}{3\sqrt{3}}) = 0 \\
&4x^3 - 3x =- \frac{b_c}{b}
\end{align}
where $x \equiv \frac{\sqrt{3}R_o}{2b}$. Now Wald wants to flex his algebraic muscles so remember a formula that says $4\text{cos}^3\theta - 3\text{cos }\theta = \text{cos }3\theta$ so defining $\text{cos }\theta\equiv x$ gives $\theta = \frac{1}{3}\text{cos}^{-1}(-b_c/b)$ or finally
$$
x = \text{cos }\left(\frac{1}{3}\text{cos}^{-1}\frac{-b_c}{b}\right)\qquad\Rightarrow\qquad R_o = \frac{2b}{\sqrt{3}} \text{cos }\left(\frac{1}{3}\text{cos}^{-1}\frac{-b_c}{b}\right)
$$


text:
Q: Jsoup and cookie - I can't logg to everything subsite I've issue about keeping cookie in Jsoup. I logged on main site through JSON, here is everything fine. I've problem when I want go to next subsite, I put the same cookie and this isn't work. In my console I can see that I have html site before logg. Any ideas what should I change?
public class MyBenefit {
    final static String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15";
    final static String LOGIN_FORM_URL = "https://system.mybenefit.pl/mybenefit/login.html";
    final static String LOGIN_ACTION_URL = "https://system.mybenefit.pl/mybenefit/login/by_email";
    final static String URL = "https://system.mybenefit.pl/mybenefit/benefit-login-dispatcher.html";
    final static String URLQUERY = "https://system.mybenefit.pl/mybenefit/global-search.html?query=";
    final static String USERNAME = "xxx";
    final static String PASSWORD = "xxx";

    public static void main(String[] args) {

        try {
            Connection.Response loginForm = Jsoup.connect(LOGIN_FORM_URL)
                    .method(Connection.Method.GET)
                    .userAgent(USER_AGENT)
                    .execute();

            //here I create json, because json is required to login
            JsonBuilderFactory jsonBuilderFactory = Json.createBuilderFactory(Collections.EMPTY_MAP);
            JsonObject jsonObject = jsonBuilderFactory.createObjectBuilder()
                    .add("password", PASSWORD)
                    .add("captcha", "")
                    .add("lang", "pl")
                    .add("email", USERNAME).build();

            HashMap<String, String> cookies = new HashMap<>(loginForm.cookies());

            Connection.Response homePage = Jsoup.connect(LOGIN_ACTION_URL)
                    .cookies(cookies)
                    .ignoreContentType(true)
                    .requestBody(jsonObject.toString())
                    .method(Connection.Method.POST)
                    .userAgent(USER_AGENT)
                    .execute();

            //here I get cookie after logg
            String sessionID = homePage.cookie("BENEFIT_SESSIONID");

            //this connection is working
            Connection.Response afterLogg = Jsoup.connect(URL)
                    .cookie("BENEFIT_SESSIONID", sessionID)
                    .execute();

            Document document = afterLogg.parse();

            //this connection is NOT workingg good, I am not logged on website
            Connection.Response test = Jsoup.connect(URLQUERY)
                    .cookie("BENEFIT_SESSIONID", sessionID)
                    .execute();

            System.out.println(test.parse());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

I checked on developers tools in Firefox, and page URL and page URLQUERY has the same cookie. I send some pictures about this. cookie after logg on URL cookie on URLQUERY


text:
Q: Multicolumn order by a tuple Lets supose I have a tabla A like:

bisac1
bisac2
bisac3
desire

x
y
z
10

y
z
x
8

z
y
x
6

x
y
p
20

r
y
z
13

x
s
z
1

a
y
l
12

a
x
k
2

x
p
w
1

I would like to be able to count the number of times any of these elements (x,y,z) appears in the cols (bisac1,bisac2,bisac3).
So, the expected result should be 3 for the first 3 rows, 2 for the next 3 and 1 for the last 3.

A: Seems the following should do what you require?
select
    case when bisac1 in ('x','y','z') then 1 else 0 end +
    case when bisac2 in ('x','y','z') then 1 else 0 end +
    case when bisac3 in ('x','y','z') then 1 else 0 end
from t;

A: You can also use one case per letter instead of one case per column (Stu's approach). The result will be the same for your sample data:
SELECT
  CASE WHEN 'x' IN (bisac1, bisac2, bisac3) THEN 1 ELSE 0 END +
  CASE WHEN 'y' IN (bisac1, bisac2, bisac3) THEN 1 ELSE 0 END +
  CASE WHEN 'z' IN (bisac1, bisac2, bisac3) THEN 1 ELSE 0 END
FROM yourtable;

The result will not be the same if the same letter occurs in different columns, For example, if your row looks like this:

bisac1
bisac2
bisac3

x
y
y

Then Stu's query will produce 3 as result, my query here 2. From your description, it is unclear to me if your sample data can contain such rows at all or if the two queries will always create the same result for your data.
And even if your data can include such rows, it's still unclear to me whether you want to get 3 or 2 as result.
So, summarized, it's up to you what exactly you want to use here.


text:
Q: Implement array and iterate I have this Ruby code that I want to use:
if args[:remove_existing_trxs] == 'true'
    Acquirer.delete_all
    Company.delete_all
    Currency.delete_all
    AdminUser.delete_all
    BaseReseller.delete_all
    Terminal.delete_all
    Contract.delete_all
    Merchant.delete_all
    MerchantUser.delete_all
    PaymentTransaction.delete_all
  end

How can I define it as an array and iterate?

A: Something like that?
[Model1, Model2].each do |model|
  model.public_send(:delete_all)
end

Or with using Symbol#to_proc:
[Model1, Model2].each(&:delete_all)

A: try this out:
  if args[:remove_existing_trxs] == 'true'
    [Acquirer, Company, Currency, AdminUser,
    BaseReseller, Terminal, Contract, Merchant,
    MerchantUser, PaymentTransaction].each(&:destroy_all)
  end


text:
Q: Read International Currency symbols from excel sheet in java poi 4.1.2 I am unable to read international currency and accounting number format from excel sheet into java standalone application using poi 4.1.2 (XSSF). Only able to read US locale symbol but unable to read other currency symbols in java. Using currency symbol only some formats cell value is displayed in java DataFormatter, other formats are displayed with ?(Eg: I/P: $10.00 O/P: ?10.00).
Accounting Number format unable to read Euro currency symbol(Exception: Illegal Argument Exception) and some currency symbols displaying cell data(currency symbol and value).
code:
for(int i=1;i<=rows;i++){
             String ExcelFilename = sheet.getRow(i).getCell(<cell no of file>).getRichStringCellValue().getString().trim();

             if(ExcelFilename.equals("<file name>")) {

                 for(int j=0;j<columns;j++) {

                      DataFormatter formatter = new DataFormatter();
                     cell = sheet.getRow(i).getCell(j,Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);

                     String  check= "";
                      switch (cell.getCellType()) {
                         case BLANK:
                             check=  formatter.formatCellValue(cell);
                             break;
                          case NUMERIC:
                             check=  formatter.formatCellValue(cell);
                             break;
                        case BOOLEAN:
                             check =formatter.formatCellValue(cell);
                             break;
                        case STRING:
                             check=formatter.formatCellValue(cell);
                             break;
                        case FORMULA:
                             check=  formatter.formatCellValue(cell);
                             break;
                        default:
                             break;
                    }
                }
            }

}
Exception:

*

*€ 100.00 - Euro
from Excel sheet Accounting-> currency type as Euro -> after running class I am getting below exception.

org.apache.poi.ss.format.CellFormat
WARNING: Invalid format: "_ [$€-2]\ * #,##0.00_ ;"
java.lang.IllegalArgumentException: Unsupported [] format block '[' in '_ [$€-2]\ * #,##0.00_' with c2: null
Similarly, I am getting exception for some other Accounting format currency symbols also.
Input (Excel sheet)-
output(Java)  - 100
Excel sheet(info.xlsx):

Output should display without exception and with cell data(symbol and numeric value) in java.

A: There really seems to be a bug in DataFormatter when currency € (EURO) is used with € sign placed in front of the value like € 1,234.56. All default Euro using states normally don't do so. They are writing currency like 1,234.56 €, so € sign placed behind the value.
If the Number format Currency or Accounting using symbol € Euro (€ 123) is used  in Excel, then Excel creates a number format like [$€-2]\ #,##0.00. That means currency symbol € placed in front of the value. But apache poi interprets that 2 as a country code like in [$£-809]#,##0.00 where the 809 means Great Britain. So because of that misinterpretation it fails since it does not find a country for code 2.
A workaround could be replacing all "[$\u20AC-2]" in data-format string with "\u20AC". That is replacing all [$€-2] with only the € sign.
Example:
import org.apache.poi.ss.usermodel.*;

import java.io.FileInputStream;
import java.io.PrintWriter;

class ReadExcelUsingDataFormatter {

 public static void main(String[] args) throws Exception {

  Workbook workbook = WorkbookFactory.create(new FileInputStream("ExcelExample.xlsx"));

  DataFormat format = workbook.createDataFormat();

  DataFormatter dataFormatter = new DataFormatter();

  PrintWriter writer = new PrintWriter("Result.txt", "UTF-8");

  Sheet sheet = workbook.getSheetAt(0);
  for (Row row : sheet) {
   for (Cell cell : row) {
     try {
         String dataFormatString = cell.getCellStyle().getDataFormatString();
         if (dataFormatString.contains("[$\u20AC-2]")) {
             System.out.println(dataFormatString);
             dataFormatString = dataFormatString.replace("[$\u20AC-2]", "\u20AC");
             System.out.println(dataFormatString);
             cell.getCellStyle().setDataFormat(format.getFormat(dataFormatString));
         }
         String value = dataFormatter.formatCellValue(cell);
         System.out.println(value); //This might not be printed correctly because of unicode deficiency of `System.out`. But `Result.txt` should contain it corrcetly.
         writer.print(value + "\t\t");
     } catch (Exception ex) {
         ex.printStackTrace();
     }

   }
   writer.println();
  }
  writer.close();
  workbook.close();
 }
}


text:
Q: In Puppeteer how to capture Chrome browser log in the console I'm trying to collect Chrome browser logs: browser-issued warnings such as deprecation and interventions. For example, for site https://uriyaa.wixsite.com/corvid-cli2:
A cookie associated with a cross-site resource at http://wix.com/ was set without the `SameSite` attribute.
A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`.
You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.

I thought the following code would do the trick but it only catches logs generated by the page code.
(async ()=> {
    const browser = await puppeteer.launch({dumpio: true});
    const page = await browser.newPage();
    page.on('console', msg => {
        for (let i = 0; i < msg._args.length; ++i)
            console.log(`${i}: ${msg._args[i]}`);
    });
    await page.goto('https://uriyaa.wixsite.com/corvid-cli2', {waitUntil: 'networkidle2', timeout: 20000});
    await page.screenshot({path: 'screenshot.png'});
    await browser.close();
})();

bellow is not relevant as I thought as reportingobserver does not catch the chrome info on cookies without sameSite:
Reading on the subject led me to https://developers.google.com/web/updates/2018/07/reportingobserver but I'm not sure how to use it, using the example int the browser console didn't work.
I'm not sure in which context the observer code should be used or if the browser need a flag to activate the reporting API. Or if this is the way to got about it.
help is welcomed.

A: Presumably, the 'console' event only catches console.log() and similar calls from the pages. But it seems you can catch warnings from the browser via CDPSession with Log Domain. Unfortunately, it works for me only with a headful browser:
'use strict';

const puppeteer = require('puppeteer');

(async function main() {
  try {
    const browser = await puppeteer.launch({ headless: false });
    const [page] = await browser.pages();
    const cdp = await page.target().createCDPSession();

    await cdp.send('Log.enable');

    cdp.on('Log.entryAdded', async ({ entry }) => {
      console.log(entry);
    });

    await page.goto('https://uriyaa.wixsite.com/corvid-cli2');
  } catch (err) {
    console.error(err);
  }
})();

And one of the entries:
{
  source: 'other',
  level: 'warning',
  text: 'A cookie associated with a cross-site resource at http://www.wix.com/ was set without the `SameSite` attribute. It has been blocked, as Chrome now only delivers cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.',
  timestamp: 1589058118372.802,
  url: 'https://uriyaa.wixsite.com/corvid-cli2'
}

A: When you launch Puppeteer browser, inside the options object, you should set dumpio to true:
await puppeteer.launch({ dumpio: true });

This will basically "pipe browser process stdout and stderr into process.stdout and process.stderr", which means it will redirect browser logs to whatever main process, server, etc. you are running.
You can see this and other launch options you can use when launching Puppeteer in here: https://www.puppeteersharp.com/api/PuppeteerSharp.LaunchOptions.html


text:
Q: Listening for click event within CKEditor 4 I've been reading about how to listen for click events within the CKEditor, specifically: CKEditor's click event not firing which was answered by Reinmar, but I still can't get this working.
My scenario is I have a CKEditor instance. Paragraphs are enclosed with
 tags, but I enclose parts of the text within  tags, the content looks like:

This is the first paragraph

This is The second paragraph

I want to add a click event, so whenever a user clicks on the text within a span tag, it performs an action, I'm happy with just getting an alert to display for the time being.
This is my code that I've been trying. I've been working through the documentation on the editable() element, editor and document properties / methods.
_instance.on('contentDom', function () {

    let editable = _instance.editable();
    let elements = new CKEDITOR.dom.element(editable.getElementsByTag('span'));
    console.log(elements);

    editable.attachListener(elements, 'click', function () {
        alert('test');
        console.log("click event");
    });
});

The results of the console.log(elements) correctly logs the following:

and from reading the documentation, the attachListener() method requires the first argument to be an instance of CKEDITOR.dom.element, so I'm passing the correct arguments, but nothing is alerted or logged when I click on the span tags.
I'm not sure how to proceed to any help would be appreciated.
Edit
If I replace editable.attachListener(elements...) with editable.attachListener(editable...) it works as expected, but works whenever I click anywhere within the editor, not specifically span tags, which doesn't really help me that much.

A: By default in current versions of CKEditor span's are not in the allowedContent config, so it might be stripped after you output those elements. I have a simple example here where i output the element name of the clicked element within the editor:
var editor = CKEDITOR.replace("txtarea");
editor.on("instanceReady", function(evt) {
  evt.editor.editable().on('click', function (event) {
      // YOUR CODE GOES HERE
      console.log("element clicked: ", event.data.$.target);
  });
});

If i switch to source and add span and then jump out of source again it is being stripped!
See full example here: http://run.plnkr.co/paYzYa25kt6wFM1J/


text:
Q: Issues with in Talend 6.5 after postgres upgrade from 9.6 to 11.5 I am using Talend DI 6.5.
I am getting below error while processing data from big csv file (10 mill rows) after migrating Postgres database from version 9.6 to 11.5
An I/O error occurred while sending to the backend.
Exception in component tPostgresqlOutput_1 (emp_table)
org.postgresql.util.PSQLException: This connection has been closed.

ETL job is working fine on 9.6 postgres version.
Do I need to change any settings in Talend DI for this DB upgrade?
any driver upgrade is requier? Please suggest


text:
Q: Dynamic Number of Radio fields I'm trying to create a multiple choice class where I pass in the question and anywhere from 2 to 8 possible answers from which the user must choose one.  How can I dynamically pass my items to my class, and create a new radiofield for each possible answer?  Here's my current class with two possible answers (Red, White)

    Ext.define('Sencha.view.question.QuestionTypeOne', {
    extend: 'Ext.Container',
    xtype: 'question-type-one',
    requires: [
        'Ext.TitleBar'
        ],
    config: {
        height: '250px',
        width: '250px',
        items: [
            {

                xtype: 'fieldset',
                title: 'What\'s your favorite color?',
                instructions: 'Select one',

                defaults: {
                    xtype: 'radiofield',
                    labelWidth: '40%'
                },
                items: [
                    {
                        name: 'color',
                        value: 'red',
                        label: 'Red'
                    },
                    {
                        name: 'color',
                        value: 'white',
                        label: 'White'
                    }

                ]

            }
        ]
    },

    initialize: function () {
        this.callParent(arguments);
    }
    });

And it would be invoked something like this?

      {
         xtype: 'question-type-one',
         // question: "What's your favorite color?",
         // items: []
      }

A: while creating view for question-type-one you can pass list of questions/answers and in initialize function you can iterate over this data and add items to you fieldset. For this you might have to keep null config q & a in view class.
var question = Ext.create("Sencha.view.question.QuestionTypeOne", {
  q : "blah blah blah",
  a : {"a1", "a2", "a3"}
});

then in initialize function
initialize: function () {
    this.callParent(arguments);
    var question = this.config.q;
    var answers = this.config.a;
    var container = this.down('fieldset');
    // now iterate over answers and all container.add(answerdfield);
}


text:
Q: Is there a JavaScript way to do file_get_contents()? Here is the PHP documentation
Here is how I would use it in an Ajax call, if I don't find a pure client way to do this.
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;

Is there way to do this client side instead so I don't have to ajax the string over?

A: you could do
JS code:
$.post('phppage.php', { url: url }, function(data) {
    document.getElementById('somediv').innerHTML = data;
});

PHP code:
$url = $_POST['url'];
echo file_get_contents($url);

That would get you the contents of the url.

A: It's 2020 and some modern approach;
async function file_get_contents(uri, callback) {
    let res = await fetch(uri),
        ret = await res.text();
    return callback ? callback(ret) : ret; // a Promise() actually.
}

file_get_contents("https://httpbin.org/get", console.log);
// or
file_get_contents("https://httpbin.org/get").then(ret => console.log(ret));

A: JavaScript cannot go out and scrape data off of pages. It can make a call to a local PHP script that then goes on its behalf and grabs the data, but JavaScript (in the browser) cannot do this.
$.post("/localScript.php", { srcToGet: 'http://example.com' }, function(data){
  /* From within here, data is whatever your local script sent back to us */
});

You have options like JSONP and Cross-Origin Resource Sharing at your disposal, but both of those require setting up the other end, so you cannot just choose a domain and start firing off requests for data.
Further Reading: Same origin policy

A: This function will return the file as a string just like the PHP file_get_contents().
function file_get_contents(uri, callback) {
    fetch(uri).then(res => res.text()).then(text => callback(text));
}

However unlike PHP, JavaScript will go on to the next statement, not waiting for the data to return.

A: Not in a general sense. Cross-domain restrictions disallow Javascript code from doing this.
If the target site has CORS (cross-origin resource sharing) set up, you can use XMLHttpRequest to load files. Most sites do not, as it's off by default for security reasons, and is rarely necessary.
If you just need to include an HTML page, you can stick it in an  element. This is subject to some layout gotchas, though (the page ends up in a fixed-size element).

A: Or You can use php.js library. Which allow some php functions for javascript. file_get_contents() function one of them.

You can find more info about php.js : http://phpjs.org/

A: I think this may be useful for you:
An npm package with the "file-get-contents" method for node.js
https://www.npmjs.com/package/file-get-contents
It is asynchronous so if you are using express it should be used like this
app.get('/',  async (req, res)=>{
    //paste here the code below
}

Example
const fileGetContents = require('file-get-contents');

// A File request

try {
    let data = await fileGetContents('/tmp/foo/bar');

    console.log(data);
} catch (err) {
    console.log('Unable to load data from /tmp/foo/bar');
}

// Or a HTTP(S) request

fileGetContents('https://pokeapi.co/api/v2/pokemon/1/').then(json => {
    const pokemon = JSON.parse(json);

    console.log(`Name of first pokemon is ${pokemon.name}`);
}).catch(err => {
    console.err(`Unable to get content from PokeAPI. Reason: ${err.message}`);
});

A:

A:

function file_get_contents(filename) {
    fetch(filename).then((resp) => resp.text()).then(function(data) {
        document.getElementById("id").innerHTML = data;
    });
}
file_get_contents("url");


text:
Q: HTTP Status 415 – Unsupported Media Type when doing POST request on Spring MVC I am trying to send a post request on a simple Spring MVC web app and use RequestBody in my controller to convert the JSON into a Java Object but for whatever reason, I keep getting HTTP Status 415 – Unsupported Media Type. I have spent a lot of time trying to find a solution to this but nothing seems to be working.
The get method in my Controller seems to be working fine. This is my original code
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping(value = "/users", method = RequestMethod.POST)
public class MyControllerAgain {

    @RequestMapping(method = RequestMethod.POST, consumes = "application/json")
    public void handleJson(@RequestBody Contact c) {
        System.out.println(c);
    }

    @RequestMapping(method = RequestMethod.GET, consumes = "application/json")
    public void handleGet() {
        System.out.println("a");
    }
}

This is my Contact
public class Contact {

    int id;

    public String name;

    public int number;

    public Contact(){}

    // Getters and setters
}

I am sending a request with Postman and this is what it looks like
POST /users HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Accept: application/json
Cache-Control: no-cache
Postman-Token: 511c9e03-4178-380d-58f8-db24a3245b9e

{
    "id":1,
    "name":"something",
    "number":1
}

I have also tried including Jackson dependencies in my pom.xml .
I have tried altering consume value in @RequestMapping annotation and I have tried all combinations of headers accept and Content type in my request.
Also, If I use @ModelAttribute instead of @RequestBody, then everything works fine except all the fields in Contact class are null.
Here is the github link - https://github.com/Sanil2108/test_springmvc

A: To me it looks like that the jpa anotations are messing up the json deserialization.
The error returned from the spring server could be misleading.
Try using plain object with setters and getters and see if this changes anything.
You should search for some exceptions in the logs.

A: Add a mapping to the handleGet method, for example:
@RequestMapping(value = "/get", method = RequestMethod.GET, consumes = "application/json")
public void handleGet() {
    System.out.println("a");
}

--UPDATE--
Remove the consumes = "application/json" part from you GET call. It sees that both requests that listen to "/users" can consume json data, but one is a GET and the other one is a POST.
--2nd UPDATE--
This will definitely work. Tested.
@RestController
@RequestMapping(value = "/users", method = RequestMethod.POST)
public class ContactController
{
    @RequestMapping(method = RequestMethod.POST, consumes = "application/json")
        public void handleJson(@RequestBody Contact c)
        {
           System.out.println(c);
        }
}

A: RequestMapping annotation not only has the consumes but also produces.
But to avoid all these settings for HTTP REST, you can use RestController annotation and GetMapping, PostMapping etc..
You can find an example in my github

A: Tried everything but couldn't it to work. Maybe I was making a silly mistake somewhere or there was something seriously wrong with my configuration. Anyway, I tried to make it work with Spring boot and it worked fine. For anyone who is interested, Here is the github link - https://github.com/Sanil2108/spring_hibernate/tree/master/spring_boot1
Also, thanks to everyone who tried to help!


text:
Q: How to interpret Linux `top` command I am running a R script and it is actually a long for loop.
Here is a screenshot of the "top" command. You can see that it says R is using 100 % CPU but on the top line, it says 4.2% usage for user processes. What does this mean? Does it mean that the CPU has multiple cores and I am only using one?

A: First of all, yes - if you have a multi-core system you can have multiple processes at 100% (the process list shows the utilization of a theoretical single core) or for multithreaded processes you can have a single process above 100%.  The overall CPU usage might be 25%, 50% etc. - because the top default is for the first CPU figures to be an aggregate of all CPUs on the system.  You will get a better view if you press 1 with top running - it will split out each CPU.
With that said, the us(er), sy(stem), ni(ce) and id(le) buckets are also relevant.  The R program does not seem to be hammering the CPU in the loop and so the CPU is mostly in the Idle bucket.  I am not super familiar with R - you might want to add some debug to see what it is waiting for, if you can optimize it to better utilize the CPU (assuming you are aiming for it to be CPU bound).  Similarly you could have a process hammering the disk and have a low percentage User but a high Wa(it) figure while you wait to page data to/from the disk.
If R was churning in the loop doing calculations/sorts or similar constantly this would shift overall CPU usage to the User bucket (or if you nice the process it would shift to the nice bucket).  The system bucket might see an uptick if you were doing large in-memory scans and sorts (though then it would not necessarily be assigned to a process in the list).  Right now though, it looks like your system is pretty lightly loaded running the current loop.


text:
Q: Pyspark filtering based on column value data and applying condition I have a pyspark dataframe in this format.
out.show(5)
+----------------+--------+--
|ip_address| Device  | Count |
+----------------+--------+--
|2.3.4.5  |   Apple  |     6 |
|1.2.3.4  |  Samsung |     18|
|6.6.6.6  |   MI     |     8 |
|4.4.4.4  |   Samsung|     12|
|8.8.8.8  |   Apple  |     16|
|9.9.9.9  |   Samsung|      8|
+----------------+--------+---

I want to get the output where output adds result which meets both the conditions

*

*For 'Device' as 'Samsung' the 'Count' >10

*else for any other 'Device' Type if 'Count' > 8

Final output should be like this
+----------------+--------+--
|ip_address| Device  | Count |
+----------------+--------+--
|1.2.3.4   |  Samsung|   18  |
|4.4.4.4   |  Samsung|    12 |
|8.8.8.8   |   Apple |    16 |

So one way I can think of doing is something like this by filtering out the Device type and  applying conditions but I want to know if we can do it using a if else and then concatenating both conditions output
frSamsung = out.filter(out["Device"].rlike("Samsung"))
 fpr=frSamsung.filter(frSamsung.Count > 10)

A: Basically here you need composite condition, count depends on device type with 2 different conditions -
from pyspark.sql import functions as F

df.where((
         ((F.col("device") == 'Samsung') & (F.col("count") > 10 )) |
         ((F.col("device") != 'Samsung') & (F.col("count") > 8 ))
)).show()

A: assuming df is your dataframe:
from pyspark.sql import functions as F

df.where(
    """
    Device = 'Samsung' and Count > 10
    or Device <> 'Samsung' and count > 8
    """
).show()


text:
Q: How to fix serve error due to package.json missing in production only? How can I fix the error below:
> ng "serve" "0.0.0.0" "--poll=2500" "--disable-host-check" "--prod=true"

WARNING Running a server with --disable-host-check is a security risk. See https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a for more information.
****************************************************************************************
This is a simple server for use in testing or debugging Angular applications locally.
It hasn't been reviewed for security issues.

DON'T USE IT FOR PRODUCTION!
****************************************************************************************
** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
 95% emittingUnhandled rejection Error: ENOENT: no such file or directory, open '/usr/src/web/node_modules/handsontable/package.json'
    at Object.openSync (fs.js:461:3)
    at Object.readFileSync (fs.js:364:35)
    at LicenseExtractor.readPackageJson (/usr/src/web/node_modules/license-webpack-plugin/dist/LicenseExtractor.js:126:23)
    at LicenseExtractor.parsePackage (/usr/src/web/node_modules/license-webpack-plugin/dist/LicenseExtractor.js:23:32)
    at ModuleProcessor.processPackage (/usr/src/web/node_modules/license-webpack-plugin/dist/ModuleProcessor.js:44:46)
    at ModuleProcessor.processFile (/usr/src/web/node_modules/license-webpack-plugin/dist/ModuleProcessor.js:41:21)
    at fileCallback (/usr/src/web/node_modules/license-webpack-plugin/dist/LicenseWebpackPlugin.js:107:61)
    at moduleCallback (/usr/src/web/node_modules/license-webpack-plugin/dist/LicenseWebpackPlugin.js:114:21)
    at /usr/src/web/node_modules/license-webpack-plugin/dist/LicenseWebpackPlugin.js:126:29
    at Array.forEach (<anonymous>)
    at Compiler.emitCallback (/usr/src/web/node_modules/license-webpack-plugin/dist/LicenseWebpackPlugin.js:92:32)
    at next (/usr/src/web/node_modules/tapable/lib/Tapable.js:204:14)
    at /usr/src/web/node_modules/html-webpack-plugin/index.js:204:9
    at PassThroughHandlerContext.finallyHandler (/usr/src/web/node_modules/bluebird/js/release/finally.js:56:23)
    at PassThroughHandlerContext.tryCatcher (/usr/src/web/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/usr/src/web/node_modules/bluebird/js/release/promise.js:547:31)

thrown when:
npm run ng serve --host 0.0.0.0 -- --poll=2500 --disable-host-check --prod=true

is run. But which isn't thrown when:
npm run ng serve --host 0.0.0.0 -- --poll=2500 --disable-host-check

is run?
Here's the package.json:
{
  "name": "retailportal-web",
  "version": "0.0.0",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "ng": "ng",
    "start": "ng serve --host 0.0.0.0",
    "test": "ng test",
    "build": "ng build --base-href /SopPortal/",
    "build-prod": "ng build --prod --base-href /SopPortal/",
    "pree2e": "webdriver-manager update --standalone false --gecko false",
    "e2e": "protractor"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "5.1.1",
    "@angular/cdk": "5.0.1",
    "@angular/common": "~5.1.1",
    "@angular/compiler": "~5.1.1",
    "@angular/core": "~5.1.1",
    "@angular/forms": "~5.1.1",
    "@angular/http": "~5.1.1",
    "@angular/material": "5.0.1",
    "@angular/material-moment-adapter": "5.0.3",
    "@angular/platform-browser": "~5.1.1",
    "@angular/platform-browser-dynamic": "~5.1.1",
    "@angular/router": "~5.1.1",
    "@ng-bootstrap/ng-bootstrap": "~1.0.0-beta.8",
    "@ng-select/ng-select": "~0.25.0",
    "@ngx-translate/core": "~9.0.2",
    "@ngx-translate/http-loader": "~2.0.0",
    "@types/jquery": "~3.2.17",
    "angular-highcharts": "5.2.8",
    "compass-sass-mixins": "0.12.7",
    "core-js": "~2.5.3",
    "enhanced-resolve": "3.3.0",
    "font-awesome": "4.7.0",
    "hammerjs": "~2.0.8",
    "highcharts": "6.0.6",
    "numbro": "2.1.2",
    "jquery": "~3.2.1",
    "ng-bootstrap": "~1.6.3",
    "ng2-file-upload": "~1.3.0",
    "ng2-handsontable": "2.0.0",
    "node-sass": "^4.7.2",
    "rxjs": "~5.5.5",
    "tether": "~1.4.3",
    "ts-helpers": "~1.1.2",
    "zone.js": "~0.8.18"
  },
  "devDependencies": {
    "@angular/cli": "1.7.1",
    "@angular/compiler-cli": "~5.0.0",
    "@types/highcharts": "5.0.16",
    "@types/jasmine": "2.5.45",
    "@types/jquery": "~3.2.12",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.1.1",
    "jasmine-core": "2.6.2",
    "jasmine-spec-reporter": "4.1.0",
    "karma": "1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-jasmine": "~1.1.0",
    "karma-remap-istanbul": "~0.2.1",
    "moment": "~2.20.1",
    "protractor": "~5.1.2",
    "ts-md5": "~1.2.0",
    "ts-node": "3.0.4",
    "tslint": "~5.3.2",
    "typescript": "2.4.2"
  }
}

and npm ls --depth=0:
# npm ls --depth=0
retailportal-web@0.0.0 /usr/src/web
+-- @angular/animations@5.1.1
+-- @angular/cdk@5.0.1
+-- @angular/cli@1.7.1
+-- UNMET PEER DEPENDENCY @angular/common@5.1.3
+-- UNMET PEER DEPENDENCY @angular/compiler@5.1.3
+-- @angular/compiler-cli@5.0.5
+-- UNMET PEER DEPENDENCY @angular/core@5.1.3
+-- UNMET PEER DEPENDENCY @angular/forms@5.1.3
+-- @angular/http@5.1.3
+-- UNMET PEER DEPENDENCY @angular/material@5.0.1
+-- @angular/material-moment-adapter@5.0.3
+-- @angular/platform-browser@5.1.3
+-- @angular/platform-browser-dynamic@5.1.3
+-- @angular/router@5.1.3
+-- @ng-bootstrap/ng-bootstrap@1.0.4
+-- @ng-select/ng-select@0.25.0
+-- @ngx-translate/core@9.0.2
+-- @ngx-translate/http-loader@2.0.1
+-- @types/highcharts@5.0.16
+-- @types/jasmine@2.5.45
+-- @types/jquery@3.2.18
+-- @types/node@6.0.118
+-- angular-highcharts@5.2.8
+-- bindings@1.5.0 extraneous
+-- codelyzer@3.1.2
+-- compass-sass-mixins@0.12.7
+-- core-js@2.5.7
+-- enhanced-resolve@3.3.0
+-- font-awesome@4.7.0
+-- hammerjs@2.0.8
+--  extraneous error: ENOENT: no such file or directory, open '/usr/src/web/node_modules/handsontable/package.json
+-- highcharts@6.0.6
+-- jasmine-core@2.6.2
+-- jasmine-spec-reporter@4.1.0
+-- jquery@3.2.1
+-- karma@1.7.0
+-- karma-chrome-launcher@2.1.1
+-- karma-cli@1.0.1
+-- karma-jasmine@1.1.2
+-- karma-remap-istanbul@0.2.2
+-- moment@2.20.1
+-- ng-bootstrap@1.6.3
+-- ng2-file-upload@1.3.0
+-- ng2-handsontable@2.0.0
+-- node-sass@4.14.1
+-- numbro@2.1.2
+-- protractor@5.1.2
+-- rxjs@5.5.12
+-- tether@1.4.7
+-- ts-helpers@1.1.2
+-- ts-md5@1.2.7
+-- ts-node@3.0.4
+-- tslint@5.3.2
+-- typescript@2.4.2
`-- zone.js@0.8.29

npm ERR! peer dep missing: @angular/common@^4.0.0, required by ng2-handsontable@2.0.0
npm ERR! peer dep missing: @angular/compiler@5.0.5, required by @angular/compiler-cli@5.0.5
npm ERR! peer dep missing: @angular/compiler@^2.3.1 || >=4.0.0-beta <5.0.0, required by codelyzer@3.1.2
npm ERR! peer dep missing: @angular/compiler@^4.0.0, required by ng2-handsontable@2.0.0
npm ERR! peer dep missing: @angular/core@5.1.1, required by @angular/animations@5.1.1
npm ERR! peer dep missing: @angular/core@^2.3.1 || >=4.0.0-beta <5.0.0, required by codelyzer@3.1.2
npm ERR! peer dep missing: @angular/core@^4.0.0, required by ng2-handsontable@2.0.0
npm ERR! peer dep missing: @angular/forms@^4.0.0, required by ng2-handsontable@2.0.0
npm ERR! peer dep missing: @angular/material@5.0.3, required by @angular/material-moment-adapter@5.0.3
npm ERR! extraneous: handsontable /usr/src/web/node_modules/handsontable
npm ERR! error in /usr/src/web/node_modules/handsontable: ENOENT: no such file or directory, open '/usr/src/web/node_modules/handsontable/package.json'
npm ERR! extraneous: bindings@1.5.0 /usr/src/web/node_modules/bindings

node & npm versions:
# node --version
v14.2.0
# npm --version
6.14.4
#

also tried with node 6 to no avail.
the package handsontable is supplied independent from npm.

A: When you build in prod mode, angular tries to extract licenses from the 3rd party libs that you use into a 3rdpartylicenses.txt file. For that, it needs looking at package.json files.
Since you put your handontable package manually in your node_modules, it's missing package.json.
What you should really do is install handontable with npm (specify the version if needed)
npm add -S handsontable

A workaround is to disable extracting the licenses, by passing a flag when building
npm run ng serve --host 0.0.0.0 --poll=2500 --disable-host-check --prod=true --extractLicenses=false


text:
Q: I am trying to call a URL from a local wordpress img file using a text widget I received permission to link to another site and they provided me their .jpg logo. I can get the URL to work but I cannot get the logo to pull from my site. I've tried numerous variations to the path of the logo file. Any help would be greatly appreciated:
"

I have also tried

And nothing seem to be working.

A: Does this work? Are you sure you are using the 'text' editor in wordpress rather than the 'visual' editor?


text:
Q: setting up a multi-multifiltering in a plugin, is it even possible in this particular case? Here is the problem in a nutshell. I don't know how to make filters of same row to exclude each other. For example, if you select islands, and then select cities, islands should be "deselected".
But in my case, they stack up.
This is my MixItUp setup
            targetSelector : '.mix',
            filterSelector : '.filter',
            sortSelector : '.sort',
            buttonEvent: 'click',
            effects : ['fade', 'scale'],
            listEffects : null,
            easing : 'smooth',
            layoutMode: 'grid',
            targetDisplayGrid : 'inline-block',
            targetDisplayList: 'block',
            listClass : '',
            gridClass : '',
            transitionSpeed : 600,
            showOnLoad : 'all',
            sortOnLoad : false,
            multiFilter : true,
            filterLogic : 'and',
            resizeContainer : true,
            minHeight : 0,
            failClass : 'fail',
            perspectiveDistance : '3000',
            perspectiveOrigin : '50% 50%',
            animateGridList : true,
            onMixLoad: null,
            onMixStart : null,
            onMixEnd : null,

I know it's dumb to ask of you to debug a distant site but here is application of my problem:
fiddle containing the essence of the problem: http://jsfiddle.net/DwX29/
Here, I want to click lemons, then small and result should be small lemons, not small lemons and small oranges. But if I click on oranges while lemons are active, lemons should be deselected and only show oranges as a result.
github: https://github.com/goxytesla/Monsi_apartments
the site: http://abbaenterijer.com/
Thanks you for taking your time to look into my problem in advance.

A: I did this by creating my own click function and having a variable for each group of filters, then joining them together and running
$('#grid').mixitup('filter',allselectedfilters);

So you have a variable for fruits that contains the active filter in, as well as a variable for size that has the active size selected in.
var fruits = 'orange';
var size = 'small';

The you join the two together
var allselectedfilters = fruits+' '+size;

and run that
$('#grid').mixitup('filter',allselectedfilters);

This is a pretty simplified version but hopefully it gets you off to the right start.
Just remember that when "All" is selected then the corresponding variable should be empty but defined.


text:
Q: Deserialize JSON string into a List of POJOs Here is my code for deserializing the response I get back from a Google App Engine Cloud Endpoint:
String jsonString = IOUtils.toString(
    httpResponse.getEntity().getContent(), "UTF-8");

ObjectMapper mapper = new ObjectMapper();
ArrayList<myPOJO> myList=
    mapper.readValue(jsonString, new TypeReference<ArrayList<MyPOJO>>(){});

jsonString looks like this:
{
  "items" : [ {
    "id" : "12345",
    "name" : "test1"
  }, {
    "id" : "121212",
    "name" : "test2"
  } ]
}

But I am getting this error:
org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token at [Source: java.io.StringReader@547a7880; line: 1, column: 1]

What is the proper way to deserialize this JSON into a List of POJOs with Jackson?

A: try deserializing directly with the mapper
String jsonString = IOUtils.toString(
        httpResponse.getEntity().getContent(), "UTF-8");

    ObjectMapper mapper = new ObjectMapper();

    List<MyPOJO> myList= mapper.convertValue(jsonString, mapper.getTypeFactory().constructCollectionType(List.class, MyPOJO.class));

A: You have to create root POJO for your JSON root object. For example:
class Root {

    private List<Entity> items;

    //getters, setters, toString, etc
}

class Entity {

    private long id;
    private String name;

    //getters, setters, toString, etc
}

Simple app:
ObjectMapper mapper = new ObjectMapper();
Root list = mapper.readValue(json, Root.class);
System.out.println(list);

prints:
Root [items=[Entity [id=12345, name=test1], Entity [id=121212, name=test2]]]


text:
Q: how do i create an infinate array in vb.net I am trying to create a while loop that ends when someone types ".".
My code is as follows and I get the error that follows the code:
    Dim x, y As Integer
    Dim stuff(x) As String
    y = 1
    x = 0
    While y = 1
        x = x + 1
        Console.WriteLine("input stuff end with .")
        stuff(x - 1) = Console.ReadLine()
        If stuff(x - 1) = "." Then
            y = 0
        End If

    End While

The error message:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in practise.exe

Additional information: Index was outside the bounds of the array.

Thanks in advance.

A: Use a List
    Dim stuff As New List(Of String)
    Do
        Console.WriteLine("input stuff end with .")
        stuff.Add(Console.ReadLine())
    Loop While stuff(stuff.Count - 1) <> "."

A: You can use instead a dictionary instead of an array, you can use your x variable as your key

A: x = x + 1
ReDim Preserve stuff(x) 'add this line
Console.WriteLine("input stuff end with .")

You will also likely exceeding what can fit in an Integer data type if it runs a while. Dim x As Long (or Decimal if you need even more) instead.

A: Basically the issue with your code is your array. The below code should do the trick initially defining the array with size 1, then you can redefine the array with size (x+1) within the loop.
    Dim x, y As Integer
    Dim stuff(1) As String
    y = 1
    x = 0
    While y = 1
        x = x + 1
        Console.WriteLine("input stuff end with .")
        stuff(x - 1) = Console.ReadLine()
        If stuff(x - 1) = "." Then
            y = 0
        End If
        ReDim Preserve stuff(x + 1)

    End While

Hope this helps
[UPDATE 13/10/16 15:21]
Changed ReDim to ReDim Preserve to preserve the data in the array. Thanks topshot


text:
Q: Update using mysqldb interface I am trying to figure out how to tell the difference when the rowcount returns a zero.
It can have two meanings:

*

*The row was not found

*The row was found but not changed
For example, and this is a very simple example just to illustrate a concept:
mysql> update tmp_tab set firstname = 'Jonhny' where id = '01001402450';
Query OK, 1 row affected (0.03 sec)
Rows matched: 1  Changed: 1  Warnings: 0

In mysqldb, cur.rowcount would be 1.
Imagine the same command is executed again two days later:
mysql> update tmp_tab set firstname = 'Jonhny' where id = '01001402450';
Query OK, 0 rows affected (0.01 sec)
Rows matched: 1  Changed: 0  Warnings: 0

In mysqldb, cur.rowcount would be 0.
Now we execute this command:
mysql> update tmp_tab set firstname = 'Jonhny' where id = 'xxxxxxxxxx';
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0  Changed: 0  Warnings: 0

In mysqldb, cur.rowcount would be 0.
My problem is how can I tell the difference between a row not being found and a row not being changed.
I am familiar with DB2, and DB2 it will return a +100 (not found) when the key does not exist, and a 0 when it exists, no matter if the values being updated remain the same or not.
Obviously I don't want to have to do a select to just figure that out, that would be extremely inefficient.
So is there a way to recognize a "not found" condition versus a "nothing changed" condition without executing another SQL query?


text:
Q: How do you hide Windows 7 Explorer Toolbar and Property Bar? In Windows 7, Windows Explorer has a large bar just above the status bar that contains properties of the highlighted item. Is it possible to hide this? It  takes up a significant amount of screen space I'd prefer using in the file listing.
Also, is it possible to hide the tool bar for the same reason? That's what I'm calling the bar near the top with "Organize, Open, Include in Library, Share With..."

A: Organize → Layout → Details pane
And no, I don't think you can hide the toolbar in Explorer windows.

A: Windows 7 Command Bar Tweaker can be used to hide the Windows 7 Explorer toolbar (or Command bar).

A: Is this what you need?:
http://www.winvistaclub.com/t219.html
It claims it's working for vista and 7.

A: It is called "Folder Band".
This link will tell you how to do so, except it shows you how to auto-hide.
customize it
If you want to remove it permanently, read the link and instead of doing their modification, replace this:
<style resid="FolderBandStyle">
<Element
background="argb(0, 0, 0, 0)"
/>

with:
<style resid="FolderBandStyle">
<Element
background="argb(0, 0, 0, 0)"
padding="rect(0rp,0rp,0rp,-28rp)" />

Once finished you can just restart explorer.exe, you don't have to restart as the article suggests.


text:
Q: Regular expression behaves unexpectedly when using some specific words I am trying to remove stopwords from strings.
I encountered surprising results with some words combination. Below is the smallest example I could make that exhibits this behavior.
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re
import json

en = '''
["different","doesn't","doing","don't","done","down","downwards","during","e","each","edu","eg","eight","either","else","elsewhere","enough","entirely","especially","et","etc","even","ever","every","everybody","everyone","everything","everywhere","ex","exactly","example","except","f","far","few","fifth","first","five","followed","following","follows","for","former","formerly","forth","four","from","further","furthermore","g","get","gets","getting","given","gives","go","goes","going","gone","got","gotten","greetings","h","had","hadn't","known","knows","l","last","lately","later","latter","latterly","least","less","lest","let","let's","like","liked","likely","little","look","looking","looks","ltd","m","mainly","many","may","maybe","me","mean","meanwhile","merely","might","more","moreover","most","mostly","much","must","my","myself","n","name","namely","nd","near"]
'''

fr = '''
["a","abord","absolument","afin","ah","ai","aie","ailleurs","ainsi","ait","allaient","allo","allons","allô","alors","anterieur","anterieure","anterieures","apres","après","as","assez","attendu","au","aucun","aucune","aujourd","aujourd'hui","aupres","auquel","aura","auraient","aurait","auront","aussi","autre","autrefois","autrement","autres","autrui","aux","auxquelles","auxquels","avaient","avais","avait","avant","avec","avoir","avons","ayant","b","bah","bas","basee","bat","beau","beaucoup","bien","bigre","boum","bravo","brrr","c","car","ce","ceci","cela","celle","celle-ci","celle-là","celles","celles-ci","celles-là","celui","celui-ci","celui-là","cent","cependant","certain","certaine","certaines","certains","certes","ces","cet","cette","ceux","ceux-ci","ceux-là","chacun","chacune","chaque","cher","chers","chez","chiche","chut","chère","chères","ci","cinq","cinquantaine","cinquante","cinquantième","cinquième","clac","clic","combien","comme","comment","comparable","comparables","compris","concernant","contre","couic","crac","d","da","dans","de","debout","dedans","dehors","deja","delà","depuis","dernier","derniere","derriere","derrière","des","desormais","desquelles","desquels","dessous","dessus","deux","deuxième","deuxièmement","devant","devers","devra","different","differentes","differents","différent","différente","différentes","différents","dire","directe","directement","dit","dite","dits","divers","diverse","diverses","dix","dix-huit","dix-neuf","dix-sept","dixième","doit","doivent","donc","dont","douze","douzième","dring","du","duquel","durant","dès","désormais","e","effet","egale","egalement","egales","eh","elle","elle-même","elles","elles-mêmes","en","encore","enfin","entre","envers","environ","es","est","et","etant","etc","etre","eu","euh","eux","eux-mêmes","exactement","excepté","extenso","exterieur","f","fais","faisaient","faisant","fait","façon","feront","fi","flac","floc","font","g","gens","h","ha","hein","hem","hep","hi","ho","holà","hop","hormis","hors","hou","houp","hue","hui","huit","huitième","hum","hurrah","hé","hélas","i","il","ils","importe","j","je","jusqu","jusque","juste","k","l","la","laisser","laquelle","le","lequel","les","lesquelles","lesquels","leur","leurs","longtemps","lors","lorsque","lui","lui-meme","lui-même","là","lès","m","ma","maint","maintenant","oust","ouste","outre","ouvert","ouverte","ouverts","o|","où","p","paf","pan","par","parce","parfois","parle","parlent","parler","parmi","parseme","partant","particulier","particulière","probante","procedant","proche","près","psitt","pu","puis","puisque","pur","pure","q","qu","quand","quant","quant-à-soi","quanta","quarante","quatorze","quatre","quatre-vingt","quatrième","quatrièmement","que","quel","quelconque","quelle","quelles","quelqu'un","quelque","quelques","quels","qui","quiconque","quinze","quoi","quoique","r","rare","rarement","rares","relative","relativement","remarquable","rend","rendre","restant","reste","restent","restrictif","retour","revoici","revoilà","rien","sa","sacrebleu","sait","sans","sapristi","sauf","se","sein","seize","selon","semblable","tres","trois","troisième","troisièmement","trop","vrai"]
'''

stopwords = set(json.loads(en) + json.loads(fr))

stopwordsStr = '|'.join(stopwords)
regex = re.compile(r'\b('+stopwordsStr+r')\b')

msg = "le vrai commentaire sur les vous tres time foobar"
print msg
print regex.sub('', msg)

The code above works as expected:
$ python debug.py
le vrai commentaire sur les vous tres time foobar
  commentaire sur  vous  time foobar

The stopwords are removed correctly.
Now! for the interesting part. If I change the lines defining the English words to this:
en = '''
["time","different","doesn't","doing","don't","done","down","downwards","during","e","each","edu","eg","eight","either","else","elsewhere","enough","entirely","especially","et","etc","even","ever","every","everybody","everyone","everything","everywhere","ex","exactly","example","except","f","far","few","fifth","first","five","followed","following","follows","for","former","formerly","forth","four","from","further","furthermore","g","get","gets","getting","given","gives","go","goes","going","gone","got","gotten","greetings","h","had","hadn't","known","knows","l","last","lately","later","latter","latterly","least","less","lest","let","let's","like","liked","likely","little","look","looking","looks","ltd","m","mainly","many","may","maybe","me","mean","meanwhile","merely","might","more","moreover","most","mostly","much","must","my","myself","n","name","namely","nd","near"]
'''

I just added the keyword "time" at the beginning. I could add it anywhere it would break the same way.
Now I get:
$ python ../converse/debug.py
le vrai commentaire sur les vous tres time foobar
le vrai commentaire sur  vous tres time foobar

Now some stopwords are not removed anymore. I really don't get what's going on.
If I remove some words from the stopwords list it works correctly again, eg if I remove "doesn't" from the English list.

A: fr list has word "o|", which results in '||' in the final regexp. That is not handled well by parser. Changing "o|" to "o" solves the problem.
Or words could be escaped with re.escape. Then error in one word wouldn't ruin whole regex.


text:
Q: How to know: How many requests is HttpServer-in-Vertx serving I write a server with Vertx.
I have about 40k users. I can print every request but I don't know how to know how many current requests my server is serving
I used this class: http://vertx.io/docs/apidocs/io/vertx/core/http/HttpServer.html but this is no method to do it
Vertx is great toolkit but it can not show server status, really????
My server code:
public class MyFirstVerticle extends AbstractVerticle {

    private HttpServer httpServer = null;

    @Override
    public void start() throws Exception {
    httpServer = vertx.createHttpServer();

    httpServer.requestHandler(new Handler<HttpServerRequest>() {
        @Override
        public void handle(HttpServerRequest request) {

            String path = request.path();
            System.out.println("incoming request: [" + request.remoteAddress() + "] at " + path);
        }
    });

    httpServer.listen(9999);
    }
}

A: Since vert.x 3.x.x http://vertx.io/docs/vertx-dropwizard-metrics is an official component of vert.x
I think what you search is this:
http://vertx.io/docs/vertx-dropwizard-metrics/java/#http-server-metrics
There are several possibilities to view the metrics

*

*jmx http://vertx.io/docs/vertx-dropwizard-metrics/java/#jmx

*http bridge for jmx http://vertx.io/docs/vertx-dropwizard-metrics/java/#_using_jolokia_and_hawtio

*In our project we write periodically to a log file and send it in parallel to a graphite / grafana instance over udp

A: Vert.x requests are very short lived, so basing calculations solely on number of requests per second is not optimal. But, for the sake of discussion, you can achieve what you want in the following way:
public class MyFirstVerticle  extends AbstractVerticle {

    private HttpServer httpServer = null;

    // Bad, done for the sake of simplicity
    public final static AtomicInteger counter = new AtomicInteger(0);

    @Override
    public void start() throws Exception {

        httpServer = vertx.createHttpServer();

        httpServer.requestHandler(new Handler<HttpServerRequest>() {

            public void handle(HttpServerRequest request) {

                counter.incrementAndGet();
                String path = request.path();
                System.out.println("incoming request: [" + request.remoteAddress() + "] at " + path);
                request.response().end();

                request.endHandler(new Handler<Void>() {
                    @Override
                    public void handle(Void aVoid) {
                        counter.decrementAndGet();
                    }
                });
            }
        });

        httpServer.listen(9999);
    }
}

Then to test yourself you can try something like that:
public class Main {

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();

        MyFirstVerticle verticle = new MyFirstVerticle();

        vertx.deployVerticle(verticle);
        // Very bad, but our request are very short
        vertx.setPeriodic(1, new Handler<Long>() {
            @Override
            public void handle(Long aLong) {
                // Otherwise will overflow our console
                if (MyFirstVerticle.counter.intValue() > 0) {
                    System.out.println(MyFirstVerticle.counter.intValue());
                }
            }
        });
    }
}