text:
Q: Javascript Banner Swap The section is foo.com/agriculture.  It has a banner image corresponding to the name in the javascript. I need the internal page foo.com/agriculture/harvest to have a separate banner than the foo.com/agriculture. The script I am working with for the banner swap for each page is as follows:

I tried the following different codes to try and assign the internal page foo.com/agriculture/harvest a separate banner.
var dir = location.pathname.split("/")[1];
//var dir2 = location.pathname;
if (dir == "agriculture/harvest")
document.write('')
else if (dir == "showcase")

var dir = location.pathname.split("/")[1];
//var dir2 = location.pathname;
if (dir == "harvest")
document.write('')
else if (dir == "showcase")

Both of the scripts above continue to grab the foo.com/agriculture banner (ib_agriculture.jpg) instead of the called foo.com/agriculture/harvest (ib_agriculture_harvest.jpg). I am not sure how to get the script to call the appropriate banner per page.

A: When you call pathname.split you get an array like this:
["foo.com", "agriculture", "harvest"]

You then take the item with index 1 and put it into the dir variable:
var dir = location.pathname.split("/")[1]

So the value of dir is "agriculture", even though "harvest" is also part of the url. To check for that string you need to use location.pathname.split("/")[2].
Or you can do this:
var parts = location.pathname.split("/");
var dir = parts[1];
if (parts.length > 2)
{
     dir += "/" + parts[2];
}
if (dir == "agriculture/harvest")
     document.write('')


text:
Q: C Dynamic allocation of matrices and vectors I'm writing this code in C to implement a genetic algorthm. This is the part where I do the dynamic allocation of all the working structures (matrices and vectors). When I run this, sometimes (3 times on 5) it crashes. I'm doing something wrong with the allocation?
int main()
{

const char progress[] = "|/-\\";
int n, popSize, numIter,optRoute,minDist,range,globalMin,idx;
int maxcell;
int i,j,p,t,k,d,iter,perm,index,m;
int dists[4];
int* dmat, * totalDist, * distHistory, *randomOrder, *bestOf4Route;
int** pop, ** newPop, ** tmpPop, **rtes;
unsigned int iseed = (unsigned int)time(NULL);

// Values initialization
n = 5;
range = 10;
popSize = 100;
numIter = 1*10^4;
globalMin = 100000;

srand (iseed);

//printf("Insert the number of cities: ");
//scanf("%i",&n);

printf("Matrix costs creation...");
// Creates dmat NxN matrix
// dmat è una matrice triangolare superiore con diag = 0
// declare halfsize 1D array
maxcell = ((n*n)-n)/2;
dmat = (int*)malloc(maxcell * sizeof(int));

//set array
for(i=0; i<maxcell; i++)
    dmat[i] = (rand()%10)+2;

printf("done.\n");

//print entire matrix
//print_triangmat(dmat,n);

printf("Creation of the pop matrix...");
// create popSize x N matrix
pop = (int**)malloc(n * sizeof(int*));
for (i = 0; i < n; i++) {
  pop[i] = (int*)malloc(popSize * sizeof(int));
}

printf("done.\n");
printf("Pop matrix loading...");
// charge the first row of the matrix
for (j = 0; j < n; j++) {
  pop[j][0] = j+1;
}

// charge the rest of the matrix with randperm of the first row
for (i = 0; i < popSize; i++)
{
    for (j = 0; j < n; j++)
    {
        perm = rand()%(n-j)+j;
        t = pop[perm][i];
        pop[perm][i] = pop[j][i];
        if(i!=popSize-1)
        pop[perm][i+1] = pop[j][i];
        pop[j][i] = t;
        if(i!=popSize-1);
        pop[j][i+1] = t;
    }
}
print_matrix(pop,popSize,n);

printf("done.\n");
printf("Creation of the working structures...");

// create 4 x N matrix
rtes = (int**)malloc(n * sizeof(int*));
for (i = 0; i < n; i++) {
  rtes[i] = (int*)malloc(4 * sizeof(int));
}

// Creates an array of popSize
totalDist = (int*)malloc(popSize * sizeof(int));

// Creates an array of numIter
distHistory = (int*)malloc(numIter * sizeof(int));

// Creates an array of n
bestOf4Route = (int*)malloc(n * sizeof(int));

// create 4 x N matrix
tmpPop = (int**)malloc(n * sizeof(int*));
for (i = 0; i < n; i++) {
  tmpPop[i] = (int*)malloc(4 * sizeof(int));
}

// create popSize x N matrix
newPop = (int**)malloc(n * sizeof(int*));
for (i = 0; i < n; i++) {
  newPop[i] = (int*)malloc(popSize * sizeof(int));
}

// Creates an array of popSize
randomOrder = (int*)malloc(popSize * sizeof(int));

printf("done.\n");

A: pop = (int**)malloc(n * sizeof(int*));
for (i = 0; i < popSize; i++) {
  pop[i] = (int*)malloc(popSize * sizeof(int));
}

if popSize > n you are in trouble here...

A: Problem is here. Consider i=popsize-1 then you will write to pop[perm][popsize] which is an invalid memory position. Then when   allocations below are requested, sometimes requested memory position is intersected with pop[perm][popsize] so you are getting the runtime error.
for (i = 0; i < popSize; i++) {
    for (j = 0; j < n; j++) {
        perm = rand()%(n-j)+j;
        t = pop[perm][i];
        pop[perm][i] = pop[j][i];
        if(i!=popsize-1)
        pop[perm][i+1] = pop[j][i];
        pop[j][i] = t;
        if(i!=popsize-1)
        pop[j][i+1] = t;
    }
}

On the other hand there many wrong memory allocations:
    pop = (int**)malloc(n * sizeof(int*));
    for (i = 0; i < popSize; i++) {
      pop[i] = (int*)malloc(popSize * sizeof(int));
    }

should be
pop = (int**)malloc(n * sizeof(int*));
for (i = 0; i < n; i++) {
  pop[i] = (int*)malloc(popSize * sizeof(int));
}

and
 rtes = (int**)malloc(n * sizeof(int*));
    for (i = 0; i < 4; i++) {
      rtes[i] = (int*)malloc(4 * sizeof(int));
    }

should be
rtes = (int**)malloc(n * sizeof(int*));
for (i = 0; i < n; i++) {
  rtes[i] = (int*)malloc(4 * sizeof(int));
}

and
tmpPop = (int**)malloc(n * sizeof(int*));
for (i = 0; i < 4; i++) {
  tmpPop[i] = (int*)malloc(4 * sizeof(int));
}

should be
tmpPop = (int**)malloc(n * sizeof(int*));
for (i = 0; i < n; i++) {
  tmpPop[i] = (int*)malloc(4 * sizeof(int));
}

There is one more ambiguity in the problem.
numIter = 1*10^4;

This makes numIter 14 since ^ is logical XOR operator. Are you sure to want to do so?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Co-Variance of Zero and Non-Zero mean random variables Is the value of co-variance function for non-zero mean random variables different from the value of co-variance function when random variables have a zero-mean?
I think yes based on this:
For a random vector $X$
$K_{X} = E[(X-\mu_X)(X-\mu_X)^H]$
or
$K_{X} = R_{X} - m_X.{m_X}^H$
But I am not sure.

A: Covariance is a bilinear function meaning, among other things, that
\begin{align}
\operatorname{cov}(X+a,Y+b) &= \operatorname{cov}(X,Y)+\operatorname{cov}(X,b) + \operatorname{cov}(a,Y) + \operatorname{cov}(a,b)\\
&= \operatorname{cov}(X,Y)+0 + 0 + 0\\
&= \operatorname{cov}(X,Y).
\end{align}
Thus, $\hat{X} = X+a$ sand $\hat{Y} = Y+b$, which happen to be random
variables with means $\mu_X + a$ and $\mu_Y + b$ respectively, have the same
covariance as $X$ and $Y$.

In short, means do not matter.

A: The formula doesn't change, but as you can see from your formula, the covariance of a zero-mean RV does simplify to (using your notation):
$K_X = E(XX^T) - E(X)[E(X)]^T = E(XX^T) - \mathbf{0} = R_X$.
Where $\mathbf{0}$ is a $D*D$ matrix of zeros and $D$ is the dimensionality of your random variable.


text:
Q: How to create a mockup on the server I am trying to create a mockup for a pillow on a server so that when user add image I can use this mockup to make his image take the shape of the pillow and send the new image to the client I have tried some packages like ( 'jimp' , 'image-clipper' , 'canvas')
I tried o use a pillow.png image and I thought there could be a way to fill it with another image and taking the pillow shape but I didn't get that result

*

*it keep sending me the pillow image alone without the other image I have added

*the pillow Image  = 2.png , the mockup

*the other image = 3.png , image I want to fill the mockup with

Is there is any package I can use for that or another way I can try to accomplish that
This is my code for canvas ,I am working on NodeJS
    const { createCanvas, loadImage ,Image} = require('canvas')
    const canvas = createCanvas(500, 500)
    const ctx = canvas.getContext('2d')
    app.post('/image', async (req,res) => {
       loadImage('./2.png').then((image) => {
        ctx.drawImage(image, 50, 0, 400, 300)

        var img  = new Image();
        img.src = './3.png'
        var pattern = ctx.createPattern(img, "repeat");
        ctx.fillStyle = pattern
        ctx.fill();
        res.json(canvas.toDataURL())
      })
});


text:
Q: My jQuery hide/view function works but does not if executed through another script I've made a function to hide/view my category menu:
The script:

      function toggle(id) {

         var e = document.getElementById(id);
         if(e.style.display == 'block')
            e.style.display = 'none';
         else
            e.style.display = 'block';
      }

      </script>

I use it on a p tag like this:

Category

The above works perfectly. When I click on "Category" it shows or hide my div.
However I then made another menu as a list. I want to execute my "toggle" function when you click on one of the "li" from my list.
I've tried to do that with this:
    $(".uldropdown").on('click','li',function (){

    $("#displaytwo .menu p").click();

    });

But when I click on one of the "li" it shows my category menu only for a split second and then it immediately disappears.
So it almost works, but for some reason the div disappears immediately right after the click. I hope someone can tell me whats wrong. Thank you
Edit:
This is my list menu:
     echo '
';
     echo '

';

   while($row = mysqli_fetch_array($results)) {
    echo '
'.$row['name'].'
';

    }
    echo '

';

My category menu:

Category

      <?php
        echo '

';

         echo '

';

        while($row = mysqli_fetch_array($resultcats)) {
            echo '
'.$row['category'].'
';

        }
        echo '

';

I did not add some of the SQL parts, just to keep it as simple as possible.


text:
Q: Check if Ajax json response data Im using a jqueryAjax function in a jsp page to display a html table. The function returns  response as a json object. Im using the json object, iterating the same and displaying the column values. But if the field value is empty, then the corresponding value in the html table is specified as 'undefined' Below is my sample code
     $.each(data1, function (i, item) {
        trHTML += '
' + item.appnName + '	' + item.Defectsin2014 + '	' + item.Defectsin2015 + '	'+
        item.DefectsasperBenchmarks +'	'+item.costDefect + '	'+ item.req2014 + '	'+ item.req2015 +'	' +
        item.ba+ '	'+ item.config+'	'+ item.Financials+ '	' + item.bReports + '	'+
        item.qa + '
';
    });
    $('#records_table').append(trHTML);

In the above, if a particular field is not available in the json for example, if item.req2015 data is not available for a particular row, then the html table displays the corresponding field as 'undefined'.I want the application to display an empty or blank field if the data is not available. Is there any way to acheive the same.
Any help on this is much appreciated.

A: Check the properties and give them an default before using them.
$.each(data1, function (i, item) {
    item.appnName      = item.appnName      || " ";
    item.Defectsin2014 = item.Defectsin2014 || " ";
    item.Defectsin2015 = item.Defectsin2015 || " ";
    item.costDefect    = item.costDefect    || " ";
    item.req2014       = item.req2014       || " ";
    item.req2015       = item.req2015       || " ";
    item.ba            = item.ba            || " ";
    item.config        = item.config        || " ";
    item.Financials    = item.Financials    || " ";
    item.bReports      = item.bReports      || " ";
    item.qa            = item.qa            || " ";

    trHTML += '
' + item.appnName + '	' + item.Defectsin2014 + '	' + item.Defectsin2015 + '	'+
    item.DefectsasperBenchmarks +'	'+item.costDefect + '	'+ item.req2014 + '	'+ item.req2015 +'	' +
    item.ba+ '	'+ item.config+'	'+ item.Financials+ '	' + item.bReports + '	'+
    item.qa + '
';
});
$('#records_table').append(trHTML);

Or even shorter possible with an inline decision:
trHTML += '
' + (item.appnName || " ") + '	' + (item.Defectsin2014 || " ") + '	' + (item.Defectsin2015 || " ") + '	'+
(item.DefectsasperBenchmarks || " ") +'	'+(item.costDefect || " ") + '	'+ (item.req2014 || " ") + '	'+ (item.req2015 || " ") +'	' +
(item.ba || " ") + '	'+ (item.config || " ")+'	'+ (item.Financials || " ") + '	' + (item.bReports || " ") + '	'+
(item.qa || " ") + '
';

A: Set default value this way:
'+ (item.req2015||' ') + '

By filed setable defaults, easily reorganiziable:
var fdef = [ 'appnName     '," "
    ,'Defectsin2014', " "
    ,'Defectsin2015'," "
    ,'costDefect   ', " "
    ,'req2014      '," "
    ,'req2015      ', " "
    ,'ba           '," "
    ,'config       ', " "
    ,'Financials   '," "
    ,'qa           ', " "
    ];

function buildLine(item) {
        var out = [];
    for (var i= 0,l=fdef.length;i<l;++i) {
        out.push(item[fdef[i][0]] || fdef[i][1]);
    }
    return '
' + out.join('	') + '
'
}

A: You can use this,
if(item.hasOwnProperty('req2015')){
  //add it
}


text:
Q: Setting the language and locale in Gnome on Debian-Bullseye has no effect I have a machine with Gnome on Bullseye. I set both Language and the Formats to German and Germany respectively in the Region and Language section of Settings GUI. After I restart the session, everything is still in English. The value of Language and Format fields are shown as German but the environment is still in English. This is on a non-admin account, but I have access to root.
When I run locale at the terminal
I get:
LANG=de_DE.UTF-8
LANGUAGE=en_US:en

Everyhting else is set to de_DE.UTF-8
LC_ALL is not set (set to nothing).
Also I notice that on the Login screen, the day is shown in German and months names in Calendar are in German, but most everything else (menus, options, messages, etc.) is in English.
UPDATE:
Somebody suggested that I should edit /etc/default/locale.
I did that and it seemed to work, with the caveat that now my admin account also changed language to German.
Then as per suggestion on Debian wiki, I ran dpkg-reconfigure locales and set the default to None.
It simply comments out the LANG line in /etc/default/locale.
I also set the relevant fields in the Region and Language section of the Settings GUI. After logout and login the admin account remained German, while the account that I wished to turn to German is back in English.
Manually setting
LANG=en_US.UTF-8
LANGUAGE="en_US:en"

in /etc/default/locale didn't work either. If you think the first line is missing quotation marks, I tried all permutations and it didn't change anything. For some reason, when I run the dpkg-reconfigure locales, it sets the first value without quotation marks and the second with them (or probably sets only one of them).
Following the other suggestions on Debian wiki, I tried the ~/.dmrc solution which did not work.
I added the line
: "${LANG:=en_US.UTF-8}"; export LANG

to /etc/profile, but this broke the system so that I could no longer login. I had to remove it. (also tried it without the colon at the beginning, same result)
Right now, the account I had tried to change to German is in English, whereas the admin account is in German. The settings GUI shows the right values, but the desktop environment ignores them. I can only characterize this as a bug.

A: SOLUTION

*

*Run sudo dpkg-reconfigure locales

*select the languages you wish to install.

NOTE 1: At the end, the wizard recommends setting the default language to None if other people are likely to ssh into this system. This will set the default to C.UTF-8. This can cause some apps to not operate properly. For example, after this, my Gnome terminal wouldn't start anymore. So if you set the default to none, then you must set a specific language for each individual account separately, as per instructions below.

*add the following to the ~/.profile for the user you wish to change the environment language for:

    LANG=de_DE.UTF-8
    LANGUAGE=de_DE:de
    LC_CTYPE="de_DE.UTF-8"
    LC_NUMERIC="de_DE.UTF-8"
    LC_TIME="de_DE.UTF-8"
    LC_COLLATE="de_DE.UTF-8"
    LC_MONETARY="de_DE.UTF-8"
    LC_MESSAGES="de_DE.UTF-8"
    LC_PAPER="de_DE.UTF-8"
    LC_NAME="de_DE.UTF-8"
    LC_ADDRESS="de_DE.UTF-8"
    LC_TELEPHONE="de_DE.UTF-8"
    LC_MEASUREMENT="de_DE.UTF-8"
    LC_IDENTIFICATION="de_DE.UTF-8"
    LC_ALL=

NOTE: Replace "de_DE.UTF-8" with the appropriate language code!

*Reboot.


text:
Q: Blackberry 9300: Can't locate installed application I have a Blackberry 9300. I install an application over the air but I cannot see the app anywhere. The app runs the first time after the installation. And if I go to options /applications I can see it there installed. However the icon app is nowhere to be found, and I can't run it again.
The app that I'm testing is the 2.0 Cordova example for blackberry.
Thanks

A: Did you check out in the downloads folder?


text:
Q: Manage VS Team Services Boards from mobile phone I would like to manage the cards of my VS Team Services boards from my mobile phone. This way I can add issue when I am at customer sites and check the development of other, move features to more urgent columns.
Is there a mobile app (for Android prefered, but I ask in general)? Is there an app for on-premise team services and/or visual studio online team services?

A: You can always use your browser to manage your visual studio team services projects - cards, boards and etc. Chrome on Android-phone are working very good for every proposes. You can also setup to publish your build or release results at slack.
Unfortunately, no official mobile client as an app.
But you can search and find many unofficial clients at Play market.
But of course without any warranty.

A: There is no official mobile app for VSTS. But there is already a user voice submitted here: Mobile App for Visual Studio Online/TFS. You can vote it. MS will review these feature requests.


text:
Q: How to add single quotes across a string in ruby? I am iterating over a config.yml from from which parsing the values in a string form as follows:
machines:
 A:
  ip: 10.11.12
  pass: vass
B:
  ip: 10.11.13
  pass: grass

The above config.yml is parsed as follows:
machines = YAML.load_file('machine.yml')
var=''
machines[A].each do |letters,hash|
   var += "[" + hash['ip'] + "]\n" + hash['pass'] + "\n"
end

The "var" value i am getting as :
   "[10.11.12]\nvass\n[10.11.13]\ngrass\n"

but instead like above i dont want double quotes rather single quotes across complete atring as follows:
   '[10.11.12]\nvass\n[10.11.13]\ngrass\n'

So, please suggest how can have single quotes across the string.

A: Generally the puts will print the value of the string without double quotes in the console.
So may be you can use puts var so that double quotes are not getting printed. And now you can wrap your content with single quote using string interpolation.
var += "'#{actual_value}'"


text:
Q: How do wildcards work in topic messaging with wso2/rabbitMq/c#? If I publish a message to a wso2 topic like so:
channel.BasicPublish(someExchangeName,"farm.cow.brown",null,someMessage);

I can retrieve the message if I am listening to the routing key "farm.cow.brown":
channel.QueueBind(someQueueName,someExchangeName,"farm.cow.brown");

I think I should also be able to get the message if I am listening to a variation such as this:
channel.QueueBind(someQueueName,someExchangeName,"farm.cow.*");

Of the two listening examples above the first works, the second never does, regardless of the routing key combinations attempted (farm.cow.* , farm.*.brown , farm.cow.# , farm.# , etc.).
I am connecting to wso2 using rabbitMq and c#.
Thank you.

A: This is working for me now. It appears that to use a wildcard to listen to multiple topics/routing paths, there need to be existing queues for each topic.
Here is what I mean: consider the topics "farm.cow.brown" and "farm.cow.white" and a listener consuming route "farm.cow.*".
If there is an existing queue on "farm.cow.brown" but not on "farm.cow.white", I will only get messages published to "farm.cow.brown", even though "farm.cow.white" exists and is getting messages published to it.
If there is a queue on "farm.cow.brown" and another on "farm.cow.white", "farm.cow.*" will get all messages published to "farm.cow.brown" and published to "farm.cow.white".
If neither have queues, "farm.cow.*" retries no messages published to "farm.cow.brown" and "farm.cow.white".
(As an aside, the "farm.cow.*" examples above are work equivalently using "farm.#")
To restate, using wildcards only retrieves messages for topics that have existing queues or subscriptions.
This is my experience. I have been testing this for a few days and it appears to be the consistent behavior.


text:
Q: How to check if a process id (PID) exists In a bash script, I want to do the following (in pseudo-code):
if [ a process exists with $PID ]; then

    kill $PID

fi

What's the appropriate expression for the conditional statement?

A: On systems that implement procfs interface such as Linux, you can just check if /proc/$PID exists:
if test -d /proc/"$PID"/; then
    echo "process exists"
fi

otherwise you can use ps program:
if [ -n "$(ps -p $PID -o pid=)" ]

In the latter form, -o pid= is an output format to display only the process ID column with no header. The quotes are necessary for non-empty string operator -n to give valid result.

A: I think that is a bad solution, that opens up for race conditions. What if the process dies between your test and your call to kill? Then kill will fail. So why not just try the kill in all cases, and check its return value to find out how it went?

A: It seems like you want
wait $PID

which will return when $pid finishes.
Otherwise you can use
ps -p $PID

to check if the process is still alive (this is more effective than kill -0 $pid because it will work even if you don't own the pid).

A: ps command with -p $PID can do this:
$ ps -p 3531
  PID TTY          TIME CMD
 3531 ?        00:03:07 emacs

A: The best way is:
if ps -p $PID > /dev/null
then
   echo "$PID is running"
   # Do something knowing the pid exists, i.e. the process with $PID is running
fi

The problem with kill -0 $PID is that the exit code will be non-zero even if the process is running and you don't have permission to kill it. For example:
kill -0 $known_running_pid

and
kill -0 $non_running_pid

have a non-zero exit codes that are indistinguishable for a normal user, but one of them is by assumption running, while the other is not.

Partly related, additional info provided by AnrDaemon: The init process (PID 1) is certainly running on all Linux machines, but not all POSIX systems are Linux. PID 1 is not guaranteed to exist there:
kill -0 1
-bash: kill: (1) - No such process …

DISCUSSION
The answers discussing kill and race conditions are exactly right if the body of the test is a "kill". I came looking for the general "how do you test for a PID existence in bash".
The /proc method is interesting, but in some sense breaks the spirit of the ps command abstraction, i.e. you don't need to go looking in /proc because what if Linus decides to call the exe file something else?

A: To check for the existence of a process, use
kill -0 $pid

But just as @unwind said, if you want it to terminate in any case, then just
kill $pid

Otherwise you will have a race condition, where the process might have disappeared after the first kill -0.
If you want to ignore the text output of kill and do something based on the exit code, you can
if ! kill $pid > /dev/null 2>&1; then
    echo "Could not send SIGTERM to process $pid" >&2
fi

A: For example in GNU/Linux you can use:
Pid=$(pidof `process_name`)

if [ $Pid > 0 ]; then

   do something
else

   do something
fi

Or something like
Pin=$(ps -A | grep name | awk 'print $4}')
echo $PIN

and that shows you the name of the app, just the name without ID.

A: You have two ways:
Lets start by looking for a specific application in my laptop:
[root@pinky:~]# ps fax | grep mozilla
 3358 ?        S      0:00  \_ /bin/sh /usr/lib/firefox-3.5/run-mozilla.sh /usr/lib/firefox-3.5/firefox
16198 pts/2    S+     0:00  \_ grep mozilla

All examples now will look for PID 3358.
First way: Run ps aux and grep for the PID in the second column. In this example I look for firefox, and then for it's PID:
[root@pinky:~]# ps aux | awk '{print $2 }' | grep 3358
3358

So your code will be:
if [ ps aux | awk '{print $2 }' | grep -q $PID 2> /dev/null ]; then
    kill $PID
fi

Second way: Just look for something in the /proc/$PID directory. I am using exe in this example, but you can use anything else.
[root@pinky:~]# ls -l /proc/3358/exe
lrwxrwxrwx. 1 elcuco elcuco 0 2010-06-15 12:33 /proc/3358/exe -> /bin/bash

So your code will be:
if [ -f /proc/$PID/exe ]; then
    kill $PID
fi

BTW: whats wrong with kill -9 $PID || true ?

EDIT:
After thinking about it for a few months.. (about 24...) the original idea I gave here is a nice hack, but highly unportable. While it teaches a few implementation details of Linux, it will fail to work on Mac, Solaris or *BSD. It may even fail on future Linux kernels. Please - use "ps" as described in other responses.

A: By pid:
pgrep [pid] >/dev/null

By name:
pgrep -u [user] -x [name] >/dev/null

"-x" means "exact match".

A: here i store the PID in a file called .pid (which is kind of like /run/...) and only execute the script if not already being executed.
#!/bin/bash
if [ -f .pid ]; then
  read pid < .pid
  echo $pid
  ps -p $pid > /dev/null
  r=$?
  if [ $r -eq 0 ]; then
    echo "$pid is currently running, not executing $0 twice, exiting now..."
    exit 1
  fi
fi

echo $$ > .pid

# do things here

rm .pid

note: there is a race condition as it does not check how that pid is called. if the system is rebooted and .pid exists but is used by a different application this might lead 'unforeseen consequences'.

A: I learned from and upvoted @FDS's answer here, because it is good and correct. But, here's a form I find easier to read and understand.
So, here is my preferred version:
Explanation:

*

*The "$?" part means "the exit or return code from the previous command".

*The ps --pid "$pid" command returns exit code 0 if the specified PID ("$pid") is running, and some other number if not.

*Doing > /dev/null discards all output printed to stdout, since we don't want to see it. Rather, all we want is the exit code ("$?") from the ps --pid "$pid" command to see if that PID is running. More specifically, using > /dev/null redirects stdout output to the /dev/null pseudofile, whose purpose is to discard all incoming input.

pid=1234
ps --pid "$pid" > /dev/null
if [ "$?" -eq 0 ]; then
    echo "PID $pid exists and is running."
fi

Running shellcheck path/to/this_script.sh tells me I should actually do it the other way (as @FDS shows) to avoid redundancy. See the shellcheck output here:
eRCaGuy_hello_world/bash$ shellcheck check_if_pid_exists.sh

In check_if_pid_exists.sh line 46:
if [ "$?" -eq 0 ]; then
     ^--^ SC2181: Check exit code directly with e.g. 'if mycmd;', not indirectly with $?.

For more information:
  https://www.shellcheck.net/wiki/SC2181 -- Check exit code directly with e.g...

Notice especially this part:

SC2181: Check exit code directly with e.g. 'if mycmd;', not indirectly with $?.

See the full description for this error code here: https://github.com/koalaman/shellcheck/wiki/SC2181.
So, shellcheck recommends this form instead:
pid=1234
if ps --pid "$pid" > /dev/null; then
    echo "PID $pid exists and is running."
fi

If you want to adjust to doing it that way, go for it. But, if you'd rather do it my way because you consider my way easier to read and understand, as I do, then you can optionally disable that shellcheck warning by adding # shellcheck disable=SC2181 above that line, like this:
My final and preferred answer
ps --pid "$pid" >/dev/null
# shellcheck disable=SC2181
if [ "$?" -eq 0 ]; then
    echo "PID $pid exists and is running."
else
    echo "PID $pid does NOT exist."
fi

The key takeaway here, however, is to never insert any command, not even an echo or print statement, between the command being checked (ps in this case) and checking the error code with "$?", or else checking the error code will accidentally check the error code from the latest command, such as the inserted echo or print statement, instead of from the command of interest (ps in our case)!
That's the main reason shellcheck recommends what they do: they want to make sure you're checking the error code of the correct command.
Other than that, it's just a pedantic opinion-based-discussion-equivalent to the argument in C about how you should check for NULL (null pointer) values:
// The way preferred by pedantic people who don't want to "be redundant" with
// an "unnecessary" `== NULL` check:
if (!some_ptr)
{
    printf("ERROR: null ptr.\n");
    return;
}

// Versus the more-readable and understandable way which I prefer to use
// whenever my peers will approve it without a fight or long argument
if (some_ptr == NULL)       // in C
// if (some_ptr == nullptr) // in C++
{
    printf("ERROR: null ptr.\n");
    return;
}

// Note: I just want to get my code merged and move on with life, so if they
// won't easily approve my preferred version above, I'll switch to the other,
// more-pedantic version of code to try to get a quick approval so I can be
// more productive.
// There are few things more discouraging than being blocked over
// silly "pedantry" when your code is correct, bug-free, well-written, and does
// what it says it does.

So, just as which way you choose to check for NULL values (null ptrs) in C is purely a matter of taste, which way in bash you choose to check for error codes/return codes is also purely a matter of taste. Currently, I prefer the version above I have marked as "My final and preferred answer".
Anyway, here is a full, runnable program
check_if_pid_exists.sh from my eRCaGuy_hello_world repo:
#!/usr/bin/env bash

pid=1234

if [ "$#" -gt 0 ]; then
    # At least 1 argument was passed in, so assume it is the PID
    pid="$1"
fi

# Try to print the process (`ps`) information for this PID. Send it to
# /dev/null, however, so we don't actually have to look at it. We just want
# the return code, `$?`, which will be 0 if the process exists and some other
# number if not.
ps --pid "$pid" > /dev/null
# shellcheck disable=SC2181
if [ "$?" -eq 0 ]; then
    echo "PID $pid exists and is running."
else
    echo "PID $pid does NOT exist."
fi

Sample run calls and output:
eRCaGuy_hello_world/bash$ ./check_if_pid_exists.sh 28876
PID 28876 exists and is running.

eRCaGuy_hello_world/bash$ ./check_if_pid_exists.sh
PID 1234 does NOT exist.

eRCaGuy_hello_world/bash$ ./check_if_pid_exists.sh 5678
PID 5678 does NOT exist.

You can find valid PIDs (Process IDs) to send to my script by first running ps aux and choosing a PID to pass to it.
Related

*

*My answer on How to wait in bash for several subprocesses to finish, and return exit code !=0 when any subprocess ends with code !=0?


text:
Q: how to Show Poster image on video ends using Jquery? My HTML5 Video Control API got a shape. But now the client asks me to show Poster once video played.
Now there is a dark black background.
Please let me know how I have to do that.
<video width="640" height="360" x-webkit-airplay="allow" poster="asserts/poster.png" preload="" tabindex="0" class="video1">
    <source data-quality="sd" src="http://media.jilion.com/videos/demo/midnight_sun_sv1_360p.mp4"></source>
    <source data-quality="hd" src="http://media.jilion.com/videos/demo/midnight_sun_sv1_720p.mp4"></source>
    <source data-quality="sd" src="http://media.jilion.com/videos/demo/midnight_sun_sv1_360p.webm"></source>
    <source data-quality="hd" src="http://media.jilion.com/videos/demo/midnight_sun_sv1_720p.webm"></source>
</video>

And the Jquery funciton for play/ pause is:
/* Play/Pause */
    var gPlay = function() {
        if($hdVideo.attr('paused') == false) {
            $hdVideo[0].pause();
            $video_main_control.removeClass("hd-video-main-control-none");
            $hdVideo[0].poster.show();
        }
        else {
            $hdVideo[0].play();
            $video_main_control.addClass("hd-video-main-control-none");
        }
    };
    $video_main_control.click(gPlay);
    $hd_play_btn.click(gPlay);
    $hdVideo.click(gPlay);
    $hdVideo.bind('play', function() {
        $hd_play_btn.addClass('hd-paused-button');
            });
            $hdVideo.bind('pause', function() {
                $hd_play_btn.removeClass('hd-paused-button');
            });
    $hdVideo.bind('ended', function() {
                $hd_play_btn.removeClass('hd-paused-button');
    });

A: <video width="640" height="360" x-webkit-airplay="allow" poster="asserts/poster.png" preload="" tabindex="0" class="video1" id="video_elem">
</video>

var showBanner = function () {
    // Show your banner
};
document.getElementById("video_elem").addEventListener("ended",showBanner, false );

Video api has "ended" event for this purpose. Ref: https://developer.mozilla.org/en-US/docs/DOM/Media_events


text:
Q: Powershell SOAP request with parameter I need a powershell script to call a soap service, the problem I am currently having is the soap service method has a parameter, I know for sure that I can get the powershell script to work when the method has no parameters but as soon as their is a parameter I receive an error.
i.e.
+ $res = $req.GetResponse <<<< ()
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

Soap request which works (powershell so I have used double quotes where appropriate):
<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
        <soap:Body>
          <CheckStockLevels/>
       </soap:Body>
</soap:Envelope>"

Soap request which doesn't work (powershell so I have used double quotes where appropriate):
<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
        <soap:Body>
          <CheckStockLevels>
             <configurationName>123</configurationName>
          </CheckStockLevels>
       </soap:Body>
    </soap:Envelope>"

Does anyone know how I should format the XML for the soap request which doesn't work?

A: This works?
$soap = [xml]@'
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
 <soap:Body>
  <CheckStockLevels>
    <configurationName>123</configurationName>
  </CheckStockLevels>
 </soap:Body>
</soap:Envelope>"
'@


text:
Q: Calcular a diferença de meses Tenho essa função
<?php
    function calcula_intervalo_custo($data_inicial, $data_final) {

        function geraTimestamp($data) {
            $partes = explode('/', $data);
            return mktime(0, 0, 0, $partes[1], $partes[0], $partes[2]);
        }

        $time_inicial = geraTimestamp($data_inicial);
        $time_final   = geraTimestamp($data_final);

        $diferenca = $time_final - $time_inicial;

        $res_mes = (int)floor( $diferenca / (60 * 60 * 24 * 24));

        return $res_mes;
    }
?>

Que retorna a diferença entre meses a função diz que de 01/09/2019 para 01/02/2019 a diferença é de 6 meses (o correto seriam 5 meses), e que de 01/12/2019 para 01/02/2019 é de 2 meses (esse está certo).

A: Obtive o erro:

PHP Fatal error:  Cannot redeclare geraTimestamp()

Isto é claro porque se usar mais de uma vez a função ele vai chamar novamente a declaração a cada vez que usar a função, o que se resolve assim:
function geraTimestamp($data) {
    $partes = explode('/', $data);
    return mktime(0, 0, 0, $partes[1], $partes[0], $partes[2]);
}

function calcula_intervalo_custo($data_inicial, $data_final) {
    $time_inicial = geraTimestamp($data_inicial);
    $time_final   = geraTimestamp($data_final);

    $diferenca = $time_final - $time_inicial;

    $res_mes = (int)floor( $diferenca / (60 * 60 * 24 * 24));

    return $res_mes;
}

Então depois de corrigido ao executa isto:
var_dump(calcula_intervalo_custo('01/02/2019', '01/09/2019')); //Obtive 8
var_dump(calcula_intervalo_custo('01/02/2019', '01/12/2019')); //Obtive 12

São valores totalmente diferentes dos que você citou, mas talvez imagino o porque, é que na verdade não é 01/09/2019 e 01/12/2019, o correto seria o ano de 2020 para ambos, logo então:
var_dump(calcula_intervalo_custo('01/09/2019', '01/02/2020')); //6
var_dump(calcula_intervalo_custo('01/12/2019', '01/02/2020')); //2

*

*Do dia 1 ao 30 de Setembro tem 30 dias

*Do dia 1 ao 31 de Novembro tem 31 dias

*Do dia 1 ao 31 de Dezembro tem 31 dias

*Do dia 1 ao 31 de Janeiro tem 31 dias

*Do dia 1 ao 31 de Fevereiro tem 29 dias (ano bissexto)

Somando temos 152 dias, que dividido por 30 daria 5,06, que arredonda para 5, então o que me parece errado é esta parte:
60 * 60 * 24 * 24

Se 60 é segundos, 60 é minutos, 24 é horas, então o outro 24 deve ser dias, mas um mês tem uma média de 30 dias e não de 24, creio que o correto seria:
60 * 60 * 24 * 30

Se o seu objetivo é descontar os dias finais de semanas e domingos então acho que não faz sentido, porque os dias passaram de qualquer forma e na verdade você teria que descontar primeiro do valor diferença e depois calcular, isso é um código hipotético:
$diferenca = $time_final - $time_inicial - $finais_de_semana;

$res_mes = (int) floor( $diferenca / (60 * 60 * 24 * 30));

Mas não tenho certeza se é o que deseja, mas se for o caso talvez para remover os dias de sábado e domigo talvez você tenha que criar um loop e checar dia a dia com uma IF:
if (date('N', $dia) < 6) {
   //É dia de semana
}

Eu não vou sugerir um script nem nada, porque até deve ter respostas no site que já resolvem, mas não tenho como saber se este é o seu problema, até aonde parece você só confundiu o 60 * 60 * 24 * 24 quando deveria ser 60 * 60 * 24 * 30


text:
Q: Cannot resolve dependencies or references in MVC3 C# I have an error in MVC/Controllers/ProductCOntroller.cs when trying to build solution.
Need to have a reference to SportsStore.Domain in SportsStore.WebUI
using System.Linq;
using System.Web.Mvc;
using SportsStore.Domain.Abstract;

namespace SportsStore.WebUI.Controllers
{
    public class ProductController : Controller
    {
        private IProductRepository repository;
        public ProductController(IProductRepository productRepository)
        {
            repository = productRepository;
        }
    }
}

The type or namespace name 'Domain' does not exist in the namespace 'SportsStore' (are you missing an assembly reference?)
I have set up Project dependencies for MVC (WebUI) to C# class library (Domain)
How to fix it?

A: You need to add a reference to SportsStore.Domain in SportsStore.WebUI?.
You can do this be right clicking on the "References" folder under SportsStore.WebUI in the Solution Explorer and selecting "Add Reference...".

then navigate to the "Solution" Tab:

and select SportsStore.Domain.


text:
Q: WPDB secure custom form I'm creating a custom form to update rows in a secondary MYSQL DB, different from the one of wordpress. This form is public and every user can access it. So I've created a plugin and I'm using also wpdb to connect with the database.
How can I do this in a secure way?
I'm using sanitize_text_field() and then wpdb->update(). Is this safe or should I use esc_sql()?
If I can't use wpdb->update() because I need to have some != fields in where clauses, is it ok to use sanitize_text_field(), then wpdb->prepare() and then wpdb->query()?

A: When getting user input to be stored on database, a good way to proceed is:

*

*Data validation: validate the data according whith the data you expect. For example: HTML string, number, email, URL, any text with no HTML, ect. Never trust on user input or client-side validation. You can make here also some sanitization, but it is not substitute of data validation and it is not substitute of data scaping.

*SQL escape: no explanation needed here I think. WorPress provide some functions and methods to perform this. esc_sql is the general function to prepare strings to be used in database queries. But is not always needed if you use wpdb class. For example, if using $wpdb->insert and $wpdb->update the data should be not scaped because it will be done for you.

If using $wpdb->query, the best method to scape the query is using $wpdb->prepare method. Additional scape methods are avalable in wpdb class; see this of how to use $wpdb->prepare and this for data escape before database interaction.

A: An example for inserting data to WPDB securely. It's prepared method which prevents the sql injection. First create your form and then insert your data like the following structure. Example:
$insert_value_array = array(
    'input' => '',      // name of your input field
    'textarea' => '',   // field name
    'select' => '',     // field name
    'checkbox' => '',   // field name
);

$form_item = shortcode_atts( $insert_value_array, $_REQUEST );

if(isset($_POST['submit'])){

    global $wpdb;

    $full_table_name = $wpdb->prefix . 'your_table_name';

    // $wpdb->insert( $full_table_name, $form_item); // It's without prepare method

 // Safe data insertion with prepare method ( successful )
    $wpdb->query( $wpdb->prepare(
                "   INSERT INTO $full_table_name
                    ( column_name_1, column_name_2, column_name_3, column_name_4 )
                    VALUES ( %s, %s, %s, %s )
                ", // VALUES depends on your datatype. %s for string, %d for integer
                    $form_item
            ) );

};


text:
Q: Rendering two different objects using opengl ES for android In my program I am rendering a simple triangle and a textured cube, Individually both work fine but when i call the respective draw methods together , the texturing of cube doesn't show.
The onSurfaceCreated function is as shown below:
public void onSurfaceCreated(GL10 gl, EGLConfig eglConfig) {
        cub.loadGLTexture(gl, this.context);
        //gl.glEnable(GL10.GL_TEXTURE_2D);
        gl.glShadeModel(GL10.GL_SMOOTH);
        gl.glClearColor(0.5f, 0.5f, 0.5f, 0.5f);
        gl.glClearDepthf(1.0f);
        gl.glEnable(GL10.GL_DEPTH_TEST);
        gl.glDepthFunc(GL10.GL_LEQUAL);
        gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
}

The onDrawFrame is as shown below:
public void onDrawFrame(GL10 gl) {
    gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
    gl.glMatrixMode(GL10.GL_MODELVIEW);
    gl.glLoadIdentity();
    GLU.gluLookAt(gl, 0, 0, -5, 0, 0, 0, 0, 2, 0);
    tri.draw(gl);
    gl.glRotatef(-90, 1, 0, 0);
    gl.glTranslatef(-6, 0, 0);
    cub.draw(gl);
}

A: I got the answer. Actually i just had to clear the color of the 2D model before binding the 3D model to its texture.Thanks everyone.


text:
Q: RESTful API: is it appropriate to make POST request without data I'm working on service that collects prices from third-party online shop. I use RESTful API to add new product id and get price by id.
To add new product:
POST /product/12345 (parses product page and stores price to db)
To update stored price:
PUT /product/12345 (parses product page and updates price in db)
To get price:
GET /product/12345 (return price from db if data exists)
My question is am I doing it right way (especially with POST verb)?

A: Normally the API calls for the Post : Data will not be placed on the url, which can be mentioned like below
To add new product: POST /product/new
Thanks,
SVN

A: To add a new product, POST to the collection resource /product:
POST /product/

The server will assign an ID to the new Product and return it.
201 Created
Location: http://example.com/product/9876

Edit:
If you already know the ID, create the product using PUT:
PUT /product/9876


text:
Q: Search and replace on variable name within S-Expression (lexical scope)? Using emacs with Paredit enabled.  How can I search through a LISP (Clojure) S-expression and rename a variable?  I'd like to do it within the current S-expression instead of globally.

A: Just use C-M-<space> at the start of the s-expression you'd like to use as your scope, to highlight it, and then do a query-replace as usual - it restricts itself to the active region.

A: The query-replace with active region is quite good for general
search/replace in region.  But for refactoring code, I much prefer iedit.
To rename a variable within a defun, go to the symbol to be reanmed, press
C-0 C-; and edit away.
To rename a variable within arbitrary region, go to the symbol, press
C-;, select the region of interest, and press C-; again.
iedit has many other functions to help code refactoring.  Hint: C-'


text:
Q: Is it possible to use Intel AMT to manage MacBooks? https://www.intel.com/content/www/us/en/architecture-and-technology/intel-active-management-technology.html
I've heard MacBook intel chips are AMT-capable, but AMT isn't ever enabled so you can't actually use it. Is this true?

A: Neither SCCM nor AMT are viable management suites for macOS. The former has some limited success doing anything, AMT flat out isn't well documented. One recent vulnerability seems to cover chipsets Apple uses, but there's no Apple link amongst the 30+ vendor links to patch those vulnerabilities:

*

*https://www.intel.com/content/www/us/en/support/articles/000025619/software.html
I would look to one of the traditional Mac MDM solutions to manage your Macs. I would also contact intel and Apple if you have a specific serial you want to check is or is not vulnerable and get an on the record answer.
As far as pragmatic solutions to manage macs, start with a free hosted MDM like https://www.jamf.com/products/jamf-now/ and then you can evaluate if you want to pay for a hosted service as you grow or partner / build your Mac MDM solution from open source like https://www.munki.org/munki/


text:
Q: Where to initialize UILabel? Somewhere in my storyboard I have ViewController(ReadingViewController), which I am instantiating the following way:
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main_iPad" bundle:NULL];
ReadingViewController *viewController = (ReadingViewController *)[sb instantiateViewControllerWithIdentifier:@"SB_RDVC"];
viewController.infoLabel.text = @"test";

That VC has some label outlets created in storyboard. When I try to initialize the label right after instantiation, it failed - label value is same as I set in storyboard.
As workaround I made a string property in VC, then just assigning @"test" to that variable. In viewDidLoad of ReadingViewController I just self.infoLabel.text = self.uglyProperty.
This seems ugly to me, is there a better way to assign outlet label right after instantiation?

A: Perhaps the reason why your text is the same as before is because your view has not loaded yet - set a breakpoint in viewDidLoad method of your VC and see if that gets called before or after you assign your label.
You could write a protocol and make your class a delegate of ReadingViewController, so that you could receive a callback when viewDidLoad is called, although I'm not sure that's a simpler solution than creating a property for the infoLabel text.


text:
Q: Add object to object array within mongodb model with graphql-compose-mongoose I made a GraphQL API to retrieve and manipulate data in a mongo database. This data represents an author that contains a list of books as shown in Author.ts.
Author.ts:
import { Document, Model, model, Schema } from "mongoose";
import { Ibook } from "./book";

export interface Iauthor extends Document {
    name: String;
    books: Array<Ibook>;
  }

const AuthorSchema: Schema = new Schema({
    name: { type: String, required: true },
    books: { type: Array, required: true }
  });

export const Author: Model<Iauthor> = model('author', AuthorSchema);

Book.ts:
import {Document, Model, model, Schema} from "mongoose";

export interface Ibook extends Document {
    title: String;
    pages: Number;
  }

const BookSchema: Schema = new Schema({
    title: { type: String, required: true },
    pages: { type: Number, required: true }
  });

export const Book: Model<Ibook> = model('book', BookSchema);

I'm using query resolvers and mutation resolvers to read and manipulate these objects. I just migrated to graphql-compose-mongoose to generate the resolvers instead of programming them myself. I succeeded in migrating every query and mutation till I encountered my resolver "AssignBooktoAuthor". This basicly is a resolver that adds a book object to the authors books list. I simply do not know how to get it working with graphql-compose-mongoose.
composer.ts:
import { composeMongoose } from "graphql-compose-mongoose";
import { schemaComposer } from "graphql-compose";
import { Book } from "./models/book";
import { Author } from "./models/author";

const customizationOptions = {};
const BookTC = composeMongoose(Book, customizationOptions);
const AuthorTC = composeMongoose(Author, customizationOptions);

//in aparte file zetten prob
schemaComposer.Query.addFields({
  getAllBooks: BookTC.mongooseResolvers.findMany(),
  getBookById: BookTC.mongooseResolvers.findById(),
  getAllAuthors: AuthorTC.mongooseResolvers.findMany(),
  getAuthorById: AuthorTC.mongooseResolvers.findById(),
});

schemaComposer.Mutation.addFields({
  CreateBook: BookTC.mongooseResolvers.createOne(),
  UpdateBook: BookTC.mongooseResolvers.updateById(),
  DeleteBook: BookTC.mongooseResolvers.removeById(),
  CreateAuthor: AuthorTC.mongooseResolvers.createOne(),
  UpdateAuthor: AuthorTC.mongooseResolvers.updateById(),
  DeleteAuthor: AuthorTC.mongooseResolvers.removeById(),
  /**AssignBooktoAuthor: AuthorTC.mongooseResolvers.///What function does this??///**/
});

const graphqlSchema = schemaComposer.buildSchema();
export default graphqlSchema;

gql.ts (server file):
import { ApolloServer, gql } from "apollo-server-express";
import * as mongoose from "mongoose";
import * as express from "Express";
import * as dotenv from "dotenv";
import * as jwt from "jsonwebtoken";
import graphqlSchema from "./composer";

const app = express();

dotenv.config();

(async () => {
  mongoose.connect("mongodb+srv://xxxxxxx:xxxxxxx@clusterxxxxx.mongodb.net/myFirstDatabase?retryWrites=true&w=majority", { useUnifiedTopology: true , useNewUrlParser: true});

  const server = new ApolloServer({
    schema: graphqlSchema,
  });

  await server.start();

  //verifying token
  app.use((req, res, next) => {
    const Token = req.header('auth-token');
    try{
      (Token && jwt.verify(Token, process.env.TOKEN_SECRET)) ? next() : console.log("mw: Unauthorized");
    }catch(err){
      console.log("mw:Unauthorized");
    }
  });

  server.applyMiddleware({ app });

  app.listen({ port: 4000 }, () =>
  console.log(` Server ready at http://localhost:4000${server.graphqlPath}`)
  );

})();

Since the support on graphql-compose-mongoose is not that big I hope there is someone who can help me with this problem!

A: I found the solution myself!
Graphql supports the use of adding relations by object id. So in the model you have to assign a type called something like authorid and then add a "ref" with the objectid type. see book.ts for example. See composer.ts for the addrelation example.
Book.ts:
export interface Ibook extends Document {
  title: String;
  pages: Number;
  author: Schema.Types.ObjectId;
}

const BookSchema: Schema = new Schema({
  title: { type: String, required: true },
  pages: { type: Number, required: true },
  author: { type: Schema.Types.ObjectId, ref:"author", required: true}
});

Composer.ts:
BookTC.addRelation('author', {
  resolver: () => AuthorTC.mongooseResolvers.findById(),
  prepareArgs:{
    _id: source => source.author,
    skip: null,
    sort: null,
  },
  projection: {author: true},
})

AuthorTC.addRelation('books', {
  resolver: () => BookTC.mongooseResolvers.findMany(),
  prepareArgs: {
    filter: source => ({ author: source._id }),
  },
  projection: { id: true },
});


text:
Q: How can I use the same string created by password-generator in different places? So I am stuck here where I need to use the value generated by generatePass() function. I need to obtain the same value of witPass in newPass to the same variable used in witclick() function.But I get different values because the generatePass function is called again generating a different random value.
I hope I am clear in explaining my issue since it's my first question.

```loginFunctions.js```
var passwordHolder = document.querySelector('#passwordholder);
var password;
var witPass;
witPass=password=generatePass();

//newPass is invoked when generatePassword button is clicked
function newPass() {
  passwordHolder.textContent = password;
  console.log(password);
  console.log(witPass);
  return witPass;
}

//function to generate random password
function generatePass() {
  var length = 8,
    charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
    retVal = "";
  for (var i = 0, n = charset.length; i < length; ++i) {
    retVal += charset.charAt(Math.floor(Math.random() * n));
  }
  //witPass1=retVal;
  return retVal;
}
//witness login button click event
function witclick() {
  console.log('witclick invoked');
  witnessEmail = document.getElementById('witnessEmail').value;
  witnessPassword = document.getElementById('witnessPassword').value;
  console.log(witnessPassword);
  console.log(witPass);
}

index.html

        <form class="border border-dark rounded bg-dark  text-light">

            Email address
            <input id="mailid" type="email" id="email" class="form-control" placeholder="Enter email">
            Enter a Valid Email Address

Password

          <button id="sendCred" class="btn btn-danger p-2 m-2" type="button">send cred</button>
          <button id="generatePassword" onclick="newPass()" class="btn btn-danger p-2 m-2" type="button">Generate Password</button>
          <button id="backToButtons" class="btn btn-danger p-2 m-2" type="button">Back</button>
        </form>

        <form action="" class="border border-dark rounded bg-dark  text-light">

            Email address
            <input type="email" id="witnessEmail" class="form-control" placeholder="Enter email">
            Enter a Valid Email Address

            Password
            <input type="password" id="witnessPassword" class="form-control" placeholder="Password">

          <button id="witnessFormLogin" onclick="witclick()" class="btn btn-danger p-2 m-2" type="button">Login</button>
        </form>


text:
Q: protect " for a request I have a sql request like this:
"INSERT INTO pirate(title, title_simple, user, magnet_link, \
 url, created, size, infos, images, description, number, response, new) VALUES
 (\"{0}\", \"{1}\", \"{2}\", \"{3}\", \
  \"{4}\", \"{5}\", \"{6}\", \"{7}\", \"{8}\", \"{9}\", \"{10}\", \"{11}\", \"{12}\")".format(blablabla...)

But some of the parameters of my query are huge pieces of text, mostly like a description. And sometimes there is this character in the text: "
I already tried to protect the strings I use in my query, with this syntax for an example:
\"{9}\"

But it does not work for ". Do you have any idea about how to solve my basic problem, and what is the good way to do it ?
EDIT:
@Martijn Pieters: I tried but it does not work:
requete = "INSERT INTO pirate(title, title_simple, user, magnet_link, \
           url, created, size, infos, images, description, number, response, new) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"

params = (torrent.title, simpleChar(torrent.title), torrent.user, torrent.magnet_link,
      str(torrent.url), torrent.created, strByteToOctet(torrent.size)[1],
      str_infos, str_images, torrent.info, torrent.id, retours, True)

bdd = sqlite3.connect("fichiers.sqlite")
bdd.row_factory = sqlite3.Row
c = bdd.cursor()

c.execute(requete, params)

bdd.commit()
c.close()
bdd.close()

Also, I'm doing this in a thread, so I don't get easily debug infos

A: Leave escaping of values to the database adapter. Use SQL parameters instead, not string formatting:
query = """\
    INSERT INTO pirate(
        title, title_simple, user, magnet_link,
        url, created, size, infos, images, description, number, response, new)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    """

params = (pirate_title, simplify(pirate_title), userid, link, url,
          datetime.now(), 0, torrent_infos, torrent_images, desc,
          42, response, True)
cursor.execute(query, params)

Using SQL parameters delegates escaping to the specialist, preventing SQL injection attacks and allowing the database to cache and reuse any query plans it generates.
See the sqlite3 documentation:

Usually your SQL operations will need to use values from Python variables. You shouldn't assemble your query using Python's string operations because doing so is insecure; it makes your program vulnerable to an SQL injection attack (see http://xkcd.com/327/ for humorous example of what can go wrong).
Instead, use the DB-API's parameter substitution. Put ? as a placeholder wherever you want to use a value, and then provide a tuple of values as the second argument to the cursor's execute() method. (Other database modules may use a different placeholder, such as %s or :1.)


text:
Q: API gateway for WebSocket I need a API gateway for my websocket application.

*

*Analyse and identify unusual requests from certain IP

*Quotas and Rate Limiting

*Statistics

*Free or commercial

*Solid performance

The sub-protocol of my WebSocket is WAMP, so I am afraid there is no existing product to do the job.
I intend to develop one and suppose it will work in this way:

*

*There is a proxy (NGINX or HAProxy) installed between my client application and my websocket server

*The proxy duplicates the request/response to another app, which I call monitor

*The monitor app analyses the flow and control the proxy to limit/block certain ip.

*The monitor app run alongside and if it is down, it does not affect my application and the proxy.

This approach sounds feasible. But the proxy seems not support reusing upstream connection to the monitor.
Suppose there are 10K connections established from proxy to clients, then proxy also establishes 10K connections as upstream to monitor app? that is unacceptable.
I expect only one or several connections are established between proxy and monitor to send the duplicate requests/responses. Certainly the proxy informs monitor the real source/target for each request / response.
Is there any proxy or product satisfying this requirement so that I only need develop less?

A: (TL;DR ... sorry!)
I'm working on a project doing something very similar with G-WAN.  Initially, I wrote API servlets, which worked quite well didn't take full advantage of G-WAN capabilities.  With some pointers from G-WAN support, I started exploring the use of handlers; I ported my API servlets to a URL-rewrite routine in a handler (vast majority of the content returned for an API query is static / pre-rendered content).  I'm now working on a 404-handler routine to catch the cases where we don't (yet) have the content pre-rendered, turning them into render-on-demand requests and building the response dynamically.
From the client side, it all looks totally dynamic.  But by doing URL-rewrites to static paths and allowing G-WAN to dispatch our on-demand cases, it reduces the amount of code we have to write, AND makes use of some highly-optimized features in G-WAN.  I'm mentioning these details as an example of what Gil referred to as "breaking the mould."  Initially our approach looked a lot like how we would do an implementation with nginx (except without the need for a gateway like fcgi).  It has been quite an improvement though once we stripped down to requirements and threw away many assumptions about how web services should be constructed.
One word of caution, if you plan on doing development in C++.  The linkage from G-WAN to external libraries is "C" and not "C++".  They did this performance and memory-footprint reasons (good choice), but I hadn't thought that through fully when I started writing some library routines in C++ that I intended to reference from within my G-WAN servlets and handlers in addition to being referenced from various C++ applications.  It's not a showstopper - plenty of "C" libraries out there that work just fine with C++ apps.  But it would be cumbersome to reference a dynamic C++ class library (.so) via a "C" linkage through G-WAN from a servlet.  (My simple fix was to move my "shared" C++ code into .h files and just include them into my G-WAN handlers and servlets, as well as in my C++ apps.  Not clean, but expedient.)
To your 5 specific points, from a G-WAN perspective:

*

*Depending on your definition of "analyse" and "unusual" this could easily be done in C/C++ within your protocol handler, or you can make use of external libraries.  There are multiple ways to make that asynchronous, either as separate processes or maybe just non-blocking I/O, if blocking is an issue.

*Also easily managed from a handler.

*Ditto.

*Yes.  :)   Depends on the level of support you want.  Free if you rely exclusively on SO and other community support.  We opted for an inexpensive support subscription, and the responses have well exceeded our expectations.

*Oh yeah!  We confirmed that in the first few days.
Oh, and one last thing:  Once you have spent an hour or two writing some G-WAN servlets, you may have a hard time going back to other web/app/service mechanisms.  With servlets, I just save my changes from the editor and hit refresh on the browser window to see the new result (try that with an fcgi implementation!).  I have multiple instances of G-WAN running on my server (configured for different IP addresses and port numbers) so on a single machine, I have multiple stages of development code bases, plus a production server.  For development, I run G-WAN in a terminal session (not as a daemon), and can make use of printf(...) in my servlet and handler codes to see what is happening on the back-end vs what happens in my browser window.
For more info:

*

*G-WAN Protocol Handler

*G-WAN User's Manual (starting around page 34)

*handler states

*calling library functions from servlets, handlers

*and also look at the examples in the handlers folder of the G-WAN installation package.

Good luck!
Ken

A: A G-WAN protocol handler will let you implement such a proxy to multiplex requests through one single connection (or a connection per worker thread for more scalability).
That's what G-WAN makes easy: breaking the mould to create custom solutions.


text:
Q: Can a xib in a project use autolayout while the main storyboard doesn't? The subject says it all.
I would guess that the answer is "yes" since Xcode saves the xib and the storyboard independently. The question is, if this also works correctly while runtime or if there are known problems or quirks.
Any thoughts appreciated.

A: Yes, auto layout can be turned on individually on any Interface Builder file. All the view controllers can coexist.


text:
Q: Environment specific Capefile capistrano3 rails 4.1 I have rails 4.1 app and multistage (staging, production) deployment with capistrano3.
I want to deploy it to one stage server (which use rvm) and one production server (which use ruby env)
By default everything works nice on production server, but without rvm1-capistrnao3 gem installed and included in Capefile I cannot deploy to staging.
Is there a way to require 'rvm1/capistrano3' in Capefile, only if I deploy to staging like that
cap staging deploy

A: Here is what I've done to fix it
I made default capistrano multistage setup, like Doug Hall said!
The tricky part is the way to include rvm1-capistrano3 in Capefile
See deepak's workaround here https://github.com/capistrano/rvm/issues/49
So instead of just require 'rvm1/capistrano3' in Capefile, do it like that
task :use_rvm do
  require 'rvm1/capistrano3'
end

task 'staging' => [:use_rvm]

A: When you run cap install, it creates a file called config/deploy.rb and two files in the config/deploy directory: production.rb and staging.rb. Use the config/deploy.rb file for all settings that both the production and staging servers have in common. Use the other two for the respective settings on those machines. I would require 'capistrano/rvm' in your Capfile, but only use it in the config/deploy/staging.rb file. Capistrano executes the common config/deploy.rb FIRST, then calls the proper staging.rb/production.rb file, so all set  values from config/deploy.rb are available in the staging.rb/production.rb file.


text: Q: How can I grab the HTTP(S) requests submitted by a Java app/applet? How can I grab the HTTP(S) requests submitted by a Java app/applet with a free/native Windows application? I tried pktmon but it seems it captures IPs rather than HTTP(S) requests. Unfortunately, I cannot use the Chrome/Edge web dev tools as the Java app/applet runs in a non-browser window.


text:
Q: connect to firefox with C# Sory for the title and the topic, I didn't really know where to put my question :) .
I'm looking for a way to automatically get the HTML source of an openned page in firefox so I can use it in a C# application. For example, I would browse a page in firefox. When I would like to get some data I would start my program and refresh the page in firefox. The program would get the HTML source and extract data.
Kinda like clicking the "show source" in firefox, using Ctrl+a and pasting the source into my C# application, but I want to automate this step.
I hope there is another way than to writing my own firefox extension, I never did that before and it would take long for me. Too long just to get the source.
I'm already using Greasemonkey, so I could write a script that automatically saves the source to a file from which my application could read the whole source. But that  wouldn't be effective.
Unless there is another way to connect to the firefox page via javascript, that won't work.
Ok, to put it short : which way is the best to automatically get the HTML source of an opened page in firefox to my C# application?
I'm gratefull for any answers :)

A: Does it have to be firefox? The IE browser functions integrate pretty well and easy with windows forms .NET applications. Is something like that a good idea for you? (check out the WebBroweser.Document property at http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.document(v=VS.85).aspx)


text:
Q: how to find all employees under each manager I need to get a query to display the subordinates all the way down starting from one specific manager. Let's say I have this structure and I need to get all employees starting from ManagerId = 1
EmployeeId  ManagerId
2           1
3           1
4           3
5           3
6           4

I need to get as result of the query the ManagerId and direct report employees under him, along with their subordinates.
For example, using SQL Server 2014:
CREATE TABLE #Pepe (EmployeeId INT, ManagerId int)

INSERT INTO [#Pepe] ( [EmployeeId], [ManagerId] ) VALUES  (2, 1)
INSERT INTO [#Pepe] ( [EmployeeId], [ManagerId] ) VALUES  (3, 1)
INSERT INTO [#Pepe] ( [EmployeeId], [ManagerId] ) VALUES  (4, 3)
INSERT INTO [#Pepe] ( [EmployeeId], [ManagerId] ) VALUES  (5, 3)
INSERT INTO [#Pepe] ( [EmployeeId], [ManagerId] ) VALUES  (6, 4)

Now I get the CTE
;WITH relation AS
    (
       SELECT 1 as EmployeeId,  0 AS LEVEL

       UNION ALL

       SELECT r.EmployeeId, LEVEL + 1 AS LEVEL
         FROM (SELECT EmployeeId, ManagerId FROM #Pepe) r
        INNER JOIN relation T
           ON r.ManagerId = T.EmployeeId
        WHERE r.ManagerId <> r.EmployeeId

    )

SELECT DISTINCT  EmployeeId, LEVEL FROM relation

The result of my CTE is this:
EmployeeId  LEVEL
1           0
2           1
3           1
4           2
5           2
6           3

This result start from one specific employee which is 1 (is hardcoded on the CTE), now I need only the direct report, Level = 1 and also Level 0 too which are employee id 1, 2 and 3.
This is fine, now what I need is for each employee id (level 0 and 1), I need to get this result:
EmployeeId  ManagerId
1           1
2           1
3           1
4           1
5           1
6           1
2           2
3           3
4           3
5           3
6           3

As you can see the Manager Id contains the employees with level 0 and 1, and for each one I basically call the CTE to get all employees down, like for example ManagerId = 2 doesn't have subordinates but I need to count it anyway. Is there an efficient way to do this? I was using cross apply putting the CTE in an inline function but I was having troubles with performance.

A: I guess I found a solution, I would like to have an opinion about it.
;WITH relation AS
    (
       SELECT 1 AS ManagerId, 1 as EmployeeId,  0 AS LEVEL UNION
       SELECT 2 AS ManagerId, 2 as EmployeeId,  0 AS LEVEL UNION
       SELECT 3 AS ManagerId, 3 as EmployeeId,  0 AS LEVEL

       UNION ALL

       SELECT t.[ManagerId], r.EmployeeId, LEVEL + 1 AS LEVEL
         FROM (SELECT EmployeeId, ManagerId FROM #Pepe) r
        INNER JOIN relation T
           ON r.ManagerId = T.EmployeeId
        WHERE r.ManagerId <> r.EmployeeId

    )

SELECT DISTINCT EmployeeId, [ManagerId] FROM relation ORDER BY 2

A: You pretty much had it.  Just needed to select the distinct managers from the #Pepe table instead of manually doing the 3 select statements
DECLARE @Pepe TABLE (EmployeeId INT, ManagerId int)

INSERT INTO @Pepe ( [EmployeeId], [ManagerId] ) VALUES  (1, 1)
INSERT INTO @Pepe ( [EmployeeId], [ManagerId] ) VALUES  (2, 1)
INSERT INTO @Pepe ( [EmployeeId], [ManagerId] ) VALUES  (3, 1)
INSERT INTO @Pepe ( [EmployeeId], [ManagerId] ) VALUES  (4, 3)
INSERT INTO @Pepe ( [EmployeeId], [ManagerId] ) VALUES  (5, 3)
INSERT INTO @Pepe ( [EmployeeId], [ManagerId] ) VALUES  (6, 4)

;WITH relation (ManagerId, EmployeeId, LEVEL)
AS
(
    SELECT DISTINCT ManagerId, ManagerId AS EmployeeId,  0 AS LEVEL
    FROM @Pepe

    UNION ALL

    SELECT t.[ManagerId], r.EmployeeId, LEVEL + 1 AS LEVEL
    FROM @Pepe r
      INNER JOIN relation T
        ON r.ManagerId = T.EmployeeId
    WHERE r.ManagerId <> r.EmployeeId
)
SELECT DISTINCT EmployeeId, ManagerId, LEVEL FROM relation ORDER BY ManagerId


text:
Q: sandboxing an existing OSX app I have an existing OSX app that supports OSX 10.5 onwards. I want to publish it to the AppStore and therefore I need to sandbox the app. I guess sandbox app should be supporing 10.7 onwards.

*

*The app uses a folder in the username directory to create temp files etc

*It also copies a sql db file which already has empty tables to the same temp folder and upates records as the app is used.

*Furthermore if there is a crash it picks up logs from the crashlog folder of osx and requests user to submit them to developer.

Question
with a sanbox app, where do I store temp files ?
Where should I place the db file which can be read/witten to + new App update should be able to find exsting db file.
Should the custom code for crash reporter be kept or be made redundant ?
Thanks

A:
where do I store temp files ?

In the directory recommended by NSTemporaryDirectory(). (This applies to both sandboxed and non-sandboxed applications.)

Where should I place the db file which can be read/witten to

In your application's Application Support directory. Use NSSearchPathForDirectoriesInDomains() to find it, then append your application's name. Again, this is the same whether you're sandboxed or not.

new App update should be able to find exsting db file.

Not possible. You can ask the user to locate the existing file with a NSOpenPanel, but you can't open it yourself, because it'd be outside your sandbox.

Should the custom code for crash reporter be kept or be made redundant ?

You'll need to remove it, because it won't work under sandboxing — crash reports are not stored to your sandbox. You will receive crash reports for your application through iTunes Connect.
Alternatively, you may want to look into a third-party crash reporting service like PLCrashReporter.

A: There is a mechanism to migrate the data of an existing App into the sandbox: Migrating an App to a Sandbox on developer.apple.com
This is done once the newly sandboxed app is launched the first time. If you can determine  where the database was stored, you can migrate it into the sandbox.


text:
Q: Failed to include Retrofit version > 2.6 in Project I try to include Retrofit with Gson converter in my project.
Without the changes in the gradle file, everything works. When I add the dependencies
 implementation 'com.squareup.retrofit2:retrofit:2.9.0'
 implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
 implementation 'com.google.code.gson:gson:2.8.6'

to my gradle file, the project still compiles and even installs the app, but it crashes with this error:
2020-07-10 21:14:02.261 9083-9083/com.testproject.app E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.testproject.app, PID: 9083
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.testproject.app/com.testproject.app.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.testproject.app.MainActivity" on path: DexPathList[[zip file "/data/app/com.testproject.app-Au1uLD6rtjGrZa2PoCEKZA==/base.apk"],nativeLibraryDirectories=[/data/app/com.testproject.app-Au1uLD6rtjGrZa2PoCEKZA==/lib/x86, /system/lib, /vendor/lib]]
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2718)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.testproject.app.MainActivity" on path: DexPathList[[zip file "/data/app/com.testproject.app-Au1uLD6rtjGrZa2PoCEKZA==/base.apk"],nativeLibraryDirectories=[/data/app/com.testproject.app-Au1uLD6rtjGrZa2PoCEKZA==/lib/x86, /system/lib, /vendor/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:93)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1173)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2708)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
        Suppressed: java.io.IOException: Failed to open dex files from /data/app/com.testproject.app-Au1uLD6rtjGrZa2PoCEKZA==/base.apk because: Failure to verify dex file '/data/app/com.testproject.app-Au1uLD6rtjGrZa2PoCEKZA==/base.apk': Bad method handle type 7
        at dalvik.system.DexFile.openDexFileNative(Native Method)
        at dalvik.system.DexFile.openDexFile(DexFile.java:353)
        at dalvik.system.DexFile.<init>(DexFile.java:100)
        at dalvik.system.DexFile.<init>(DexFile.java:74)
        at dalvik.system.DexPathList.loadDexFile(DexPathList.java:374)
        at dalvik.system.DexPathList.makeDexElements(DexPathList.java:337)
        at dalvik.system.DexPathList.<init>(DexPathList.java:157)
        at dalvik.system.BaseDexClassLoader.<init>(BaseDexClassLoader.java:65)
        at dalvik.system.PathClassLoader.<init>(PathClassLoader.java:64)
        at com.android.internal.os.PathClassLoaderFactory.createClassLoader(PathClassLoaderFactory.java:43)
        at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:69)
        at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:36)
        at android.app.LoadedApk.createOrUpdateClassLoaderLocked(LoadedApk.java:676)
        at android.app.LoadedApk.getClassLoader(LoadedApk.java:709)
        at android.app.LoadedApk.getResources(LoadedApk.java:936)
        at android.app.ContextImpl.createAppContext(ContextImpl.java:2242)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5672)
        at android.app.ActivityThread.-wrap1(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1661)
                ... 6 more

Edit:
Found out that it works with Retrofit 2.6.0, but not with greater versions.

A: You only need the Square GSON dependency - remove the GSON dependency from Google. Should read like this:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'


text:
Q: Derivative of log of multivariate Normal respect to Matrix? I am wondering how to calculate the gradient of a multivariate Normal respect to L where  $\Sigma=LL^{T}$. I know what would be the derivative respect to $\Sigma$ and I can use chain rule to get the derivative respect to L but since $\Sigma$ is a matrix and L is matrix then derivative of a matrix respect to matrix is 4D tensor.
Therefore I am wondering can anyone help to find the derivative of
log|L|$-(x-z)L^{-1}L^{-T}(x-z)^{T}$ respect to L. The first term involving the determinant is a standard calculation but I am stuck  in the second term.

A: In matrix calculus it is often easier to use differentials instead of the chain rule, since it avoids the need to calculate third and fourth order tensors.
Define the variables
$$A = LL^T,\quad y = x-z$$
Note that
$$A^T=A,\quad A^{-1} = L^{-T}L^{-1} $$
Write the cost function in terms of these new variables.
$$\eqalign{
\phi &= \log(\det(L)) + y^TA^{-1}y \\
}$$
Then calculate the differential and the gradient.
$$\eqalign{
d\phi &= d\log(\det(L)) + y^TdA^{-1}y  \\
&= d{\,\rm tr}(\log(L)) + {\rm tr}\big(y^TdA^{-1}y\big) \\
&= {\rm tr}\Big(d\log(L) - y^TA^{-1}dA\,A^{-1}y\Big) \\
&={\rm tr}\Big(L^{-1}dL-y^TA^{-1}dL\,L^TA^{-1}y-y^TA^{-1}L\,dL^T\,A^{-1}y\Big) \\
&={\rm tr}\Big(L^{-1}dL-2L^TA^{-1}yy^TA^{-1}dL\Big) \\
\frac{\partial \phi}{\partial L}
 &= L^{-1} - 2L^TA^{-1}yy^TA^{-1} \\
 &= L^{-1} - 2L^{-1}yy^TL^{-T}L^{-1} \\
}$$
Depending on your preferred layout convention, you may want the transpose of this result.


text:
Q: rails upgrade from 4.0.3 to 4.2.0 cannot load such file error I try to upgrade my rails app from 4.0.3 to 4.2.0, the bundle install command is successful, but when I start up server with "rails s", it reports the following error
activesupport-4.2.0/lib/active_support/dependencies.rb:274:in `require': cannot load such file -- raven/sidekiq (LoadError)

I suspect this error is related to 'sidekiq' gem which I used to queue background job or 'sentry-raven' gem which is used by heroku addon to send any system error.
I tried to remove these 2 suspicious gems, but it didn't work.
How could I solve this?

A: Seems like you use sidekiq monitoring. Do determine it, open routes.rb, and found here something like
require 'sidekiq/web'
mount Sidekiq::Web => '/sidekiq'

Related to this issue, you need to add sinatra gem to your Gemfile.
e.g.
gem 'sinatra', require: nil

A: I also encountered this error after my sentry-raven gem got upgraded from 0.6.x to 0.13.x when I did a bundle upgrade.
I bypassed this error by removing the require 'raven/sidekiq' line in my config/initializers/raven.rb and have rails s command run successfully.
I followed the document of sentry-raven to add the require 'raven/sidekiq' in my initializer files when I was working with its version 0.6.0. Now for version 0.13.x it seems not needed any longer.
Hope this helps.


text:
Q: Higher-order corrections for Euler's method I would like to preface my question by confessing that I come from a Physics background, so I apologize for any abuse of notation.
Given a 1st order ODE
$$ y' = f(x, y) $$
we can use Euler's Method to find an approximate solution:
$$ y_{n+1} = y_n + f(x_n, y_n) \,dx $$
Assuming both $f$ and $y$ are both analytic, if locally
$$ y = y_0 +y'_0 dx + \frac12y''_0(dx)^2 + \cdots +\frac{1}{n!}y^{(n)}_0(dx)^n + \cdots$$
and since
$$ y'' = \frac{d}{dx}f(x, y) = \frac{\partial f}{\partial y}y' + \frac{\partial f}{\partial x} $$
could one better approximate a solution to the ODE by adding a second order correction to Euler's Method of the form:
$$ y_{n+1} = y_n +y'_n * dx + \frac12y''_n(dx)^2 = y_n +f(x_n,y_n)dx + \frac12[\frac{\partial f}{\partial y}(x_n,y_n)*f(x_n,y_n) + \frac{\partial f}{\partial x}(x_n,y_n)](dx)^2 $$
and generally, could Euler's method provide even better approximations if correction terms of higher order are added (assuming we can easily determine the partial derivatives of $f$)?

A: Yes, one can do that, this is called the Taylor series method. Most efficiently you do this with methods of algorithmic differentiation, that is, you capture the right side as computational graph, equip each node with space for the Taylor series coefficients of that node, and populate these coefficients with increasing degree. Straight evaluation gives $y'$, augmenting the input by the linear term allows to augment all nodes, giving $y''$ in the end, then augment the input to a quadratic polynomial etc.
One rather old package that does this efficiently is the TADIFF part of the FADBAD, now both FADBAD++ package with applications to certified error bounds of ODE solutions
Local examples for the Taylor series method are https://math.stackexchange.com/a/2953714/115115 and https://math.stackexchange.com/a/3663073/115115, while https://math.stackexchange.com/a/2499684/115115 explores the Taylor arithmetic aspect of a simple example.

More frequently you will encounter the first derivative of the ODE function, as part of a Newton-like method in implicit methods, in determining the split in splitting methods, which leads to Rosenbrock and similar methods. The latter can be seen as an amalgamation of the Taylor series and Runge-Kutta approaches.

A: If we have information on higher order derivatives, then it is certainly possible to get higher order approximations as you have shown. However, this is usually not the case in practice and so methods like Euler's are developed in the spirit of approximating $y$ with as little knowledge as possible.
I think that this post is also worth looking at, where someone describes how Richardson's extrapolation could be used to achieve a more accurate version of Euler's method while still only requiring knowledge of $y'$.


text:
Q: List displayed as 2 columns I have a dynamic List (asp .net collection) of Data that I need to display on a aspx page. I want the data in two columns filling up from left to right depending on the number of items on the list. WHat webcontrol would be the best to use in this case?

A: You can use DataList, Repeater or GridView. It's really a matter of which features do you need to support (sorting,filtering, paging, etc.) besides your layout requirements (all of the above can do what you need).
GridView and Repeater are a bit heavier but provide easy hooks for implementing more advanced features.
UPDATE
Example:
<asp:DataList runat="server" id="dltest"
                Border="1"
                Font-Name="Verdana" CellPadding="4"
                Font-Size="10pt"
                RepeatColumns="2" >
   <ItemTemplate>

              <%# DataBinder.Eval(Container.DataItem, "Description") %>

              <%# DataBinder.Eval(Container.DataItem, "Value") %>

   </ItemTemplate>
</asp:DataList>

Note: Modified to your needs but this should get you started.

A: A repeater would work in this situation and allow you alot of flexibility to style it.
CSS
.container{margin:0; width:300px;}
.item{float:left;width:150px;height:30px;}
.clear{clear:both;width:100%; height:1px;}

ASPX

    <asp:Repeater ID="rptTest" runat="server">
    <ItemTemplate>

<%#Eval("DataColumn") %>

    </ItemTemplate>
    </asp:Repeater>

Eval("DataColumn") would represent the name of the table column you wanted to display, and you can set the datasource for the repeater either in the codebehind or using one of the drag and drop datasource controls.
The CSS will make the data appear as 2 columns going left to right thanks to the "float:left". The container is 300px wide, and the items are going to be 150px each which should give it the two column appearance.


text:
Q: Redux + React understanding size of webpack bundle I read various answers like this regarding reducing the bundle size. First I wanted to understand what is going on with my 13MB bundle, so I've installed the Webpack Bundle Size Analyzer. It generated this output:

There are a few things I don't understand:

*

*Why is react appearing twice with two different sizes?

*How come it doesn't add up to 13MB? (it's around 4.75MB)

*Does this means my own code is only 4KB? (last line)

*Is it possible to understand from this tree how to save KBs? I mean, for instance, is there a way to use only parts of lodash or is it required as a whole by React?

Update:
Found the answer for #1. React-color requires ReactCSS which requires a different version of react and lodash. Without React-color my bundle dropped from 13MB to 8MB. I will try to find a way to re-use react and lodash.

A: It seems that you have eval-source-map devtool option in your webpack config file, that's why you are getting such huge bundle size. This way, sourcemaps are putting inside of bundle js file.
Try to change this option to source-map to build source maps separately.
// webpack.config.js
{
  devtool: 'source-map',
  // ... other options
}

A: 1) Sometimes other dependencies require again lodash and / or react, so these dependencies are pulled in multiple times by webpack (usually happens when the version differs), here the DedupePlugin should help. The final bundle size also depends on your devtool entry in webpack, so in development it is usually much bigger as you probably have sourcemaps enabled and a your build is not optimized. Hard to tell without your actual webpack config.
2) Maybe webpack is already deduping?
3) last line says 400KB
4) You can definitely save a few kbs. A good way to start is using lodash-webpack-plugin with babel-plugin-lodash, this will import only the lodash methods you are actually using instead of the complete library. You can also just require the bits you need from material-ui as outlined in this answer.
I recently added the webpack-dashboard to my webpack config, so I instantly see the output and percentages that make up my bundle size, so maybe you think twice about adding huge dependencies if you don't really need them.


text:
Q: COUNT(*) inaccurate on linked server query I am running a query over a linked server in SQL Server to Oracle using the OraOLEDB.Oracle provider.
When I run this query, I get a data set of 11,990 rows:
SELECT *
FROM OPENQUERY([ORA_LINK], 'SELECT * FROM DB1.MY_TABLE');

However, this COUNT(*) query returns a value of 200, not 11,990:
SELECT COUNT(*)
FROM OPENQUERY([ORA_LINK], 'SELECT * FROM DB1.MY_TABLE');

Is there something in the linked server or provider settings limiting this?
UPDATE: If I access the table directly, I get the correct count:
SELECT COUNT(*)
FROM [ORA_LINK]..[DB1].[MY_TABLE]

So seems the issue is with the usage of OPENQUERY.

A: My guess it is related with default fetchsize

FetchSize - specifies the number of rows the provider will fetch at a time (fetch array). It must be set on the basis of data size and the response time of the network. If the value is set too high, then this could result in more wait time during the execution of the query. If the value is set too low, then this could result in many more round trips to the database. Valid values are 1 to 429,496, and 296. The default is 100.

1 Materialzing it on SQL Server side
SELECT *
INTO #tmp
FROM OPENQUERY([ORA_LINK], 'SELECT * FROM MY_TABLE');

SELECT COUNT(*) FROM #tmp;

2 Runing COUNT(*) or Oracle side;
SELECT *
FROM OPENQUERY([ORA_LINK], 'SELECT COUNT(*) FROM MY_TABLE');


text:
Q: Native OpenGL ES code runs on emulator but it doesn't run on real device I'm programming an OpenGL ES 1.1 app on Android (all OpenGL ES code is C++).
Testing it on emulator it works fine, but when I test it on a real device (HTC Desire), it doesn't work (I only see a black screen).
This is my OpenGL C++ code:
RenderingEngine1::RenderingEngine1()
{
    // Create & bind the color buffer so that the caller can allocate its space.
    glGenRenderbuffersOES(1, &m_renderbuffer);
    glBindRenderbufferOES(GL_RENDERBUFFER_OES, m_renderbuffer);
}

void RenderingEngine1::Initialize(int width, int height)
{
    // Create the framebuffer object and attach the color buffer.
    glGenFramebuffersOES(1, &m_framebuffer);
    glBindFramebufferOES(GL_FRAMEBUFFER_OES, m_framebuffer);
    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES,
                                 GL_COLOR_ATTACHMENT0_OES,
                                 GL_RENDERBUFFER_OES,
                                 m_renderbuffer);

    glViewport(0, 0, width, height);

    glMatrixMode(GL_PROJECTION);

    // Initialize the projection matrix.
    const float maxX = 2;
    const float maxY = 3;
    glOrthof(-maxX, +maxX, -maxY, +maxY, -1, 1);

    glMatrixMode(GL_MODELVIEW);

    // Initialize the rotation animation state.
    OnRotate(DeviceOrientationPortrait);
    m_currentAngle = m_desiredAngle;
}

void RenderingEngine1::Render() const
{
    glClearColor(0.5f, 0.5f, 0.5f, 1);
    glClear(GL_COLOR_BUFFER_BIT);
    glPushMatrix();
    glRotatef(m_currentAngle, 0, 0, 1);
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);

    glVertexPointer(2, GL_FLOAT, sizeof(Vertex), &Vertices[0].Position[0]);
    glColorPointer(4, GL_FLOAT, sizeof(Vertex), &Vertices[0].Color[0]);

    GLsizei vertexCount = sizeof(Vertices) / sizeof(Vertex);
    glDrawArrays(GL_TRIANGLES, 0, vertexCount);

    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_COLOR_ARRAY);
    glPopMatrix();
}

JNI methods are in this C++ code:
extern "C" {
    IRenderingEngine* m_renderingEngine;

    JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
    {
        return JNI_VERSION_1_4;
    }

    void Java_com_company_tests_MainRenderer_nativeInit( JNIEnv*  env, jobject thiz )
    {
        m_renderingEngine = CreateRenderer1();
        m_renderingEngine->Initialize(480, 800);
    }

    void Java_com_company_tests_MainRenderer_nativeRender( JNIEnv*  env, jobject thiz )
    {
        m_renderingEngine->Render();
    }
}

And I also have two Java classes: one that inherits from GLSurfaceView, and a renderer that implements GLSurfaceView.Renderer.
I don't know why it doesn't work on a real device.
Any advice?
If you need something else, please tell me.


text:
Q: jQuery - Extraer los últimos 3 caracteres de un texto Tengo el siguiente texto: "Hola mundo", y quisiera extraer los 3 últimos es decir que quedase: "Hola mu". ¿Qué fallo tengo?
Código:
    $("#quitar_3caracteres").click(function() {
    //Obtenemos primero el texto completo para analizarlo.
    var texto = $(".quintoparrafo").text();
    console.log(texto);
    console.log(texto.length); //296
    var texto_nuevo = texto.substr(0,texto.length-3);
    console.log(texto_nuevo);
    console.log(texto_nuevo.length); //293
    $(".quintoparrafo").text(texto_nuevo);
});

¿Por qué me varia la longitud de 296 a 296 si el texto sigue siendo el mismo palabra a palabra, letra a letra, espacio a espacio...?
He escrito en mi código (actualizado) console.log para verlo más claro pero no hace nada, me quite 3 caracteres en la longitud total pero el texto sigue siendo el mismo.

A: Tienes que obtener primero el texto de .tercerparrafo y luego cambiar los limites del substr que tendría que ser 0 y length - 3;
Por ejemplo:
$("#quitar_3caracteres").click(function() {
   var str = $(".tercerparrafo").text();
   alert(str.substr(0, str.length-3));
});


text:
Q: Refinement to previous question: is the conjecture true or false in the affine case? This question is a follow-up to this other question. There I asked to prove or disprove the conjecture stated at the end. What I want to ask here now is a refinement of this conjecture. For this reason, I advice to first familiarize yourself with the conjecture from the linked post.
As you can see, on my first question Mohan answered providing a counterexample that seems to have quasi-affine (and presumably not affine) domain. Here is now the refinement: If we further assume the domain to be affine, is the conjecture true or false?
Note that here a possible negative answer may be a proof that the quasi-affine variety $X$ from Mohan's answer is actually affine (although I think this may not be the case).
(The terms "affine" and "quasi-affine" are defined with precision on my first question.)


text:
Q: What is the easiest way to hint localizations while typing? I think I could use MultiAutoCompleteTextView to show hints. But how can I get some hints from Geocode API while typing it (e.g. where there are at least 3 letters typed)
Any idea?

A: On Android you can use Places API for Android.
Please look at this web site:
https://developers.google.com/places/android-api/
Places API for Android provides Place autocomplete and Place picker.


text:
Q: plex media server : how can i desable (by default) all options available on "Settings" -> "Online Media Sources"? i installed plex media server using docker, and added my local library having videos.
I would like ALL my users can ONLY access to my local libraries AND NOT other options like music, ...
i found where can do that using Settings -> Online Media Sources but the user can always re-enable those options
My question: how can i desabale Settings -> Online Media Sources 's options BY DEFAULT ? and deny the access to those options for all my users ?
Thank you in advance!


text:
Q: SIP Client - JsSIP login issue in my server I am creating an web application. In which I have to integrate the text, voice and video chat via SIP server. So that I have chosen the "JsSIP" from http://tryit.jssip.net/. I am trying to chat in the demo screen. It is working good. So I downloaded the code and put into my apache server.
Now I am open the login screen and trying to login. But it throws the following error.
WS connection error:
- WS close code: 1006
- WS close reason:

Can anyone tell me what may be the problem and how to fix it?


text:
Q: No current context I used a debugger in NetBeans and made a watch for a certain boolean variable. At a breakpoint it said that that variable had "No current context (stack frame) <" I'm just wondering what that exactly means.

A: Simple answer : The debugger simply tells you that it can't evaluate your variable because your boolean variable is not in the memory at your breakpoint.
Regards.


text:
Q: PHP: Getting MYSQLI_CLIENT_COMPRESS to work I can connect to my database with mysqli.  But when I add the MYSQL_CLIENT_COMPRESS flag it does not connect.
I'm using PHP 7.0.10, MySQL 5.7.14, and a WAMP installation on Windows 8.1.
I've been using:
$db=mysqli_connect($sHost, $sUsername, $sPassword, $sDatabase, MYSQLI_CLIENT_COMPRESS);

I get the following connection error

Debugging errno: 2002
  Debugging error: No connection could be made
  because the target machine actively refused it.

A: This works:
$db = mysqli_init();
$db->real_connect($sHost, $sUsername, $sPassword, $sDatabase, 0, '',  MYSQLI_CLIENT_COMPRESS);

This also works:
global $db;
$db=new mysqli($sHost, $sUsername, $sPassword, $sDatabase, 0, '', MYSQLI_CLIENT_COMPRESS);


text:
Q: Conference Calling in Pjsua android How to implement Conference calling with pjsip android?
I can put my current call on hold and un-hold it successfully. Anybody pls do help with conferencing. It seemed to be a tough nut for me. I know, we can start transmitting various ports using startTransmit() in Audio Media. But, firstly, how to initiate a conference call? anybody pls help.

A: In your code in the handleMediaStateChange of the class that extends Call, look for this line (or something similar)
remoteAudio = AudioMedia.typecastFromMedia(media);
remoteAudio.startTransmit(audDevManager.getCaptureDevMedia());

Make sure that remoteAudio is a class variable and not a local variable.
Configure both calls as if they were single calls. The behavior now should be that you can hear both parties, both parties can hear you, but the 2 parties can't hear each other. To fix this add the following code.
call1.remoteAudio.startTransmit(call2.remoteAudio);
call2.remoteAudio.startTransmit(call1.remoteAudio);

A: Unfortunately, you can't Conference calls using PJSIP Android according to their documentation. See What is missing section.
You can contribute as it is open source.


text:
Q: Query about Java Heap space String Object Storage I know that
String s1 = "test";
String s2 = new String("test");
System.out.println(s1==s2);  // false

in above snippet "test" String Object is created inside the String pool in java (s1 will be passed its reference)
and a new String Object will be created in the heap space of the memory (s2 will be in heap sapce).
so will s2 String object be referring to the String pool's "test" String object internally or s2 keeps an altogether different "test" String Object in memory ?
what will be the effect if we somehow "test" String Object in String constant pool is removed ? will s2 still be having the value "test" ?
I know this topic has been touched a lot but none of the previous answers which i checked clarifies it.
please mention any sources if that has a better explanation.
Thanks in advance !

A: In the Java 8 source code, the String(String) constructor reuses the value field from the parameter.
Note that value is a char[], though, so the two string instances use the same underlying array, but s2 is not using the "test" itself internally, since that is a String, not a char[].

A: Here is the link to the Article by Corey McGlone
http://www.javaranch.com/journal/200409/Journal200409.jsp#a1