text:
Q: Looping over forecast functions in tsCV I have a loop below looping over 4 time series forecast methods in tsCV (rolling forecast origin). The 3rd method in list, y, does not break the loop. However, the results table, z, whose purpose is to store MAE (mean absolute error) records NaN for this user defined function.
This forecast function is user defined as I need to specify damped=T
library(forecast)
x <- 8  # t +
y <- list(ses
          , holt
          , function(j, k){forecast(holt(j, h=k, damped=T))}, hw
          )
z <- list()

for (i in seq_along(y))
{
  a <- data.frame(tsCV(AirPassengers, y[[i]], h=x))
  a[1:12, ] <- NA  # 1st 12 months' forecast likely to be meaningless
  b <- colMeans(abs(a), na.rm=T)
  c <- data.frame(model = i
                  ,h = 1:x
                  ,mae = b
                  )
  z[[i]] <- c
}

z <- do.call(rbind, z)
z$model <- as.factor(z$model)

I got my idea for the user defined function here:
http://pkg.robjhyndman.com/forecast/reference/tsCV.html#see-also
Thank you.

A: As per the documentation for tsCV, the supplied function needs to have an argument actually named "h". So just change your function to
y <- list(ses, holt, function(j, h){forecast(holt(j, h=h, damped=T))}, hw)

When you do that, no NaN values are returned.


text:
Q: Pre Increment in the IF statement has no effect. Why? The pre-increment in the IF statement has no effect. Can anyone please explain?
<?php
     $x = 10;
     if($x < ++$x)
     {
       echo "Hello World";
     }
?>

A: As shown by the opcode dump below, and it shows:

*

*$x is assigned value 10

*$x is then incremented to 11 at the memory location

*if is executed

Therefore, when you are making the if you are effectivelly comparing variables (memory location) $x with $x and not values 10 and 11.
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
    2     0  E >   ASSIGN                                                   !0, 10
    3     1        PRE_INC                                          ~2      !0
          2        IS_SMALLER                                               !0, ~2
          3      > JMPZ                                                     ~3, ->5
    5     4    >   ECHO                                                     'Hello+World'
    7     5    > > RETURN                                                   1

What your code does, is really the following:
<?php
$x=10;
++$x;
if ($x < $x){

The order of evaluation of the operands seems not guaranteed inside a if block, which means the value of $x may be incremented as you seem to expect, or at some other time. the pre_increment has a not well defined behavior.
To fix this, use the increment, it has a very well defined behavior:
<?php
$x = 10;
if ($x < $x++){
echo "hello world";
}

I say the pre_inc behavior is not well defined, because it varies from php interpreter to interpreter. Here's an example of the code that works "as you'd think is expected": https://3v4l.org/n0v6n#v5.0.5
and here's how it "fails": https://3v4l.org/n0v6n#v7.0.25

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to connect my client to a node.js server on cloud foundry This code works perfectly on localhost but doesn't work after pushing it on cloud foundry...
this is the server code :
var net = require("net"),
    JsonSocket = require("json-socket");

var port = process.env.VCAP_APP_PORT || process.env.PORT || '3000';
var server = net.createServer();

//DEFINE A JSON MODEL FOR TAG DATAS
var tags = [];
var ids = [1, 2, 3, 4, 5];
var date = new Date();
for (var i = 0; i < ids.length; i++) {
    tags.push({id: ids[i],
               timestamp: date,
               position: [0, 0]
           });
    console.log(tags[i]);
}

function update(tags, i){
    var now = new Date();
    tags[i].timestamp = now;
    if(tags[i].position[0] < 180 && tags[i].position[0] > -180){
        tags[i].position[0] += Math.floor(Math.random()*3 - 1);
    } else {
        tags[i].position[0] = 0;
    }
    if(tags[i].position[1] < 180 && tags[i].position[1] > -180){
        tags[i].position[1] += Math.floor(Math.random()*3 - 1);
    } else {
        tags[i].position[1] = 0;
    }
}

server.listen(port);
console.log('Socket emitting on port: '+port);

server.on("connection", function(socket) {
    console.log('New connection');
    socket = new JsonSocket(socket);
    console.log('JsonSocket created');
    var i = 0;
    socket.on("message", function(message) {
        console.log('Mesaage received');
        if(message.command == "newData"){
            //remplir l'array
            //message.data.position[0] --> x
        }else{
            streamInterval = setInterval(function() {
                if(i<tags.length){
                   socket.sendMessage(JSON.stringify(tags[i]));
                   update(tags, i);
                   i++;
                } else {
                    i = 0;
                    socket.sendMessage(JSON.stringify(tags[i]));
                    update(tags, i);
                    i++;
                }
            }, 1000); //SET INTERVAL DURATION IN MS
        }
    });
});

So basically i'm just waiting for a message starting a connection. After that I send all my data to the client.
This is the code of my client :
var net = require('net'),
    JsonSocket = require('json-socket');

var port = 80;
var host = 'locationserver.apps.eu01.cf.canopy-cloud.com';
var socket = new JsonSocket(new net.Socket());

socket.connect(port, host);

socket.on('connect', function(err) {
    console.log('client connected');
    socket.sendMessage({command: 'start'});
    console.log('message sended');
    socket.on('message', function(msg) {
        console.log(msg);
    });
});

On localhost this is the result :
client connected
message sended
{"id":1,"timestamp":"2016-04-12T12:36:33.491Z","position":[0,0]}
{"id":2,"timestamp":"2016-04-12T12:36:33.491Z","position":[0,0]}
{"id":3,"timestamp":"2016-04-12T12:36:33.491Z","position":[0,0]}
{"id":4,"timestamp":"2016-04-12T12:36:33.491Z","position":[0,0]}
{"id":5,"timestamp":"2016-04-12T12:36:33.491Z","position":[0,0]}

But if I put the server on cloud foundry i get this :
client connected
message sended

And then it stop...
I have no error.. nothing. But on cloud foundry my debug message saying that a client is connected doesn't appear ! (console.log('New Connection') line 38)...
I have some connection but i suppose it's just the keep alive system of cloud foundry..
Does someone have some information about this ?
cloud foundry just said to use : var port = process.env.VCAP_APP_PORT || process.env.PORT || '3000'; And i suppose I then have to bind my client on port 80 but i'm not sure of that...
Thank you
EDIT : content of process.env
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT PWD: '/home/vcap/app',
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT NODE_HOME: '/home/vcap/app/.heroku/node',
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT MEMORY_LIMIT: '1024m',
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT CF_PROCESS_TYPE: 'web',
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT VCAP_APP_HOST: '0.0.0.0',
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT PORT: '61231',
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT CF_INSTANCE_PORTS: '[{"external":61231,"internal":61231}]',
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT HOME: '/home/vcap/app',
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT CF_INSTANCE_INDEX: '0',
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT CF_INSTANCE_IP: '10.0.2.54',
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT VCAP_SERVICES: '{}',
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT NODE_ENV: 'production',
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT CF_INSTANCE_PORT: '61231',
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT LANG: 'en_US.UTF-8',
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT MEMORY_AVAILABLE: '1024',
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT WEB_CONCURRENCY: '2',
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT PATH: '/home/vcap/app/.heroku/node/bin:/bin:/usr/bin:/home/vcap/app/bin:/home/vcap/app/node_modules/.bin',
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT VCAP_APPLICATION: '{"limits":{"mem":1024,"disk":1024,"fds":16384},"application_id":"28c1b6b7-230c-4d54-9954-3b837e65b128","application_version":"b835475f-7205-4f27-abc6-ea125c600191","application_name":"locationServer","application_uris":["locationserver.apps.eu01.cf.canopy-cloud.com"],"version":"b835475f-7205-4f27-abc6-ea125c600191","name":"locationServer","space_name":"Agile Unit","space_id":"19879db7-9f82-4ccf-93d4-31ce7a1f9e72","uris":["locationserver.apps.eu01.cf.canopy-cloud.com"],"users":null,"instance_id":"0dbb0c8e138d4d6b869b1ac6fcf4b66b","instance_index":0,"host":"0.0.0.0","port":61231,"started_at":"2016-04-12 13:27:37 +0000","started_at_timestamp":1460467657,"start":"2016-04-12 13:27:37 +0000","state_timestamp":1460467657}',
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT USER: 'vcap',
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT VCAP_APP_PORT: '61231',
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT _: '/home/vcap/app/.heroku/node/bin/node' }
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT WEB_MEMORY: '512',
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT TMPDIR: '/home/vcap/tmp',
Tue Apr 12 2016 13:27:39 GMT+0000 (UTC) App/0   OUT { CF_INSTANCE_ADDR: '10.0.2.54:61231',

A: You should log
var port = process.env.VCAP_APP_PORT || process.env.PORT || '3000'; to check which port is used when you deploy it.
On your client side, what happens is that the port is probably wrong (port 80).
It doesn't show any error on your client side because you didn't print it :
socket.on('connect', function(err) {
    if (err) {
      console.log(err);
    }
    console.log('client connected');
    socket.sendMessage({command: 'start'});
    console.log('message sended');
    socket.on('message', function(msg) {
        console.log(msg);
    });
});

What probably happens is that it can't connect and send the message, so it goes on timeout.
EDIT :
After looking at cloud foundry docs, it's written that the traffic is redirect going to port 80 (http) or 443 (https) is redirected on the environment port.

A: I'm now using socket.io and everything works perfectly
see at http://socket.io/ and an exemple : http://socket.io/get-started/chat/
The problem with cloud foundry is that Everything used http ! You can't use TCP on it yet.. they are working on it.


text:
Q: How to take screenshot of current window using PHP? I am trying to prepare desktop application using PHP Nightrain.
I want to take screen shot of open window after every 10 seconds. I tried using html2canvas but it is taking screen shot of application open page.
If I will open Microsoft word and work inside it that time i want screen shot of it using PHP.
Is it possible using PHP?
And one more thing I want to make desktop application using PHP which is OS compatible.

A: This cannot be done with php alone. You will need javascript to take the screenshot, convert it into a string and send it via ajax to a php script which would then save the content.
To do that you can use this library http://html2canvas.hertzen.com/. Now the magic happens in the next few lines of code:
// an example html page
<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
    <script type="text/javascript" src="./javascripts/html2canvas.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('#screenshot').on('click', function(e){
                e.preventDefault();
                html2canvas($('body'), {
                    onrendered: function(canvas){
                        var imgString = canvas.toDataURL();
                        window.open(imgString);
                        $.ajax({
                            url: '',
                            type: 'POST',
                            data: {
                                file: imgString
                            },
                            success: function(response){
                                //alert('Everything works fine.');
                            },
                            error: function(response){
                                //alert('Server response error.');
                            }
                        });
                    }
                });
            });
        });
    </script>
</head>
<body>

As far as the IE 7 & 8 support goes - google (and other giant web sites) have stated to support up to 1 version back from the latest. So, if the current version is 10, they will only support 9 and 10. I believe this is a good practice and I'm using it with my clients as well. IE < 8 is a big pain in the ... to be working with if you're developing advanced web pages. If your client still insists having IE 7 & 8 support, you may want to checkout Modernizr and html5shiv which may be able to help you bring the html5 support to IE.

A: Will only work on servers, check how about this:
<?php
// capture the screen
$img = imagegrabscreen();
imagepng($img, 'screenshot.png');
?>

OR
<?php
// Capture the browser window
$Browser = new COM('InternetExplorer.Application');
$Browserhandle = $Browser->HWND;
$Browser->Visible = true;
$Browser->Fullscreen = true;
$Browser->Navigate('http://www.stackoverflow.com');

while($Browser->Busy){
  com_message_pump(4000);
}

$img = imagegrabwindow($Browserhandle, 0);
$Browser->Quit();
imagepng($img, 'screenshot.png');
?>

Searching is useful for a fast answer ;)
Website screenshots using PHP


text:
Q: Rod cut at two points, expected length of largest part This question is similar to this but I cant find what goes wrong in my answer. The full statement of problem is this:

If a 1 meter rope is cut at two uniformly randomly chosen points (to give three pieces), what is the average length of the largest piece?

What I am doing:
|-------|------|------|
0       x      y      1

I assume rod as of being length 1 unit and divide it at distance $x$ from left and another cut is at distance $y$ from left ($y > x$). Then I take two cases:

*

*If $x \ge \frac{1}{2}$ then wherever we cut $y$ we always get $x$ as largest. So expectation is
$$\int_{1/2}^{1}x(1-x) dx = \frac{1}{12}$$

*If cut is made $\frac{1}{3} \le x \le \frac{1}{2}$ then $y$ may lie only in region $1-x$ to $2x$ for leftmost part to be largest. Then we have
$$\int_{1/3}^{1/2} x(3x-1) dx = \frac{1}{54}$$
So i thought expected length to be $1/12 + 1/54 = \frac{11}{108}$ but this is very wrong correct result is $11/18$

A: Another approach: multivariable. Let the cuts be $x,y$ from the left, $y>x$. Then the pieces are $x,\,y-x,\,1-y$. The desired expected value is then $2$ times
$$\frac12 E=\iint\limits_{x>y-x\\x>1-y} x\,\mathrm{d}x\,\mathrm{d}y+
\iint\limits_{y-x>x\\y-x>1-y} (y-x)\,\mathrm{d}x\,\mathrm{d}y+
\iint\limits_{1-y>y-x\\1-y>x} (1-y)\,\mathrm{d}x\,\mathrm{d}y.$$

$$\frac12 E=
\left(\int\limits_{1/3}^1 \int\limits_{1-x}^{2x}
-\int\limits_{1/2}^1 \int\limits_{1}^{2x}
-\int\limits_{1/2}^1 \int\limits_{1-x}^{x}\right) x\,\mathrm{d}y\,\mathrm{d}x+\\
\left(\int\limits_{0}^{1/2}\int\limits_{2x}^{1}-
\int\limits_{0}^{1/3}\int\limits_{2x}^{(x+1)/2}\right) (y-x)\,\mathrm{d}y\,\mathrm{d}x+\\
\left(\int\limits_{0}^{1/2}\int\limits_{x}^{1-x}-
\int\limits_{0}^{1/3}\int\limits_{(1+x)/2}^{1-x}\right) (1-y)\,\mathrm{d}y\,\mathrm{d}x$$
It appears that it suffices to take only the first integral, the other should be equal by symmetry.
$$\frac16 E=
\int\limits_{1/3}^1 (3x-1)x\,\mathrm{d}x-
\int\limits_{1/2}^1 (2x-1)x\,\mathrm{d}x-
\int\limits_{1/2}^1 (2x-1)x\,\mathrm{d}x=\\
\frac{14}{27}-2\cdot \frac{5}{24}=\frac{11}{108}.$$


text:
Q: How do I convert a numpy array filled with strings to json n=int(input('n='))
array = np.empty(shape=
[n,4],dtype='|S10')
.
.
.
.
array= array.tolist()
array =[[b'1',b'1/1/1',b'1',b'1']]
dump(array,json_file)

I got an error: Object of type bytes is not JSON serializable

A: Why you type 'b' before the strings ?
Your code is not complete, I modified it to let it work:
import numpy as np
import json

n=int(input('n='))
array = np.empty(shape=[n,4],dtype='|S10')
array = [['1', '1/1/1', '1', '1']]
with open('test.json', 'w') as json_file:
    json.dump(array, json_file)

That if you want your current code to work, if you want to serialize a numpy array of strings you must use 'U1' dtype and then convert it to list, like this:
import numpy as np
import json

n = int(input('n='))
array = np.empty(shape=[n,4], dtype='U1')
array = array.tolist()
with open('test.json', 'w') as json_file:
    json.dump(array, json_file)


text:
Q: Which constructs in Verilog can contain function definition? I am new to verilog and trying to figure out where the function can be defined/declared in verilog (like I know function can be defined in packages, what else?). Thanks in advance.

A: In Verilog, a function can be declared between

*

*module and endmodule (ie in the current region of a module - inside a module, but outside an initial or always block)

*generate and endgenerate
That's it.
In System-Verilog, a function can be declared between

*

*module and endmodule

*generate and endgenerate
and

*

*class and endclass

*interface and endinterface

*checker and endchecker

*package and endpackage

*program and endprogram
and

*

*outside a module / interface / checker / package / program

A: Probably, easiest way to declare and use function is like, declare all your functions in <module_function_pkg>.vh and include that to design verilog file.
Use it as @dave_59 said in comment.


text:
Q: angular2: how to test a component which has an observable time interval I have a slide-show component that has an Input array of slide objects and shows each one as long as it's been defined in slide.time of itself. also there are two buttons that clicking them has to slide to the next item and reset the timer. in order to make this work, I'm using Observables like this:
/**
 * a "SUBJECT" for pausing(restarting) the slider's auto-slide on user's click on left and right arrows
 * @type {Subject}
 */
private pauser = new Subject();

/**
 * the main observable for timer (before adding the pause/reset option)
 * @type {Observable<T>}
 */
private source = Observable
    .interval(1000)
    .timeInterval()
    .map(function (x) { /*return x.value + ':' + x.interval;*/ return x })
    .share();

/**
 * the final timer, which can be paused
 * @type {Observable<R>}
 */
private pausableSource = this.pauser.switchMap(paused => paused ? Observable.never() : this.source);

/**
 * the subscription to the timer which is assigned at OnInit hook , and destroyed at OnDestroy
 */
private subscription;

ngOnInit(){
    this.subscription = this.pausableSource.subscribe(() => {
        //doing changes to the template and changing between slides
    });
    this.pauser.next(false);
}

ngOnDestroy() {
    this.subscription.unsubscribe();
}

and it's working properly.
now to test this component, I'm giving it some data within a test-host component and want to check it's functionality like this:
it("should show the second (.slidingImg img) element after testHost.data[0].time seconds
    have passed (which here, is 2 seconds)", () => {
    //testing
});

i tried many things that i found in docs or anywhere on the internet, but none of them work for me. the problem is that I can't mock the passage of time in a way that the observable timer would perform next actions, and it's like no time has passed whatsoever. two of the ways that haven't worked for me are these:
it("should show the second (.slidingImg img) element after testHost.data[0].time seconds
    have passed (which here, is 2 seconds)", fakeAsync(() => {
    fixture.detectChanges();
    tick(2500);
    flushMicrotasks();
    fixture.detectChanges();
    let secondSlidingImg = fixture.debugElement.queryAll(By.css('.slidingImg'))[1].query(By.css('img'));
    expect(secondSlidingImg).toBeTruthy();
    //error: expected null to be truthy
}));

i got this from angular2 docs.
and:
beforeEach(() => {
    fixture = TestBed.createComponent(TestHostComponent);

    testHost = fixture.componentInstance;

    scheduler = new TestScheduler((a, b) => expect(a).toEqual(b));

    const originalTimer = Observable.interval;
    spyOn(Observable, 'interval').and.callFake(function(initialDelay, dueTime) {
        return originalTimer.call(this, initialDelay, dueTime, scheduler);
    });
    // or:
    // const originalTimer = Observable.timer;
    // spyOn(Observable, 'timer').and.callFake(function(initialDelay, dueTime) {
    //     return originalTimer.call(this, initialDelay, dueTime, scheduler);
    // });
    scheduler.maxFrames = 5000;

});
it("should show the second (.slidingImg img) element after testHost.data[0].time seconds
    have passed (which here, is 2 seconds)", async(() => {
    scheduler.schedule(() => {
        fixture.detectChanges();
        let secondSlidingImg = fixture.debugElement.queryAll(By.css('.slidingImg'))[1].query(By.css('img'));
        expect(secondSlidingImg).toBeTruthy();
        //error: expected null to be truthy
    }, 2500, null);
    scheduler.flush();
}));

i got this approach from this question.
so I desperately need to know how exactly should I simulate time passage in my unit test so that the component's observable time interval would really trigger...
versions:
angular: "2.4.5"
"rxjs": "5.0.1"
"jasmine": "~2.4.1"
"karma": "^1.3.0"
"typescript": "~2.0.10"
"webpack": "2.2.1"

A: fakeAsync doesn't work for some case with RxJs. You need to manually move internal timer in RxJs. Something along those lines:
import {async} from 'rxjs/internal/scheduler/async';
...

describe('faking internal RxJs scheduler', () => {
  let currentTime: number;

  beforeEach(() => {
    currentTime = 0;
    spyOn(async, 'now').and.callFake(() => currentTime);
  });

  it('testing RxJs delayed execution after 1000ms', fakeAsync(() => {
    // Do your stuff
    fixture.detectChanges();
    currentTime = 1000;
    tick(1000);
    discardPeriodicTasks();

    expect(...);
  }));
});

A: Best way I found for testing this is Marble Testing:
Tutorial: https://medium.com/@bencabanes/marble-testing-observable-introduction-1f5ad39231c
You can control emits by order and time, which seems to be exactly what you need.


text:
Q: git fetch, git pull not working in my VM in GCP I am a GCP user. I have a VM that is running in GCP.
But recently, when I try to run the "git pull" or "git fetch" commands to update my project, it just hung there, and there are no responses.
My project is on GitHub.
It worked very well a few weeks ago. I didn't change any ssh or network config.
Not sure what kind of problem it is. I will appreciate it if anyone could give some advice.

A: I found the problem and resolved it. Hope this can help other people who faced the same issue as mine.
This was my ssh config file
Host github.com
      HostName github.com
      PreferredAuthentications publickey
      IdentityFile ~/.ssh/id_rsa
      AddKeysToAgent yes

After I removed the line AddKeysToAgent yes, it works now. I don't know why it worked before.

A: First, you need to make sure if you are indeed using ssh on GCP in your repository folder:
cd /path/to/repository
git remote -v
# Check the URL is
# git@github.com:you/yourRepository
#              ^^^ (note the :)
# Or:
# ssh://git@github.com/you/yourRepository
#                    ^^^ (note the /)

Check also your environment variables:
env|grep -i SSH

(A GIT_SSH... environment variable might affect how Git operates with SSH)
And see if the network route is still opened from your GCP shell to GitHub:
curl -v telnet://github.com:22
# You should see
Connected to github.com (140.82.121.3) port 22 (#0)

For testing, check if you can use (while entering your GitHub account and a GitHub Personal Acccess Token or PAT) use HTTPS:
git ls-remote https://github.com/You/yourRepository

If you are using SSH, activate traces on SSH ,and on Git itself with TRACE2:
export GIT_SSH_COMMAND='ssh -Tv'
GIT_TRACE2_EVENT=1 git pull
# or
GIT_TRACE2=1 git pull

As noted in the OP Louis Hong's answer, activating the traces would show the step where, by tring to add a key to an ssh-agent (from the ~/.ssh/config), said ssh-agent might request a passphrase for another (encrypted) key, thereby hanging on stdin.


text:
Q: In Spring, when transactions happen close to each other, can they get merged? Context
I support a fairly conventional Spring Boot application, which uses a transactional datastore (Oracle). The data source is configured as an instance of HikariDataSource, and setting up of the transaction manager is left to Spring Boot.
Service methods are annotated with plain @Transactional annotation, which implies Propagation.REQUIRED. There are no @Transactional annotations at lower levels (i.e., Dao).
Symptoms
The symptoms I am observing now are:

*

*Through a duplicated request, the @Transactional method is being called twice in quick succession, with the same arguments.

*

*First invocation is successful.

*Second invocation fails due to duplication, and rolls back its transaction.

*The end result within the database is as if none of the invocations occurred.

My suspicion is that the two invocations manage to somehow share a physical transaction.
Questions
The documentation states that:

PROPAGATION_REQUIRED enforces a physical transaction, either locally for the current scope if no transaction exists yet or participating in an existing 'outer' transaction defined for a larger scope.

So far I was not able to get a clear understanding of what the "'outer' transaction" means.
My questions are:

*

*Is the term "'outer' transaction" restricted to one @Transactional method calling another @Transactional method?

*Given the Propagation.REQUIRED setting, when a non-nested @Transactional method is called twice in a quick succession, is it possible that both invocations will share the same physical transaction?


text:
Q: How do I modify outgoing SIP messages from Yate? I need to strip the rport parameter from the Via field of SIP messages being generated by Yate (for compatibility with a broken peer). Can I use the scripting capabilities of Yate to do this? How do I intercept and modify outgoing SIP messages?

A: I discovered, by reading the code, that Yate already supports this feature. In accfile.conf, in the section defining the sip server to register to, place the following line:
xsip_flags=1

This prevents the rport parameter from being placed in SIP messages. This may break routing if you are behind a NAT, so beware.
An example config would therefore be:
[sip_service]
enabled=yes
protocol=sip
description=sip_service
username=user
domain=somewhere.com
authname=auth
password=secret
server=somewhere.com
xsip_flags=1


text:
Q: how to post data to remote server in android app
Possible Duplicate:
How to do a HTTP Post in Android?

I want to send the two values to a server ,say http://localhost/twoVal.php, which will further process the  information.
for example,
i have got the val1 = 12 and val2 = 13
i want to post these data to above mentioned URL.  (May be some URL need not be localhost) how to do it?
Also, data  needs to be sent as part of HTTP header (POST) & not as query parameters.

A: Have you even tried to search for the answer?

*

*Http Post in android

*Android, sending XML via HTTP POST (SOAP)

*Http post in Java

*Http post in Java with UrlConnection

*HttpClient android docs


text:
Q: Visual Studio 2013 extension file doesn't open While trying to install the XNA Game Studio 4.0 Refresh extension, doubleclicking on the .vsix does nothing at all. Entirely nothing. No " stopped responding", no warning, nothing at all.

A: Only doing a repair through the installer seemed to fix this.


text:
Q: How to use the new floor value in your calculation php I am facing the below issue with my php code.
$value = 28.835223;
$newValue = floor($value);

When I echo $newValue, it will show 28.
But when I use $newValue for a new calculation, the value is 28.835223.
How can I use the new floor value "28" in my calculations?

A: Try below code
$value = 28.835223;
$newValue = (int) $value;
echo $newValue;


text:
Q: How do you find the logo code on theme file or where can I find the header theme file? I am trying to find the header.php file and/or the code for the logo on any theme file. Under appearance- editor section of my website ( www.pithandsubstance.com ) I can only find function.php and style.php files.
Please note : I am new to Wordpress and highly detailed instructions will be very appreciated.
Thank you in advance,
PS

A: You are using the Child theme for the Vlog theme. Header file should be in the parent theme file.
The parent theme file name should be Vblog.

Go to Dashboard --> Appearance --> Editor.

Top (just below the top) of right corner you can find "Select theme to edit:" text. There is a select box. Select Vblog from that select box. Then click select button. Then you can find header.php file.


text:
Q: How can we order a union query in MySQL? I have a stored procedure like below in MYSQL:
    (SELECT 1 AS sort_col, col_a, col_b FROM t1 WHERE col_b LIKE %some% AND col_b LIKE %thing%)
    UNION
    (SELECT 2, col_a, col_b FROM t1 WHERE col_b LIKE %some% OR col_b LIKE %thing%)
 ORDER BY sort_col, col_a;

I want the result of first select show at first, but some results of the first are common in second too, and second select changed their sort_col to 2.(I can't use LIMIT in my selects)
what can I do for solve it?

A: Use a sub-query:
SELECT * FROM
(
   (SELECT 1 AS sort_col, col1a, col1b FROM t1)
   UNION
   (SELECT 2, col2a, col2b FROM t2)
) tbl
ORDER BY sort_col, col1a;

Edit (after OP's edit)
SELECT * FROM
(
  (SELECT 1 AS sort_col, col_a, col_b
     FROM t1
    WHERE col_b LIKE %some%
      AND col_b LIKE %thing%)
  UNION
  (SELECT 2, col_a, col_b
     FROM t1
    WHERE col_b LIKE %some%
       OR col_b LIKE %thing%)
) tbl
ORDER BY sort_col, col_a;


text:
Q: array empty when component rerenders I've tried searching, tried different approaches in the code, also had a friend help me but to no avail. My problem is that an array that I get from props is empty after setting some other state.
I have a carousel component. This component has two children:
Gallery (displays the images, either as cards, horizontaly or as a ul, stackad vertically)
and
Pagination (which is two buttons that return on click events and recieve booleans to be disabled).
Carousel gets an array called 'puffItems'. There are 11 items in this array. When console logging both in the Carousel and in Gallery (which recieves the array) the array is first '0', then rerenders and changes to '11'. After clicking "Next" Carousel rerenders and now the array rerenders only one time and its '0'. The funny thing is this only happens in mobile view. It works as expected in desktop view.
This is the code:
Carousel:
const Carousel = ({
forwardButtonText,
backwardButtonText,
puffItems,}: Props) => {
const widthOfOnePuff = (px(gridMaxWidth - 16 * 2) + Theme.spacing.space2) / 3;

const [cssState, setcssState] = useState({
    translate: 0,
    transition: 0.40,
});

const isPhone = useMediaQuery({
    minWidth: breakpointsNumber.phone,
    maxWidth: breakpointsNumber.tablet - 1,
});

const { translate, transition } = cssState;
const [currentIndex, setCurrentIndex] = useState<number>(3);
const [slideWidth, setSlideWidth] = useState<number>(widthOfOnePuff * 3);
const [numberOfPuffsToSlide, setNumberOfPuffsToSlide] = useState<number>(3);

useEffect(() => {
    if (isPhone) {
        setSlideWidth(widthOfOnePuff);
    }
}, [isPhone]);

console.log('puffItems', puffItems);

const onPreviousSlide = () => {
    setcssState({
        ...cssState,
        translate: translate - slideWidth,
    });

    setCurrentIndex(prev => prev - numberOfPuffsToSlide);
};

const onNextSlide = () => {
    setcssState({
        ...cssState,
        translate: translate + slideWidth,
    });

    setCurrentIndex(prev => prev + numberOfPuffsToSlide);
};

return (
    <CarouselContainer>
        <Gallery
            puffItems={puffItems}
            translate={translate}
            transition={transition}
            isPhone={isPhone}
        />
        <Space top={Theme.spacing.space3}>
            <Pagination
                forwardButtonText={forwardButtonText}
                backwardButtonText={backwardButtonText}
                onPreviousSlide={onPreviousSlide}
                onNextSlide={onNextSlide}
                inactivateForwardButton={puffItems.length <= currentIndex}
                inactivateBackwardButton={currentIndex === 3}
            />
        </Space>
    </CarouselContainer>
);};export default Carousel;

Gallery:
const Gallery = ({
puffItems,
translate,
transition,
isPhone,}: GalleryProps) => {
const listLength = puffItems.length;
let numberOfColumns = 0;
if (isPhone) {
    numberOfColumns = listLength % 3 === 0
    ? Math.floor(listLength / 3)
    : Math.floor(listLength / 3) + 1;
}

console.log('puffItems gallery ', puffItems.length);

return isPhone ? (
    <div>
        <GalleryListStyle
            columns={numberOfColumns}
            myTranslate={translate}
            transition={transition}>

            <GalleryListItems
                puffItems={puffItems}
                columns={numberOfColumns}
            ></GalleryListItems>

        </GalleryListStyle>
    </div>
) : (
    <GalleryCardStyle myTranslate={translate} transition={transition}>
        {puffItems.map((puffItem, index) => (
            <EpiFragments fragments={[puffItem]} key={index} />
        ))}
    </GalleryCardStyle>
);};export default Gallery;

and finally, Pagination:
const Pagination = ({
forwardButtonText,
backwardButtonText,
onPreviousSlide,
onNextSlide,
inactivateForwardButton,
inactivateBackwardButton,}: Props) => {
return (
    <PaginationContainer>
        <Button
            variant={ButtonVariant.Tertiary}
            onClick={onPreviousSlide}
            disabled={inactivateBackwardButton}
        >
            {backwardButtonText}
        </Button>

        <Button
            variant={ButtonVariant.Tertiary}
            onClick={onNextSlide}
            disabled={inactivateForwardButton}
        >
            {forwardButtonText}
        </Button>
    </PaginationContainer>
);};export default Pagination;

In the image below you can see, that number 1,2 and 3 are the after page-refresh and number 4 is when I click 'Next', meaning 'onNextSlide' is prompted.

Does anyone know why this is happening? And why only in mobile view (chrome developer tool, ~375px width)?

A: I do a 'splice' on the array further down in 'GalleryListItems', which alters the array.. changed it to slice. This solves the problem. Thanks anyways!


text:
Q: Powershell for O365 GUI: permissions Background:
It seems someone has set user-mailbox permissions using the O365 GUI (not exchange online GUI):
Issue:
This means I can't use the normal exchange-powershell method to check mailbox permissions... like we can if set using Exchange Online Admin Center GUI or Add-MailboxPermission:
Import-PSSession ( New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Authentication Basic -AllowRedirection -Credential (Get-Credential myname@myco.com ) )
Get-MailboxPermission SharedUser@myco.com

^^ This does not return the permissions set in O365 GUI. Only Exchange Online.
Question:
What is the correct commandlet to manage the permissions set using the O365 GUI ?
Previous work:
I have tried looking at the MSOL-User commandlets also, as these seem to use O365 rather than exchange online... but they don't have one relating to permissions.
Also I have previously checked mailboxfolderpermission.
More Clarifications:
StaffMember@myco.com can see SharedUser@myco.com's mailbox in outlook.
This is also represented in:
Office 365 control panel / GUI > Users > SharedUser > Mail Settings > Mailbox Permissions
These permissions do NOT seem to show in Exchange Admin Center or exchange powershell.

A: There are three types of permissions you can set over the mailbox: FullAccess, SendAs and SendOnBehalf. Each of them can be checked/managed using different cmdlets:

*

*FullAccess (Read and manage in O365 GUI) can be viewed using Get-MailboxPermission and managed using Add-MailboxPermission/Remove-MailboxPermission

*SendAs can be viewed using Get-RecipientPermission and managed using Add-RecipientPermission/Remove-RecipientPermission

*SendOnBehalf can be viewed using Get-Mailbox and managed usingSet-Mailbox (parameter GrantSendOnBehalfTo)

Clarifying the question from comments:

Unfortunately Get-RecipientPermission says "applied to: Exchange online" and I am specifically talking about Office365 which seems to be a different set of cmdlets. Other-User had full access to shared-user's mailbox, yet Get-MailboxPermission shared-user showed nothing about the Other-User.

The fact that permissions can be set via O365 portal doesn't mean that the permissions are not set in Exchange Online. Office 365 user objects (the ones you can access via Get-MsolUser) cannot have FullAccess/SendAs/SendOnBehalf set on them, only mailboxes can have them.
When you set the permission (let's say you add Read and manage over shared-user to other-user) via O365 portal, the change should reflect on the Exchange Admin Center (when you check shared-user you'll see other-user in Full Access field) and in Get-MailboxPermission shared-user. Not sure what happened that you haven't seen these permissions but check these three first. It might be some delay in synchronization too.


text:
Q: Change background color for certain cells in the appending row to a table using JQuery I'm appending a row to a table. How can I change the background color in that row for a group of cells. Say column has 25 columns; columns starting from 17 till 22 needs a background color change.
This is what I tried so far:
$("#table1").append(row1);
$(row1).children('td')
    .not('td:eq(0)')
    .not('td:eq(0)')
    .css({ "background-color": workcolor });

Here I use Childeren 'td' which all cells in row got colored instead I need a particular cells background need to changed as per ID of column.
I added my Html code You can clarify this:

      Image
      Employee
      00:00
      01:00
      02:00
      03:00
      04:00
      05:00
      06:00
      07:00
      08:00
      09:00
      10:00
      11:00
      12:00
      13:00
      14:00
      15:00
      16:00
      17:00
      18:00
      19:00
      20:00
      21:00
      22:00
      23:00

A: You can try .filter()
$(row1).find('td').filter(function(index){
 return parseInt(this.id) >= 17 && parseInt(this.id) <= 22
}).css({ "background-color": yellow});

The above example using td id this.id you can change it with index passing on filter function if you working with td index
and you can still set the all td for a row by using .css() before filter()
$(row1).find('td').css({ "background-color": workcolor }).filter(function(){
   return parseInt(this.id) >= 17 && parseInt(this.id) <= 22
}).css({ "background-color": yellow});

Notes:

*

*No need to use .find('td') if you're looking for row id not td id

*If you want to reference the row by td you can keep using .find('td') and on filter you can use parseInt($(this).closest('tr').attr('id'))
Up to your question update .. you can use just css to do that
th:nth-child(n + 20):not(:nth-child(26)),
td:nth-child(n + 20):not(:nth-child(26)){
  background : yellow;
}

Explanation:

Why (n + 20)? because nth-child index is starting from 1 .. so if
  you count the element with id 17 you'll find its index is 20 and n + 20 will select the element with index is 20 and above and
  :not(:nth-child(26)) to  not the last column

A: You can try this way :

/* added this loop to append tr you can ignore this loop as this only for demo */
for(i=0; i<=10; i++){
  var row = $('

');
  for(j=0; j<=25; j++){
    row.append(''+j+'	');
  }
  $("#table1 tbody#body1").append(row);
}
// demo code ends here

// actual logic starts here

var startIndex = $('#table1 thead th').index($('#table1 thead th[id=17]')) // get the index of id 17

var endingIndex = $('#table1 thead th').index($('#table1 thead th[id=22]')) // get the index of id 22

// iterates through all rows.
$.each($('#table1 #body1 tr'), function(i, item) {
  // update background-color of td between the index values 17 and 22
  $(item).children('td:lt('+(endingIndex + 1)+'):gt('+(startIndex - 1)+')').addClass('highlight')
});
.highlight{background-color: yellow;}

      Image
      Employee
      00:00
      01:00
      02:00
      03:00
      04:00
      05:00
      06:00
      07:00
      08:00
      09:00
      10:00
      11:00
      12:00
      13:00
      14:00
      15:00
      16:00
      17:00
      18:00
      19:00
      20:00
      21:00
      22:00
      23:00

So as a first step we need to find starting index and ending index in which we want to fill the background color.
 var startIndex = $('#table1 th').index($('#table1 th[id=17]')) // index is 19

 var lastIndex = $('#table1 th').index($('#table1 th[id=22]')) // index is 24

now we can iterate through each row and select columns based on starting index and last index:
$.each($('#body1 tr'), function(i, item) {
  $(item).children('td:lt('+(endingIndex + 1)+'):gt('+(startIndex -1)+')').css('background-color', 'yellow')
});

in which item is row/tr itself so from that using Jquery :lt and :gt selector we can get children(td) between those index and apply css on it.
:lt(index):gt(index) will gives all the elements in an array between this index as we also want startIndex and endingIndex along with this we incremented and decremented accordingly.

A: You could use a combination of the gt and lt selectors:
$("#table1").append(row1);
$(row1).children('td:gt(17):lt(22)').css('background-color', workcolor);


text:
Q: "Invalid conversion" error with conditional operator I'm getting compile error in this line:
cout << (MenuItems[i].Checkbox ? (MenuItems[i].Value ? txt::mn_yes : txt::mn_no) : MenuItems[i].Value)

Error:
menu.cpp|68|error: invalid conversion from 'int' to 'const char*'
menu.cpp|68|error:   initializing argument 1 of 'std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]'

MenuItems is std::vector of following class:
class CMenuItem
{
public:
string Name;
int Value;
int MinValue, MaxValue;
bool Checkbox;
CMenuItem (string, int, int, int);
CMenuItem (string, bool);
};

mn_yes and mn_no are std::strings.
Compiler is MinGW (version that is distributed with code::blocks).

A: The two possible conditional values have to be convertible to a common type.  The problem is that the left of the outer conditional:
(MenuItems[i].Value ? txt::mn_yes : txt::mn_no)

is always a string, but the right:
MenuItems[i].Value

is an int.  It tries to find a way by going const char *->string, but then it won't allow the int to const char * conversion (which is good, because it would be meaningless).  Just do:
if(MenuItems[i].Checkbox)
{
    cout << (MenuItems[i].Value ? txt::mn_yes : txt::mn_no);
}
else
{
    cout << MenuItems[i].Value;
}

or similar.


text:
Q: ayuda con calculadora en javascript estoy haciendo una calculadora con javascript y por alguna razon me arroja como valor NaN, me lo arroja en la segunda y tercera funcion, pero en la primera no, no encuentro el error, copie y pegue el codigo de la primera funcion y cambie los valores y no veo el error.
gracias.

// Variables
var button = document.getElementById("button");
var realSerieZ1 = document.getElementsByTagName("input")[0];
var imaginarySerieZ1 = document.getElementsByTagName("input")[1];
var moduleSerieZ1 = document.getElementsByTagName("input")[2];
var phaseSerieZ1 = document.getElementsByTagName("input")[3];
var realSerieZ2 = document.getElementsByTagName("input")[4];
var imaginarySerieZ2 = document.getElementsByTagName("input")[5];
var moduleSerieZ2 = document.getElementsByTagName("input")[6];
var phaseSerieZ2 = document.getElementsByTagName("input")[7];
var realParallelZ1 = document.getElementsByTagName("input")[8];
var imaginaryParallelZ1 = document.getElementsByTagName("input")[9];
var moduleParallelZ1 = document.getElementsByTagName("input")[10];
var phaseParallelZ1 = document.getElementsByTagName("input")[11];
var realParallelZ2 = document.getElementsByTagName("input")[12];
var imaginaryParallelZ2 = document.getElementsByTagName("input")[13];
var moduleParallelZ2 = document.getElementsByTagName("input")[14];
var phaseParallelZ2 = document.getElementsByTagName("input")[15];
var resultRealSerie = document.getElementsByTagName("input")[17];
var resultImaginarySerie = document.getElementsByTagName("input")[18];
var resultModuleSerie = document.getElementsByTagName("input")[19];
var resultPhaseSerie = document.getElementsByTagName("input")[20];
var resultRealParallel = document.getElementsByTagName("input")[21];
var resultImaginaryParallel = document.getElementsByTagName("input")[22];
var resultModuleParallel = document.getElementsByTagName("input")[23];
var resultPhaseParallel = document.getElementsByTagName("input")[24];

// Conversor de angulos
Math.degreesToRadians = function(degrees) {
    return degrees * Math.PI / 180;
  };
Math.radiansToDegrees = function(radians) {
    return radians * 180 / Math.PI;
};

// Calculadora
var sumSerie = function(){
    var realSerie = realSerieZ1.valueAsNumber + realSerieZ2.valueAsNumber;
    var imaginarySerie = imaginarySerieZ1.valueAsNumber + imaginarySerieZ2.valueAsNumber;
    var totalSerie = Math.hypot(realSerie,imaginarySerie);
    var sinSerie = imaginarySerie / totalSerie;
    var phaseRadSerie = Math.asin(sinSerie);
    var phaseDegSerie = Math.radiansToDegrees(phaseRadSerie);
    resultPhaseSerie.valueAsNumber = phaseDegSerie.toFixed(2);
    resultModuleSerie.valueAsNumber = totalSerie.toFixed(2);
}
var moduleAndPhaseZ1 = function(){
    var module1 = Math.hypot(realSerieZ1,imaginarySerieZ1);
    var sin = imaginarySerieZ1 / module1;
    var phaseRad = Math.asin(sin);
    var phaseDeg = Math.radiansToDegrees(phaseRad);
    phaseSerieZ1.valueAsNumber = phaseDeg.toFixed(2);
    moduleSerieZ1.valueAsNumber = module1.toFixed(2);
}
var sumParallel = function(){
    var denominatorReal = realParallelZ1.valueAsNumber + realParallelZ2.valueAsNumber;
    var denominatorImaginary = imaginaryParallelZ1.valueAsNumber + imaginaryParallelZ2.valueAsNumber;
    var denominatorModule = Math.hypot(denominatorReal,denominatorImaginary);
    var denominatorSin = denominatorImaginary / denominatorModule;
    var denominatorPhaseRad = Math.asin(denominatorSin);
    var denominatorPhaseDeg = Math.radiansToDegrees(denominatorPhaseRad);
    var module1 = Math.hypot(realParallelZ1,imaginaryParallelZ1);
    var sin1 = imaginaryParallelZ1 / module1;
    var phaseRad1 = Math.asin(sin1);
    var phaseDeg1 = Math.radiansToDegrees(phaseRad1);
    var module2 = Math.hypot(realParallelZ2,imaginaryParallelZ2);
    var sin2 = imaginaryParallelZ2 / module2;
    var phaseRad2 = Math.asin(sin2);
    var phaseDeg2 = Math.radiansToDegrees(phaseRad2);
    var nominatorModule = module1 * module2;
    var nominatorPhase = phaseDeg1 + phaseDeg2;
    var totalModule = nominatorModule / denominatorModule;
    var totalPhase = nominatorPhase - denominatorPhaseDeg;
    resultModuleParallel.valueAsNumber = totalModule.toFixed(2);
    resultPhaseParallel.valueAsNumber = totalPhase.toFixed(2);
}
// button
button.addEventListener("click", function(e){
    e.preventDefault();
    sumSerie();
    moduleAndPhaseZ1();
    sumParallel();
})
*{
    margin: 0;
    padding: 0;
    text-decoration: none;
}
body{
    width: 80%;
    margin:0 auto;
    text-align: center;
    background: rgb(200, 200, 200);
}
.serieParallel{
    box-sizing: border-box;
    width: 100%;
    background: rgb(10, 126, 221);
    border-radius: 20px;
    padding: 20px;
}
form{
    display: flex;
    justify-content: space-between;
    text-align: left;
}
form input{
    margin: 10px 0;
    width: 60px;
}
form p{
    display: inline;
}
form div{
    width: 50%;
}
<!DOCTYPE html>

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

Impedancias serie y paralelo

        <form action="">

Suma en serie:

Z1 =

                <input type="number" step="0.001">

+J

                <input type="number" step="0.001">

||

                <input type="number" step="0.001">

con fase

                <input type="number" step="0.001">

Z2 =

                <input type="number" step="0.001">

+J

                <input type="number" step="0.001">

||

                <input type="number" step="0.001">

con fase

                <input type="number" step="0.001">

Suma en parelo:

Z1 =

                <input type="number" step="0.001">

+J

                <input type="number" step="0.001">

||

                <input type="number" step="0.001">

con fase

                <input type="number" step="0.001">

Z2 =

                <input type="number" step="0.001">

+J

                <input type="number" step="0.001">

||

                <input type="number" step="0.001">

con fase

                <input type="number" step="0.001">

                <input type="submit" value="calcular" id="button">

Resultado:

                <input type="number" step="0.001">

+J

                <input type="number" step="0.001">

||

                <input type="number" step="0.001">

con fase

                <input type="number" step="0.001" style="margin-bottom: 67px">

Resultado:

                <input type="number" step="0.001">

+J

                <input type="number" step="0.001">

||

                <input type="number" step="0.001">

con fase

                <input type="number" step="0.001">

        </form>

P.D.: lamento que el codigo sea largo, luego vere si puedo hacerlo mas corto pero por ahora lo dejo asi, asi puedo ver bien los errores

A: El error es que operaste con objetos input y no con sus valores cambia tus funciones var moduleAndPhaseZ1 y var sumParallel por:
var moduleAndPhaseZ1 = function(){
    var module1 = Math.hypot(realSerieZ1.valueAsNumber,imaginarySerieZ1.valueAsNumber);
    var sin = imaginarySerieZ1.valueAsNumber / module1;
    var phaseRad = Math.asin(sin);
    var phaseDeg = Math.radiansToDegrees(phaseRad);
    phaseSerieZ1.valueAsNumber = phaseDeg.toFixed(2);
    moduleSerieZ1.valueAsNumber = module1.toFixed(2);
}

var sumParallel = function(){
    var denominatorReal = realParallelZ1.valueAsNumber + realParallelZ2.valueAsNumber;
    var denominatorImaginary = imaginaryParallelZ1.valueAsNumber + imaginaryParallelZ2.valueAsNumber;
    var denominatorModule = Math.hypot(denominatorReal,denominatorImaginary);
    var denominatorSin = denominatorImaginary / denominatorModule;
    var denominatorPhaseRad = Math.asin(denominatorSin);
    var denominatorPhaseDeg = Math.radiansToDegrees(denominatorPhaseRad);
    var module1 = Math.hypot(realParallelZ1.valueAsNumber,imaginaryParallelZ1.valueAsNumber);
    var sin1 = imaginaryParallelZ1.valueAsNumber / module1;
    var phaseRad1 = Math.asin(sin1);
    var phaseDeg1 = Math.radiansToDegrees(phaseRad1);
    var module2 = Math.hypot(realParallelZ2.valueAsNumber,imaginaryParallelZ2.valueAsNumber);
    var sin2 = imaginaryParallelZ2.valueAsNumber / module2;
    var phaseRad2 = Math.asin(sin2);
    var phaseDeg2 = Math.radiansToDegrees(phaseRad2);
    var nominatorModule = module1 * module2;
    var nominatorPhase = phaseDeg1 + phaseDeg2;
    var totalModule = nominatorModule / denominatorModule;
    var totalPhase = nominatorPhase - denominatorPhaseDeg;
    resultModuleParallel.valueAsNumber = totalModule.toFixed(2);
    resultPhaseParallel.valueAsNumber = totalPhase.toFixed(2);
}


text:
Q: Why does this code always print "not matched"? #include <stdio.h>

int main(int argc, char const *argv[])
{
    FILE *ls = popen("tmp.sh", "r");
    char char_array[256];
    while (fgets(char_array, sizeof(char_array), ls) != 0) {
       //NOP
    }
    char *ptr_somechar = &char_array[0];
    char *pointer = "high";
    if (strcmp(pointer, ptr_somechar) == 0)
    {
        printf("%s\n", "match");
    } else
    {
        printf("%s\n", "not matched");
    }
    pclose(ls);
    return 0;
}

I want to compare the output with the line. tmp.sh returns a "high". Why does this code always print "not matched"?

A: It seems that the string "high" in file is followed by a newline character and fgets reads that \n too. You need to remove that character before comparison.


text:
Q: TypeError: Cannot read property 'Symbol(dartx._get)' of null (in Flutter when adding Firestore Listener) I am unable to add a listener to my firestore document. I am getting the above error which I am not understanding as to what is causing it. My code is as follows:
 StreamSubscription<DocumentSnapshot> listener;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_){
      _initListener();
    });
  }

  _initListener() async {
    listener = FirebaseFirestore.instance
        .collection('Ref to my collection path')
        .doc('status')
        .snapshots()
        .listen((DocumentSnapshot documentSnapshot) {
            Map<String, dynamic> firestoreInfo = documentSnapshot.data();
            setState(() {
              paid = firestoreInfo['status'];
            });
            if(paid) Navigator.pop(context);
          });
      listener.onError((handleError){
      if(DEBUG) print('Cannot attach listener: Error: $handleError');
    });
  }

  @override
  void dispose() {
    listener.cancel();
    super.dispose();
  }

EDIT: MY BUILD METHOD IS AS FOLLOWS:
I am using a web view plugin to display a payment page. My intention is to read data on firebase and see when it is updated and then move to payment success or payment failure page.
@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        iconTheme: IconThemeData(
          color: Colors.white, //change your color here
        ),
        elevation: 0.0,
        title: Text("PAYMENT", style: Header),
        backgroundColor: Provider.of<CP>(context, listen: false).primary,
      ),
      backgroundColor: Color(0xfff6f7f8),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(13.0),
            child: Text('Please enter your payment details'),
          ),
          Expanded(
            child: Container(
              padding: EdgeInsets.all(20),
              child: EasyWebView(
                onLoaded: (){},
                src: 'PATH FOR PAYMENT URL',
                isHtml: false, // Use Html syntax
                isMarkdown: false, // Use markdown syntax
                convertToWidgets: false, // Try to convert to flutter widgets
                width: MediaQuery.of(context).size.width,
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(13.0),
            child: Text('Your payment info is encrypted and protected by STRIPE', style: TextStyle(fontSize: 12, fontStyle: FontStyle.italic),),
          ),
        ],
      ),
    );
  }

A: Your issue I think is here:
.listen((DocumentSnapshot documentSnapshot) {
            Map<String, dynamic> firestoreInfo = documentSnapshot.data();
            setState(() {
              paid = firestoreInfo['status'];
            });
            if(paid) Navigator.pop(context); // issue
          });

You notice paid isn't initialized outside of the setState just inside it so your if statement doesn't have accuss to paid. Change it to this:
.listen((DocumentSnapshot documentSnapshot) {
            Map<String, dynamic> firestoreInfo = documentSnapshot.data();
            setState(() {
              paid = firestoreInfo['status'];
            });
            if(firestoreInfo['status']) Navigator.pop(context);
        });

Comment below if you have any questions or if this didn't solve your issue

A: So, the issue was that paid = firestoreInfo['status']; was returning null. One I put the null checks in place, the error went away. paid variable is initialised globally to false.

A: I'm not writing this answer for this particular question but for anyone getting this TypeError: Cannot read properties of null (reading 'Symbol(dartx.***)') error while using Firebase and Flutter. I wasn't able to get field or to reach any doc or collection and the only thing came up was this error.
Everything was in place except ONE LITTLE THING:
Firebase console > Firestore Database > Rules > line 5: from allow read, write: if false; to  allow read, write: if true;
I was trying to reach the data without the user login, so the only thing that must be changed was this. I hope this helps someone one day.


text:
Q: Kafka Connect JDBC dblink I'm starting to study Apache Kafka and Kafka Connect.
I'm trying to get data from a remote Oracle Database that my user only have read privilegies and can't list tables (i don't have permission to change that). To every query, i have to pass a dblink, but in the JDBC Connector, i didn't find a option to pass a dblink.
I can do the query if i pass a specific query on the connector configuration, but i want to fetch allot of tables and speficifying the query on the connector, would make me create allot of connectors.
There's a way to pass the dblink on the connector configuration or to the JDBC URL?


text:
Q: How to get String Array from JSON Object I am trying to get a list of available numbers from the following json object
 void doJSONParser(String str)
    {
        try {

            JSONObject order = new JSONObject(str);
            JSONArray index = order.getJSONArray("webnautes");
            for(int i = 0; i < index.length(); i++)
            {
                JSONObject tt = index.getJSONObject(i);

                name += "name: " + tt.getString("name")+"\n";
                phone = new String[tt.getString("phone").length()];
                //phone += "phone: " + tt.getString("phone")+"\n";
            }

            Log.d("JSON DATA:", name);
            Log.d("JSON DATA:", phone.toString());

        }
        catch (JSONException e)
        {
            e.printStackTrace();
            Log.d("JSON ERROR", e.getLocalizedMessage());
        }

    }

A: Try this
JSONArray phoneJson = tt.getJSONArray("phone");
String[] arr = new String[phoneJson.length()];
for(int i = 0; i < phoneJson.length(); i++)
    arr[i] = phoneJson.getString(i);


text:
Q: Interview prep - How does one access nodes in binary search trees in the real world? I'm preparing for the data structures portion of an interview. I see that there are already questions about applications of binary trees in the real world - What are the applications of binary trees?
My question is different - How does one actually access nodes in data structures based on trees?
I understand BFS, DFS and such for explicit node traversal, I get a sense this is not how the real world works. Do people write their own traversal / search algorithms, or do they rely on iterators and similar access methods provided by the database?
What is the name of a high level abstraction of accessing structured tree data, if any?  I'm thinking of iterators, but am not sure if this is the right term.
I am looking for a way to intelligently converse on the subject.

A:
What is the name of a high level abstraction of accessing structured
  tree data, if any?

Iterator is something more suitable for linear data-structure like linked list or dynamic array. As tree is a hierarchical data-structure, parent(), child(), children(), ancestor(), descendent() are more suitable. For instance, if you want to implement a file system, you will have RootDirectory and to get all the sub-directories you might call like getAllSubDirectories() which are actually children of root directory. So the naming is actually domain specific.
class Directory {
   private Integer someAttribute;
   ....
   ....
   private Directory parentDirectory;
   List<Directory> subDirectories;
}

You can abstract as iterator and can call iterator.hasNext() or iterator.next() on a hierarchical data-structure as well. So for example, for a binary search tree, you can abstract away an iterator which can iterate the tree in preorder/inorder/postorder traversal in both direction. See in-order successor.


text:
Q: What proof uses both the Riemann Hypothesis and its negation? Some time ago I happened to see a proof that was remarkable in that it used both the Riemann Hypothesis and its negation. That is, it considered the two cases: RH is true, and RH is false, obtaining, after a non-trivial chain of reasoning in each case, the theorem in question. I failed to bookmark it well enough that I can readily retrieve it, so I'm asking the community's help.
What reminded me of this result was this question on MO about famous vacuously true statements. Obviously, one of the cases in the proof is vacuous and, since it involves the Riemann Hypothesis, conceivably qualifies as being famous.

A: There is a small list on Wikipedia: https://en.wikipedia.org/wiki/Riemann_hypothesis#Excluded_middle


text:
Q: How do I add numbers in C++ again? Seriously, I don't remember..
Would an integer work??
But I don't know why its not working...
I'm trying to add integers, like this.
int main() {
   i = 1;
   b = 3;
}
 Signed int addition() {
i + b

}

A: You can't use functions and variables, including local variables, parameters, etc before they have been declared first.  Though, you can initialize variables at the same time you declare them. For example:
#include <iostream>

int addition(int a, int b);

int main() {
   int i = 1;
   int b = 3;
   int sum = addition(i, b);
   std::cout << sum;
}

int addition(int a, int b) {
    return a + b;
}

A: You have a lot of syntax errors in that code.  Until you are more comfortable with programming, just start with a simple working "Hello world" example, and add one line of code at a time, compiling after each line you add.  Look carefully at the error messages the compiler gives you and fix them before adding another line.  You might arrive at something like this:
int main() {
  int i = 1;
  int b = 3;
  return i + b;
}

When you run this and check the process return code (e.g. using$? in Bash) then you would get 4.

A: It should not be hard.
// [...]
int Add(int x, int y) { return x + y; }

using namespace std;
int main(void) {
  int a = 1, b = 2;
  printf("%d\n", Add(a + b));
  return 0;
}


text:
Q: How do ı make continiously mathematical operations in python? I want to advance my calculator and I want it to make continiously mathematical operations with the last number of calculation. for example
11+2=13
and than take the 13 and us it in the next calculation
13 x 3= 39
and than after using the 39 like
39%3=13
instead of this my code works like
11+2=13
13*3=39
and goes back to first conclusion and be like
11 *? =...
ıt alvays goes back to first conclusion after second calculation. how can ı make it continiously until ı want it to be stopped?
def addition(str):
    "addition"
    print(str)
    return
def subtraction(str):
        "subtraction"
        print(str)
        return
def multiplation(str):
    "multiplation"
    return
def division(str):
    "division"
    print(str)
    return
def exponantial_notation(str):
    "exponantial notation"
    print(str)
    return
def yes(str):
    "yes"
    print(str)
    return
def no(str):
    "no"
    print(str)
    return
def dif(str):
    "dif"
    print(str)
    return
def div(str):
    "def"
    print(str)
    return
def sum(str):
    "sum"
    print(str)
    return
def mul(str):
    "mul"
    print(str)
    return
def exp(str):
    "exp"
    print(str)
    return

while True:
        mathematical_operation=input("Choose your mathematical operation(addition/subtraction/multiplication/division/exponantial notation/root): ")
        print(mathematical_operation)

        if mathematical_operation== 'addition':
            first=input("first: ")
            print("first")
            second=input("second: ")
            print("second")
            sum=float(first) + float(second)
            print("sum :" + str(sum))
            while True:
                continiune = input("would you like to go on?")
                if continiune == 'yes':
                    mathematical_operation = input(
                        "Choose your mathematical operation(addition/subtraction/multiplication/division/exponantial notation/root): ")
                print(mathematical_operation)
                if mathematical_operation == 'addition':
                    print("first: " + str(sum))
                    second = input("second: ")
                    print(second)
                    sum = float(str(sum)) + float(second)
                    print("sum :" + str(sum))
                if mathematical_operation == 'subtraction':
                    print("first: " + str(sum))
                    second = input("second: ")
                    print(second)
                    dif = float(str(sum)) - float(second)
                    print("dif :" + str(dif))
                if mathematical_operation == 'multiplication':
                    print("first: " + str(sum))
                    second = input("second: ")
                    print(second)
                    mul = float(str(sum)) * float(second)
                    print("mul: " + str(mul))
                if mathematical_operation == 'division':
                    print("first: " + str(sum))
                    second = input("second: ")
                    print(second)
                    div = float(str(sum)) / float(second)
                    print("div: " + str(div))
                if mathematical_operation == 'exponantial notation':
                    print("first: " + str(sum))
                    second = input("second: ")
                    print(second)
                    exp = float(str(sum)) ** float(second)
                    print("exp: " + str(exp))
                if continiune == 'no':
                    break
            question = input("would you like to make another calculation?(yes/no) ")
            if question == 'no':
               break

        if mathematical_operation == 'subtraction':
            first = input("first: ")
            print("first")
            second = input("second: ")
            print("second")
            dif = float(first) - float(second)
            print("dif :" + str(dif))
            while True:
                continiune = input("would you like to go on?")
                if continiune == 'yes':
                    mathematical_operation = input(
                        "Choose your mathematical operation(addition/subtraction/multiplication/division/exponantial notation/root): ")
                print(mathematical_operation)
                if mathematical_operation == 'addition':
                    print("first: " + str(dif))
                    second = input("second: ")
                    print(second)
                    sum = float(str(dif)) + float(second)
                    print("sum :" + str(sum))
                if mathematical_operation == 'subtraction':
                    print("first: " + str(dif))
                    second = input("second: ")
                    print(second)
                    dif = float(str(dif)) - float(second)
                    print("dif :" + str(dif))
                if mathematical_operation == 'multiplication':
                    print("first: " + str(dif))
                    second = input("second: ")
                    print(second)
                    mul = float(str(dif)) * float(second)
                    print("mul: " + str(mul))
                if mathematical_operation == 'division':
                    print("first: " + str(dif))
                    second = input("second: ")
                    print(second)
                    div = float(str(dif)) / float(second)
                    print("div: " + str(div))
                if mathematical_operation == 'exponantial notation':
                    print("first: " + str(dif))
                    second = input("second: ")
                    print(second)
                    exp = float(str(dif)) ** float(second)
                    print("exp: " + str(exp))
                if continiune == 'no':
                    break
            question = input("would you like to make another calculation?(yes/no) ")
            if question == 'no':
                break

        if mathematical_operation=='multiplication':
            first=input("first: ")
            print("first")
            second=input("second: ")
            print("second")
            mul=float(first) *float(second)
            print("Sum :" + str(mul))
            while True:
                continiune = input("would you like to go on?")
                if continiune == 'yes':
                    mathematical_operation = input(
                        "Choose your mathematical operation(addition/subtraction/multiplication/division/exponantial notation/root): ")
                print(mathematical_operation)
                if mathematical_operation == 'addition':
                    print("first: " + str(mul))
                    second = input("second: ")
                    print(second)
                    sum = float(str(mul)) + float(second)
                    print("sum :" + str(sum))
                if mathematical_operation == 'subtraction':
                    print("first: " + str(mul))
                    second = input("second: ")
                    print(second)
                    dif = float(str(mul)) - float(second)
                    print("dif :" + str(dif))
                if mathematical_operation == 'multiplication':
                    print("first: " + str(mul))
                    second = input("second: ")
                    print(second)
                    mul = float(str(mul)) * float(second)
                    print("mul: " + str(mul))
                if mathematical_operation == 'division':
                    print("first: " + str(mul))
                    second = input("second: ")
                    print(second)
                    div = float(str(mul)) / float(second)
                    print("div: " + str(div))
                if mathematical_operation == 'exponantial notation':
                    print("first: " + str(mul))
                    second = input("second: ")
                    print(second)
                    exp = float(str(mul)) ** float(second)
                    print("exp: " + str(exp))
                if continiune == 'no':
                    break
            question = input("would you like to make another calculation?(yes/no) ")
            if question == 'no':
                break

        if mathematical_operation=='division':
            first=input("first: ")
            print("first")
            second=input("second: ")
            print("second")
            div=float(first) /float(second)
            print("div :" + str(div))
            while True:
                continiune = input("would you like to go on?")
                if continiune == 'yes':
                    mathematical_operation = input(
                        "Choose your mathematical operation(addition/subtraction/multiplication/division/exponantial notation/root): ")
                print(mathematical_operation)
                if mathematical_operation == 'addition':
                    print("first: " + str(div))
                    second = input("second: ")
                    print(second)
                    sum = float(str(div)) + float(second)
                    print("sum :" + str(sum))
                if mathematical_operation == 'subtraction':
                    print("first: " + str(div))
                    second = input("second: ")
                    print(second)
                    dif = float(str(div)) - float(second)
                    print("dif :" + str(dif))
                if mathematical_operation == 'multiplication':
                    print("first: " + str(div))
                    second = input("second: ")
                    print(second)
                    mul = float(str(div)) * float(second)
                    print("mul: " + str(mul))
                if mathematical_operation == 'division':
                    print("first: " + str(div))
                    second = input("second: ")
                    print(second)
                    div = float(str(div)) / float(second)
                    print("div: " + str(div))
                if mathematical_operation == 'exponantial notation':
                    print("first: " + str(div))
                    second = input("second: ")
                    print(second)
                    exp = float(str(div)) ** float(second)
                    print("exp: " + str(exp))
                if continiune == 'no':
                    break
            question = input("would you like to make another calculation?(yes/no) ")
            if question == 'no':
                break

        if mathematical_operation=='exponantial notation':
            first=input("first: ")
            print("first: ")
            second=input("second")
            print("second")
            exp=float(first) **float(second)
            print("sum :" + str(exp))
            question = input("would you like to make another calculation?(yes/no) ")
            while True:
                continiune = input("would you like to go on?")
                if continiune == 'yes':
                    mathematical_operation = input(
                        "Choose your mathematical operation(addition/subtraction/multiplication/division/exponantial notation/root): ")
                print(mathematical_operation)
                if mathematical_operation == 'addition':
                    print("first: " + str(exp))
                    second = input("second: ")
                    print(second)
                    sum = float(str(exp)) + float(second)
                    print("sum :" + str(sum))
                if mathematical_operation == 'subtraction':
                    print("first: " + str(exp))
                    second = input("second: ")
                    print(second)
                    dif = float(str(exp)) - float(second)
                    print("dif :" + str(dif))
                if mathematical_operation == 'multiplication':
                    print("first: " + str(exp))
                    second = input("second: ")
                    print(second)
                    mul = float(str(exp)) * float(second)
                    print("mul: " + str(mul))
                if mathematical_operation == 'division':
                    print("first: " + str(exp))
                    second = input("second: ")
                    print(second)
                    div = float(str(exp)) / float(second)
                    print("div: " + str(div))
                if mathematical_operation == 'exponantial notation':
                    print("first: " + str(exp))
                    second = input("second: ")
                    print(second)
                    exp = float(str(exp)) ** float(second)
                    print("exp: " + str(exp))
                if continiune == 'no':
                    break
            if question == 'no':
                break
        else:
            print("Invalid Input")

A: I'm not really sure where to begin explaining where your approach is misguided and broken, though I would be happy to try if you have further questions.  There are many ways to write a simple calculator program.  Here's one I just wrote to give you some better ideas of how to approach this (it's probably missing a few things and buggy, but it should show you how little code you actually need to write for this).  This also uses regular expressions which may be a concept you haven't studied yet, but it can also be done without a regular expession (and is even recommended if you want to support things like parentheses):
calc.py
import operator
import re

infix_ops = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.truediv,
    '**': operator.pow
}

num_re = r'-?(?:\d+)?.?\d+'

infix_expr_re = re.compile(
    r'({num})\s*({ops})\s*({num})'.format(
        num=num_re, ops='|'.join(re.escape(op) for op in infix_ops))
)

def calculator():
    result = None

    while True:
        try:
            if result is None:
                expr = input()
            else:
                expr = str(result) + input(str(result) + ' ')
        except (KeyboardInterrupt, EOFError):
            print()
            print('goodbye')
            break

        if not (m := infix_expr_re.match(expr)):
            print(f'invalid expression: {expr}')
            continue

        lhs, op, rhs = m.groups()
        result = infix_ops[op](float(lhs), float(rhs))

if __name__ == '__main__':
    calculator()

Example calculation session:
$ python3 calc.py
1 + 1
2.0 * 3
6.0 ** 2
36.0 / 4
9.0 - 9
0.0 ^C
goodbye


text:
Q: What functions should I disable if I would allow users to type PHP? Let's say I want my users to allow to create PHP scripts on my page and I would save those pages in directory. What functions should I disable to not be hacked? Or what should I do?
Firstly, I would not allow people to upload files through PHP file (not sure how to do it yet), what else?

A: In such case I'd not let them execute PHP files though its possible ro run them by disabling thousands of function.
For this Its better to allow user to write xml.  A parser would have read it and execute it accordingly. Most programming language feature can be implemented in xml. See how ant does it. There is loop, conditional statement etc.

A: You cannot make PHP into a safe language by blacklisting individual functions -- there are simply too many which can be used maliciously.

A: *

*File handling (fopen,fclose,fwrite,etc.)

*File browsing (opendir,readdir,etc.)

*Execution (exec,shell,etc.)

*Remote file access (allow_url_include php.ini directive)

And anything else you may see as being harmful. put yourself in the place of a "Cracker" and what ways would you use to see your system or environment and disallow anything you see as being harmful.

A: Rather than retype all of the useful stuff in this fellow stackexchange site, I provide you a link sir: https://security.stackexchange.com/questions/1382/disable-insecure-dangerous-php-functions
And a few functions:
"apache_child_terminate, apache_setenv, define_syslog_variables, escapeshellarg, escapeshellcmd, eval, exec, fp, fput, ftp_connect, ftp_exec, ftp_get, ftp_login, ftp_nb_fput, ftp_put, ftp_raw, ftp_rawlist, highlight_file, ini_alter, ini_get_all, ini_restore, inject_code, mysql_pconnect, openlog, passthru, php_uname, phpAds_remoteInfo, phpAds_XmlRpc, phpAds_xmlrpcDecode, phpAds_xmlrpcEncode, popen, posix_getpwuid, posix_kill, posix_mkfifo, posix_setpgid, posix_setsid, posix_setuid, posix_setuid, posix_uname, proc_close, proc_get_status, proc_nice, proc_open, proc_terminate, shell_exec, syslog, system, xmlrpc_entity_decode"

A: I would do it the other way around. I would provide the users a subset of PHP that they can use.
Then, you only have to validate that what they sent is contained in that safe list.
Also, you can create your own functions to replace some of the dangerous ones.


text:
Q: Index array of geopoints in Elasticsearch Following is my (sample) Elastic search data which has a series of geo coordinates that I'm trying to index.
PUT geomap/_doc/1
{
  "geometry": {
    "coordinates": [
      [
        [
          -10.8544921875,
          49.82380908513249
        ],
        [
          -10.8544921875,
          59.478568831926395
        ],
        [
          2.021484375,
          59.478568831926395
        ],
        [
          2.021484375,
          49.82380908513249
        ],
        [
          -10.8544921875,
          49.82380908513249
        ]
      ]
    ]
  }
}

and this is the elasticsearch mapping I've created for it.
PUT geomap
{
  "mappings": {
    "properties": {
      "geometry": {
        "properties": {
          "coordinates": { "type": "geo_point" }
        }
      }
    }
  }
}

When I tried to insert the data it did not work. I suspect it is due to the fact that I've got arrays of array coordinates. When I updated the sample dataset to single array of coordinates it worked (below).
PUT geomap/_doc/1
{
  "geometry": {
    "coordinates": [
      [
        -10.8544921875,
        49.82380908513249
      ],
      [
        -10.8544921875,
        59.478568831926395
      ],
      [
        2.021484375,
        59.478568831926395
      ],
      [
        2.021484375,
        49.82380908513249
      ],
      [
        -10.8544921875,
        49.82380908513249
      ]
    ]
  }
}

I would be glad to know what mistake I've done in my mapping which doesn't let me to do so.

A: I suspect your doc is a polygon so you're gonna want to use geo_shape instead:
PUT geomap
{
  "mappings": {
    "properties": {
      "geometry": {
        "type": "geo_shape",
        "strategy": "recursive"
      }
    }
  }
}

Notice the "recursive" strategy too to support more spatial queries (at least in the newer ES releases).
PUT geomap/_doc/1
{
  "geometry": {
    "coordinates": [
      [
        [
          -10.8544921875,
          49.82380908513249
        ],
        [
          -10.8544921875,
          59.478568831926395
        ],
        [
          2.021484375,
          59.478568831926395
        ],
        [
          2.021484375,
          49.82380908513249
        ],
        [
          -10.8544921875,
          49.82380908513249
        ]
      ]
    ],
    "type": "polygon"
  }
}

Notice how the coords array was wrapped in one more array to comply w/ the geojson standard and that the type: polygon attribute was added.


text:
Q: How to prove that the following function is monotonically decreasing? $f(x) = \frac{\int_{\alpha x}^{x} e^{-t} t^{b+1}\ dt}{x \int_{\alpha x}^{x} e^{-t} t^b\ dt}:\ ]\ 0,+\infty\ [\ \to \mathbb{R}$
where $\ 0<\alpha<1\ $ and $\ b>0$

A: First perform a change of variables in the integration using $t = sx$. This gives
$$ f(x) = \frac{\int_a^1 e^{-xs} s^{b+1}~ \mathrm{d}s}{\int_a^1 e^{-xs} s^{b} ~\mathrm{d}s} = - \frac{d}{dx} \ln \int_a^1 e^{-xs} s^b ~\mathrm{d}s $$
Define
$$ g(x) = \int_a^1 e^{-xs} s^b ~\mathrm{d}s $$
you have
$$ f'(x) \leq 0 \iff \ln g(x) \text{ is convex} \iff \ln g(\frac{\alpha + \beta}{2}) \leq \frac12 (\ln g(\alpha) + \ln g(\beta)) $$
this in turn
$$ \iff g(\frac{\alpha+\beta}{2}) \leq \sqrt{g(\alpha)g(\beta)} $$
This final line holds by Cauchy-Schwarz applied to $e^{-\alpha s / 2} e^{-\beta s/2}$ integrating against the measure $s^b ~\mathrm{d}s$.


text:
Q: File disappeared on Linux. Search says it's still there So I was editing a cpp file in sublime on my linux machine and I'm not sure what I did or what happened but all of a sudden the file disappeared on sublime. So it went to it's directory to open it back up but it's not there.
I did a quick search for it and it says it's says it's still in the the directory it was in but it doesn't show the actual file.
I don't think it's hidden. Any ideas??
Thanks

A: Use chmod to give permission to use the file in user.
chmod 777 <filename>

Before running this command you have to open root privilege by using sudo su command.


text:
Q: How to run graphical applications as root under wayland Under the new Wayland display server, several applications requiring root permission fail to run. I actually have an answer (one way of working around the issue). I welcome any better solutions or criticisms.
Many other answers to this issue recommend adding root to xhost which, while it solves the issue, breaks the Wayland security model a bit. It is much better that we add root to xhost only for the duration of the running of the program, be it synaptic or gparted or whichever.
Gufw:
Edit your gufw.desktop file (/usr/share/applications/gufw.desktop in Debian 10) and change the line:
Exec=gufw
to
Exec=sh -c "xhost +si:localuser:root && gufw && xhost -si:localuser:root"
Synaptic:
Inspired by the post at: https://discourse.ubuntu.com/t/adding-applications-to-start-up/9288
Edit /usr/bin/synaptic-pkexec to comment out the zenity warning message (assuming Debian 10) and change the line:
exec "/usr/sbin/synaptic" "$@"
to
xhost +si:localuser:root
pkexec "/usr/sbin/synaptic" "$@"
xhost -si:localuser:root

I imagine other programs can mostly be adapted in the same way as gufw. This does not solve the underlying issue of old programs running everything including GUI as root but at least they can function like before.

A: In Wayland, other users cannot start applications because they cannot access the Wayland socket file located at $XDG_RUNTIME_DIR/$WAYLAND_DISPLAY.
However, root ignores all file permissions and so can perfectly access the socket file when its full path is specified in WAYLAND_DISPLAY. Because of an implementation detail in the Wayland client library, it is also necessary to define XDG_RUNTIME_DIR to something (even if the actual value is not really used).
So it is actually possible to run Synaptic as a pure Wayland application with something like
sudo /bin/env WAYLAND_DISPLAY="$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY"  XDG_RUNTIME_DIR=/user/run/0  /usr/sbin/synaptic

So far, I tested that trick only with Sway.

A: And if ssh is enabled for root, then it is also possible to use waypipe: https://gitlab.freedesktop.org/mstoeckl/waypipe
waypipe ssh root@localhost synaptic

A: Here is a shell script to run any Wayland program as root using sudo and waypipe (no ssh needed). This is inspired from the examples in the waypipe man page.
sudo does not start a proper user session. That can be problematic for some applications. See the comment for more details.
#!/bin/bash

# There is still a small risk of collision when using -u but this is unlikely.
SOCKET=`mktemp -u /tmp/sudo-waypipe.XXXXXXX.sock`

waypipe --socket "$SOCKET" client &

# waypipe --server requires a proper XDG_RUNTIME_DIR directory for the root user.
#
# That should typically be /run/user/0 or /var/run/0
#
# Unfortunalely, sudo does not create a user session so this variable is not set.
# Even worse, systemd destroys the directory when the last session terminates.
#
# In practice, that means that we cannot assume that /run/user/0 or /var/run/0
# exists and, even if it does exist, it cannot be safely used because it may
# be removed by systemd at any time.
#
# Ideally, a user session should be created for user 0 (via systemctl?)
# but this is not that easy. The alternative is to use a custom directory in /root
#
# The disadvantage is that the application may not be able to access services
# such as dbus.
#

sudo sh -c "XDG_RUNTIME_DIR=\$HOME/xdg-run/ ; mkdir -m 700 -p \$XDG_RUNTIME_DIR ; export XDG_RUNTIME_DIR ; waypipe --socket $SOCKET server -- $(printf "%q " "$@")"
kill %1
rm -f "$SOCKET"


text:
Q: Wrong number of cpu cores in /proc/cpuinfo I am running Ubuntu 18.04 server. I have an Intel i9 9980xe CPU, which has 18 cores and 2 threads per core. But it shows that the CPU has only 15 cores in /proc/cpuinfo as well as in htop. Why?
Here is the part of content in cpuinfo:
processor       : 0
vendor_id       : GenuineIntel
cpu family      : 6
model           : 85
model name      : Intel(R) Core(TM) i9-9980XE CPU @ 3.00GHz
stepping        : 4
microcode       : 0x200005e
cpu MHz         : 1200.143
cache size      : 25344 KB
physical id     : 0
siblings        : 15
core id         : 0
cpu cores       : 15
apicid          : 0
initial apicid  : 0
fpu             : yes
fpu_exception   : yes
cpuid level     : 22
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault cat_l3 cdp_l3 invpcid_single pti ssbd mba ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_pkg_req md_clear flush_l1d
bugs            : cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds
bogomips        : 6000.00
clflush size    : 64
cache_alignment : 64
address sizes   : 46 bits physical, 48 bits virtual
power management:

The output of lscpu:
Architecture:        x86_64
CPU op-mode(s):      32-bit, 64-bit
Byte Order:          Little Endian
CPU(s):              15
On-line CPU(s) list: 0-14
Thread(s) per core:  1
Core(s) per socket:  15
Socket(s):           1
NUMA node(s):        1
Vendor ID:           GenuineIntel
CPU family:          6
Model:               85
Model name:          Intel(R) Core(TM) i9-9980XE CPU @ 3.00GHz
Stepping:            4
CPU MHz:             1200.425
CPU max MHz:         4500.0000
CPU min MHz:         1200.0000
BogoMIPS:            6000.00
Virtualization:      VT-x
L1d cache:           32K
L1i cache:           32K
L2 cache:            1024K
L3 cache:            25344K
NUMA node0 CPU(s):   0-14
Flags:               fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault cat_l3 cdp_l3 invpcid_single pti ssbd mba ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_pkg_req md_clear flush_l1d

A: I solved the above problem. Just because misconfigured the bios.
My colleague installed Win10 on this computer before. However, in the process of installation, he met a "blue screen" error and fixed it through disabling 3 cores of this CPU in bios.  That's the reason why there are only 15 cores shown in my Ubuntu OS.
Thanks for your attention.


text:
Q: deserialize json without property name .Net I'm using JSON.NET to deserialize response from HTTP, but I'm stuck with an issue. That's because the response sending results wthout property names
i have something like this
{"people":{"jack":{"condition":"good","version":"1.0.5"},"jim":{"condition":"bad","version":"1.0.5"}},"hede":14,"hodo":"apple"}
how can I put this in a class.
not: json result can have more than jack and jim when i paste as a class it creates jim and jack classes. bob and mike will come soon.
sorry bro. i was just writing my effort but my daughter woke up. went to send her to bed back. what I mean is, after searching "good" in dictionaries i want to go back and find "jack".
var values = from value in dictioanries.values
where value.condition ="good"
select new { value.condition, value.version }

ok here I searched the dictionaries, there are 2 of them(jack and jim) i want to know under which dictionary i found "good"

A: You don't have a class as much as you have a dictionary of string and objects. If you do the following, you should be able to deserialize properly:
public class PeopleResponse
{
  public Dictionary<string, Info> people { get; set; }
  public string hede { get; set; }
  public string hodo { get; set; }
}

public class Info
{
  public string condition { get; set; }
  public string version { get; set; }
}

From there, you should be able to do:
var results = JsonConvert.DeserializeObject<PeopleResponse>("{myJSONGoesHere}");

Edit: Based on your updated question, if you would like to get the names of all whose condition is "good," you can do the following (assuming your deserialized object is called results:
var goodStuff = from p in results.people
                where p.Value.condition.ToLower() == "good"
                select p.Key;

You could, of course, just get p instead of p.Key, which would return the entire key/value pair.


text:
Q: warning: left hand operand of comma has no effect (c) if (class == 'a','A')

I'm trying to continue only if the user inputs 'a' or 'A'. Every time I build it, it warns "left hand operand of comma has no effects".
I'm very new to C, so I apologize if I'm not specific enough or missing something obvious.

A: that's not how to do it , you should do instead
if(class == 'a' || class == 'A')

A: Change the condition to
if ( class == 'a' || class == 'A' )

As for your original expression
if (class == 'a','A')

then there is used the comma operator and the value of expression is 'A'. As 'A' is not equal to zero then the condition will be always equal to true.  The expression before the comma is discarded.

A: Whilst both current answers are correct, I think it may be more idiomatic to do:
#include <ctype.h>
...
if (tolower(class) == 'a')
{
    ...
}

A: In if (class == 'a','A'), the left half is the comparison class == 'a' and may evaluate to either true or false (in the boolean sense¹). The right half is just 'A', which is not equal to 0 and thus true. The left half gets evaluated but the result is not used. Then the right half is evaluated, and its "result" is 'A', which is true. Hence, the code acts as if you wrote
if (true)
   ...

You can check this by using a '0' at the right half:
if (class == 'a', 0)
    printf ("if-statement is true\n");
else
    printf ("if-statement is false\n");

and running this (after coercing the compiler to compile it) will indeed show the "false" line.
The compiler complains because the left half class == 'a' "does nothing": it has no side effect on class or on the result of the if statement. Thus, the compiler assumes this is a mistake and therefore issues the warning. It is a warning and not an error, because the syntax is correct. For comparison, you are allowed to write something similar such as
if (class = 'a', 'A')
    printf ("class == a,A seems to be true\n");
else
    printf ("That didn't work.\n");

which has a valid side effect (class gets the value for the character constant 'a') -- but it also will always state that it appears to be true, because the second half is what is passed on to the if statement.

¹ For C, I use true and false in the boolean sense only, as C has by default no concept of these named values without including stdbool.h (this defines the constants by name). The underlying concept is the same, though: an if statement evaluates its parameter, which is considered false if it evaluates to 0 (and thus will not execute the following expression), true if it evaluates to anything else than 0.


text:
Q: What should be the context parameter for ContextCompat.getDrawable( )? I use it in setOnClickListeneraccording to an another post here
like this :
  start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                start.setBackground(ContextCompat.getDrawable( this,R.drawable.buttonstop));

parameter this is wrong
Thanks

A: You can use v.getContext() to get the Context associated with that View.

A: If you are in class named MainActivity you can use:
In Kotlin:
this@MainActivity

e.g.
button.setOnClickListener(object : View.OnClickListener {
    override fun onClick(v: View?) {
        Toast.makeText(this@MainActivity, "Hello!", Toast.LENGTH_SHORT).show();
    }
})

// Or in shorter way:
frame_layout.setOnClickListener {
    Toast.makeText(this@MainActivity, "Hello!", Toast.LENGTH_SHORT).show();
}

In Java:
MainActivity.this

e.g.
Button button = findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(A.this, "Hello!", Toast.LENGTH_SHORT).show();
    }
});

// Or in shorter way:
button.setOnClickListener(v -> Toast.makeText(MainActivity.this, "Hello!", Toast.LENGTH_SHORT).show());

A: using
this

in the onclicklistener will reference the listener you should use
MainActivity.this or getActivity()


text:
Q: CodeIgniter in subdomain folder, removing the index.php from address So I am trying to remove index.php from address using this manual: http://dev.lohv.eu/1/user_guide/general/urls.html
Atm I have address http://dev.lohv.eu/1/index.php but I want to use it in future without index.php, like so: http://dev.lohv.eu/1/
I created .htaccess file according to manual:
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

But unfortunaly it fails, I get 404 error. I guess the problem is, I am trying to configure .htaccess in subdomain folder so it wont fit as in manual and needs some extra, but I don't know what extras it needs.

A: I think you're missing a '?'. RewriteRule ^(.*)$ /index.php?/$1 [L]
This is CI's recommended .htaccess template (or at least it was a year ago), and that ? is the major difference between the two.
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    #Removes access to the system folder by users.
    #Additionally this will allow you to create a System.php controller,
    #previously this would not have been possible.
    #'system' can be replaced if you have renamed your system folder.
    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #Checks to see if the user is attempting to access a valid file,
    #such as an image or css document, if this isn't true it sends the
    #request to index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>