text:
Q: Android CookieManager fails to refresh cookies Curently in my Android app, I am using CookieManager and CookieSyncManager.
What I notice is that, the cookie is not updated properly.
For example:
Android ----> Server: No cookie
Server  ----> Android: Cookie C1
Android ----> Server: Cookie C1 (Correct)
Server  ----> Android: Cookie C2
Android ----> Server: Cookie C1 C2 (Incorrect)

Because of the 2 cookies returned, server side rejected the transaction.
I have tried to force sync, but the issue still persists.
I even tried to add some sleep, but it did not help either.
Any suggestion on what else I can try?
Thank a lot.
Regards
Andrew
cookieManager = CookieManager.getInstance();

cookieInput = cookieManager.getCookie(Constants.HOST_URL);

write("Cookie from CookieManager 4:" + cookieInput);

cookieManager.removeAllCookie();

//SystemClock.sleep(2000);

cookieManager = CookieManager.getInstance();

cookieInput = cookieManager.getCookie(Constants.HOST_URL);

write("Cookie from CookieManager 5:" + cookieInput);

cookieManager.removeSessionCookie();

cookieManager.removeAllCookie();

//SystemClock.sleep(2000);

//CookieSyncManager.getInstance().sync();

cookieManager.setCookie(Constants.HOST_URL, cookieString);

cookieManager.setCookie(Constants.HOST_URL, cookieString1);

cookieManager.setCookie(Constants.HOST_URL, cookieString2);

//SystemClock.sleep(5000);

cookieManager = CookieManager.getInstance();

cookieInput = cookieManager.getCookie(Constants.HOST_URL);

write("Cookie from CookieManager 6:" + cookieInput);

CookieSyncManager.getInstance().sync();

//SystemClock.sleep(30000);


text:
Q: Inserting data to the database Can someone please tell me how to fix this. I have the html form coded right with the php file coded for the insert to database. I need help because when i click on the submit button it doesn't do anything. I need it to submit the information to the database and reset itself for the new person to fill it out.
Html:

        <title></title>

        <link rel="stylesheet" href="css/contact_form.css" />

                <form id="form" action="insert.php" method="post">

Contact Form

                                Name: *

                <input type="text" id="name" name="name" placeholder="Name"/>

                Email: *

                <input type="text" id="email" name="email" placeholder="Email"/>

                Contact No: *

                                <input type="text" id="contact" name="contact" placeholder="Ex.0002223333"/>

                Message:

                                <textarea id="message" name="message" placeholder="Message......."></textarea>

                <input type="button" id="submit" value="Send Message"/>

                </form>

PHP
<?php

$user = "xxxx";
$password = "xxxx";
$host = "xxxx";
$dbase = "xxxx";
$table = "xxxx";

$name= $_POST['name'];
$email= $_POST['email'];
$contact= $_POST['contact'];
$message= $_POST['message'];

$dbc= mysqli_connect($host,$user,$password, $dbase)
or die("Unable to select database");

$query= "INSERT INTO $table  ". "VALUES ('$name', '$email', '$contact', '$message')";

mysqli_query ($dbc, $query)
or die ("Error querying database");

echo 'Your Contact has been added.
 Thanks for sharing you information with us.
Sincerely,
 xxx' . '
';

mysqli_close($dbc);

?>

A: Found the problem. Here was the issue
$query= "INSERT INTO $table  ". "VALUES ('$name', '$email', '$contact', '$message')";

The fix
$query= "INSERT INTO $table  ". "VALUES ('', '$name', '$email', '$contact', '$message')";

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating a 'typed' effect with keyframes inside a table cell Using keyframes animation I'm trying to create a 'typewriter' affect, whereby a word slowly appears left to right as if typed.  For some reason, this works well within a
 or
, but not in a table cell.  Outside the cell, the animation works correctly, 'typing' slowly left to right.  Inside a table cell, however, the whole word appears all at once.  In my search for a solution, I added a font color change to the keyframe.  Here, oddly enough, the font changes color slowly in both cases, as it should.  Can someone tell me why the same code works outside a cell but not inside?  I'm stumped. Thanks for any help.
Here's the code:

.typing {
  text-align: left;
  white-space: nowrap;
  overflow: hidden;
  padding: 6px;
  opacity: 0;
}
.typewriter-ani {
  animation: typewriter;
  animation-duration: 2s;
  animation-timing-function: steps(8);
  animation-direction: normal;
  animation-fill-mode: forwards;
}
@keyframes typewriter {
  0% {
    width: 0;
    opacity: 0;
  }
  1% {
    opacity: 1;
    color: blue;
  }
  100% {
    width: 60px;
    opacity: 1;
    color: red;
  }
}

Welcome!

    Welcome!
    Welcome!

    Welcome!
    Welcome!

A: Modern browsers by default will assign the td element a display attribute of table cell.
display: table-cell;

Your code doesn't work because display is defaulting to table-cell. This value is supposed to take the entirety of the space so that it might cover all the relative coordinates of the grid. To understand the how browsers render tables you can check out: https://www.w3.org/TR/2012/WD-html5-20121025/single-page.html#concept-cell
One easy solution is to assign the table cells a new display value.
td {
       display: inline-block;
   }

I added display: inline-block to over ride the default user agent stylesheet.
JS-Fiddle: https://jsfiddle.net/jamesvan/v6wq5qhb/

A: It appears it has something to do with the width rule in the animation. My guess is table cells just don't operate in the same way as block level elements when it comes to overflow: hidden and adjusting the width to smaller than its contents.
You can get around this by wrapping whatever element you want to appear "typed" in a block level element within the table cell and applying styles to that instead.

.typing {
  text-align: left;
  white-space: nowrap;
  overflow: hidden;
  padding: 6px;
  opacity: 0;
}
.typewriter-ani {
  margin: 0;

  animation: typewriter;
  animation-duration: 2s;
  animation-timing-function: steps(8);
  animation-direction: normal;
  animation-fill-mode: forwards;
}
@keyframes typewriter {
  0% {
    width: 0;
    opacity: 0;
  }
  1% {
    opacity: 1;
    color: blue;
  }
  100% {
    width: 60px;
    opacity: 1;
    color: red;
  }
}

Welcome!

Welcome!

        Welcome!

        Welcome!
        Welcome!


text:
Q: Import-CSV GroupBy Sum I am stuck trying to get meaningful output from a csv file.
The raw input looks like this.
Col1,Col2,Col3,Col4
a,2,b,z
a,2,c,x
a,1,d,y
e,1,f,s
e,2,g,t
h,1,k,r

I am trying to achieve an output of below (exclude col4) and export to a file for further reporting using PowerShell 2.
a  5  b,c,d
e  3  f,g
h  1  k

Code from my script function is:

    $data = import-csv $filename.csv | Select-Object -property Col1,Col2,Col3
    $view | Group Col1 | `
    select Name,@{
      Name="Col2Sum";
       Expression = {
         [math]::round(($_.Group | Measure-Object -Sum Col2).Sum/60,2)
       }
      } | `
    Sort "Col2Sum" -desc | ft -auto -GroupBy Col | out-file $file.txt

Where I am stuck is how to produce arrays from Col3 in one line and output them properly.
If anyone has any ideas.

A: Can you try this :
    $a = import-csv C:\temp\F.csv |Group-Object -Property col1 | `
         % {$_.name + " "  + $_.count + " " + `
         ($_.group | % {$i=0;$j=$_.count}{$i++ ; $_.col3 + ","*($j-$i -gt 0)})}
    $a

a 3 b, c, d
e 2 f, g
h 1 k

And then
    $a = import-csv C:\temp\F.csv |Group-Object -Property col1 | `
         % {$_.name + " "  + ($_.group | %{$i=0}{$i+=$_.col2}{$i}) + " " + `
         ($_.group | % {$i=0;$j=$_.count}{$i++ ; $_.col3 + ","*($j-$i -gt 0)})}
    $a

a 5 b, c, d
e 3 f, g
h 1 k


text:
Q: why step() returns weird results from backward elimination for full model using lmerTest I am confused that why the results from processing step(model) in lmerTest are abnormal.
m0 <- lmer(seed ~ connection*age + (1|unit), data = test)

step(m0)

note: Both "connection" and "age" have been set as.factor()

 Random effects:
      Chi.sq Chi.DF elim.num p.value
 unit   0.25      1        1  0.6194

 Fixed effects:
 Analysis of Variance Table

 Response: y
                Df  Sum Sq  Mean Sq F value  Pr(>F)
 connection      1 0.01746 0.017457  1.5214 0.22142
 age             1 0.07664 0.076643  6.6794 0.01178 *
 connection:age  1 0.04397 0.043967  3.8317 0.05417 .
 Residuals      72 0.82617 0.011475
 ---
 Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

 Least squares means:
      Estimate Standard Error DF t-value Lower CI Upper CI p-value

 Final model:

 Call:
 lm(formula = fo, data = mm, contrasts = l.lmerTest.private.contrast)

 Coefficients:
      (Intercept)       connectionD              ageB  connectionD:ageB
         -0.84868          -0.07852           0.01281           0.09634

Why it does not show me the Final model?

A: The thing here is that random effect was eliminated as being NS according to the LR test. Then the anova method for the fixed effects model, the "lm" object was applied and no elimination of NS fixed effects was done. You are right, that the output is different from "lmer" objects and there are no (differences of ) least squares means. If you want to get  the latter you may try the lsmeans package. For the backward elimination of NS effect of the final model you may use stats::step function.


text:
Q: Storage account access for 3rd party Azure we are trying to set up a storage account where a third party company can come and programmatically collect updated files, we upload a new file, then the company gets an email notification but we are stuck where the company needs a sas token, that's fine but it's per blob, does anyone know how we can set up access to storage account for third party for them to programmatically collect the latest files in a secure mannner?
Thanks in advance :)

A: If you want to give access at the container level, specify "container" as the allowed resource type.


text:
Q: Confused about Failed Facebook app review for user_friends permission We've submitted our app for review to get the Facebook user_friends permission. Our review was rejected with the following comments :

While use case and screencast are approvable we could not reproduce
  the permission due to errors on loading the app.

We've tested our app on PC, Android Studio and Android, no error on loading the app was found.

Your app had errors that prevented us from fully testing it.
  Please ensure that the APK provided is working correctly when run on
  Android 6.0 (Marshmallow) or higher, as this is the version of Android
  our team uses in review.

Inside Unity, we've set the "Minimum API Level" to Android 6.0, we've tested it in Android studio with Android 6.0, no error and everything works fine. We still got the same reply from the second Facebook review.

Notes From Your Reviewer:
  I've attached some screenshots that may help you understand my response
  better. You can find them here: https://imgur.com/ENDW35G

We do not understand how this image could be helping us in any way.
Yes it looks like a ZIP of the APK we've provided, but why should this help us ?
We're just very confused with their review.

"Confused about your review feedback? Ask a question"

We've tried that, no reply from them
Our app is built in Unity3d with the "Minimum API Level" set to Android 6.0.
We've also tried setting the "Target API Level" to Android 6.0 but we're getting this error :

CommandInvokationFailure: Gradle build failed.
  C:\Program Files\Unity\Hub\Editor\2018.3.8f1\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\OpenJDK\Windows\bin\java.exe -classpath "C:\Program Files\Unity\Hub\Editor\2018.3.8f1\Editor\Data\PlaybackEngines\AndroidPlayer\Tools\gradle\lib\gradle-launcher-4.6.jar" org.gradle.launcher.GradleMain "-Dorg.gradle.jvmargs=-Xmx4096m" "assembleRelease"
stderr[
FAILURE: Build failed with an exception.

*

*What went wrong:
  Execution failed for task ':processReleaseResources'.

Android resource linking failed
    Output:  error: resource android:style/TextAppearance.Material.Widget.Button.Borderless.Colored not found.
    error: resource android:style/TextAppearance.Material.Widget.Button.Colored not found.
    error: failed linking references.

Could anyone help us understand their comment and what's the problem with our app ?
Thanks in advance.

A: Facebook finally replied with a new comment, explaining that they were not able to open the ZIP file of the app.
So after few more tries, uploading the .apk (not zipped) finally worked (the upload took about 5 to 10 min) and Facebook reviewed our app within the hour.
A direct dropbox link to the APK and a zipped APK did not work for us.


text:
Q: WOL remote Windows pc's at startup I have five Windows 8.1 pc's all connected together to the same local network.
I'd like to automatically switch on my 4 slaves when I power on my Master pc.
All the machines are properly set up to use Wake On LAN features and I was able to turn them on individually using the PowerOn.exe I found here http://www.codeproject.com/Articles/11469/Wake-On-LAN-WOL
Unfortunately this is not good enough because I want my Master pc to run a script at startup and wake up all the other pc's. I didn't find any suitable script on the internet and I would be glad if someone could show me the correct way to achieve this goal.

A: Some WOL softwares have a command line feature, like this one: http://www.depicus.com/wake-on-lan/wake-on-lan-cmd.aspx
Then you'll just need to write a batch file that launch a command and make this batch run on startup.

A: This can be accomplished using a PowerShell script.  It utilizes a CSV file to list the names of the machines to start.  Make sure to use version 1.1 of the script.


text:
Q: codility MaxDistanceMonotonic, what's wrong with my solution Question:
A non-empty zero-indexed array A consisting of N integers is given.
A monotonic pair is a pair of integers (P, Q), such that 0 ≤ P ≤ Q < N and A[P] ≤ A[Q].
The goal is to find the monotonic pair whose indices are the furthest apart. More precisely, we should maximize the value Q − P. It is sufficient to find only the distance.
For example, consider array A such that:
A[0] = 5
A[1] = 3
A[2] = 6
A[3] = 3
A[4] = 4
A[5] = 2

There are eleven monotonic pairs: (0,0), (0, 2), (1, 1), (1, 2), (1, 3), (1, 4), (2, 2), (3, 3), (3, 4), (4, 4), (5, 5). The biggest distance is 3, in the pair (1, 4).
Write a function:
int solution(vector &A);
that, given a non-empty zero-indexed array A of N integers, returns the biggest distance within any of the monotonic pairs.
For example, given:
A[0] = 5
A[1] = 3
A[2] = 6
A[3] = 3
A[4] = 4
A[5] = 2

the function should return 3, as explained above.
Assume that:
N is an integer within the range [1..300,000];
each element of array A is an integer within the range [−1,000,000,000..1,000,000,000].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
Here is my solution of MaxDistanceMonotonic:
    int solution(vector<int> &A) {

    long int result;

    long int max = A.size() - 1;
    long int min = 0;

    while(A.at(max) < A.at(min)){
        max--;
        min++;
    }

    result = max - min;

    while(max < (long int)A.size()){
        while(min >= 0){
            if(A.at(max) >= A.at(min) && max - min > result){
                result = max - min;
            }
        min--;
        }
    max++;
    }

    return result;
}

And my result is like this, what's wrong with my answer for the last test:

A: If you have:
0  1 2  3  4  5
31 2 10 11 12 30

Your algorithm outputs 3, but the correct answer is 4 = 5 - 1.
This happens because your min goes to -1 on the first full run of the inner while loop, so the pair (1, 5) will never have the chance to get checked, max starting out at 4 when entering the nested whiles.
Note that the problem description expects O(n) extra storage, while you use O(1). I don't think it's possible to solve the problem with O(1) extra storage and O(n) time.
I suggest you rethink your approach. If you give up, there is an official solution here.


text:
Q: tenses agreement on reported speech
'Do you understand the instructions?'

What is the proper reported speech for the above mentioned sentence?

The teacher asked us if we understand the instructions.

vs

The teacher asked us if we understood the instructions.

A:
The teacher asked us if we understood the instructions.

This is correct. While converting to reported speech, we must backshift the entire sentence. We can't backshift just one part of it.
"The teacher asked" has backshifted the sentence by one tense. So the remaining part of the sentence must also be backshifted into past tense.
Thus "understand" is wrong.
This of similar to :

I ate breakfast at 9

Becomes

He said that he had eaten his breakfast at 9

Since the original sentence is already in past tense, we convert it to past perfect.
"He said that he ate his breakfast at 9" wouldn't be fully correct
You can read about backshifting here :
https://www.englishgrammar.org/reported-speech-backshifting/


text:
Q: Inserting , updating and deleting of Data I want to make a control that show list of bounded data like in grid view but I want to be able to insert new record from the same control
what is the best asp.net control I can use to do that (GridView , FormView or DetailsView)? and why?
Thanks in Advance

A: You can do that with all three.  If you want to know how, there are some good tutorials on the official ASP.NET website, here.
The choice between them is a formatting/layout decision.  A GridView produces a table, showing multiple records, while a DetailsView shows one at a time.  A FormView lets you display the data however you want, but required much more effort, since you have to provide the HTML.


text:
Q: Fourier transform of $\frac{2\sin(x)}{1+x^2}$ I'm trying to calculate FT of $$f(x)=\frac{2\sin(x)}{1+x^2}$$
First of all we have
$$
\int_{-\infty}^{+\infty}\left|\frac{2\sin(x)}{1+x^2}\right| \, dx\leq 2\int_{-\infty}^{+\infty}\frac{1}{1+x^2} \, dx=2\pi
$$
thus $\mathcal{F}(f)$ is well defined. Now let's compute $\mathcal{F}(f)(\xi)$:
$$\mathcal{F}(f)(\xi)=2\int_{-\infty}^{+\infty}\frac{\sin(x)e^{-2\pi i x\xi}}{1+x^2} \, dx = \left[\sin(x)=\frac{e^{ix}-e^{-ix}}{2i}\right]=\\=-i\int_{-\infty}^{+\infty} \frac{e^{-2\pi ix\xi + ix}-e^{-2\pi ix\xi -ix}}{1+x^2}\, dx$$
Now I'm not sure how to proceed further. Any help?

A: This can be solved using the convolution theorem.
You should first verify for yourself that
$$\mathcal{F}^{-1}\left\{2\pi e^{-|2\pi\xi|}\right\} = \dfrac{2}{1+x^2}$$
and that
$$\mathcal{F}\left\{\sin(x)\right\} = \dfrac{i}{2}\delta\left(\xi + \dfrac1{2\pi}\right)-\dfrac{i}{2}\delta\left(\xi - \dfrac1{2\pi}\right)$$
By the convolution theorem
$$\begin{align}\mathcal{F}\left\{\dfrac{2}{1+x^2} \cdot \sin(x)\right\} &= \mathcal{F}\left\{\dfrac{2}{1+x^2} \right\} * \mathcal{F}\left\{\sin(x)\right\} \\
\\
&= 2\pi e^{-|2\pi\xi|} \space * \space \left[\dfrac{i}{2}\delta\left(\xi + \dfrac1{2\pi}\right)-\dfrac{i}{2}\delta\left(\xi - \dfrac1{2\pi}\right)\right]\\
\\
&= i\pi \left( e^{-\left| 2\pi\left(\xi + \frac1{2\pi}\right)\right|}-e^{-\left| 2\pi\left(\xi - \frac1{2\pi}\right)\right|}\right)\\
\\
&= i\pi \left( e^{-\left| 2\pi\xi +1 \right|}-e^{-\left| 2\pi\xi-1\right|}\right)\\
\end{align}$$

A: Hint: Define the upper semi-circle with center in origin and redius $R$ as the contour and when $z=i$ is a pole of
$$\int_{C}\frac{e^{-2\pi ix\xi + ix}-e^{-2\pi ix\xi -ix}}{1+x^2}dx$$
in $C$, find the residue, then you can simplify the integral.


text:
Q: Joda time calculating the days, hours, minutes, and seconds between two datetime objects I am trying to find the days, hours, minutes and seconds between two date/times. I thought I could use period and I tried the code below but I get a non nonsensical answer.
    DateTime dt1 = new DateTime("2004-12-13T21:39:45.618-06:00");
    DateTime dt2 = new DateTime("2004-12-13T21:39:45.618-08:00");
    Period p = new Period(dt1, dt2);

    System.out.println("Test: " + p);

From this I get output:
I/System.out: Test: PT2H

Not sure what this is meant to mean.
Thanks for your help

A: toString() method in Period gives you the value as ISO8601 duration format.
From the API:

Gets the value as a String in the style of the ISO8601 duration
  format. Technically, the output can breach the ISO specification as
  weeks may be included. For example, "PT6H3M5S" represents 6 hours, 3
  minutes, 5 seconds.

As you ask to get separately the days,hours,minutes and seconds you can use the convenient get methods from the API:
import org.joda.time.DateTime;
import org.joda.time.Period;

...
DateTime dt1 = new DateTime("2004-12-13T21:39:45.618-06:00");
DateTime dt2 = new DateTime("2004-12-13T21:39:45.618-08:00");
Period p = new Period(dt1, dt2);

System.out.println("DAYS: " + p.getDays())
System.out.println("HOURS: " + p.getHours());
System.out.println("MINUTES: " + p.getMinutes());
System.out.println("SECONDS: " + p.getSeconds());

Or alternatively as other answers suggests use PeriodFormatter.

A: Period is printed in ISO format

The standard ISO format - PyYmMwWdDThHmMsS.

If you need to find days, hours, minutes and seconds between two days, you should convert period to specific type. E.g.:
  Period p = new Period(dt1, dt2);
  System.out.println("Days: " + p.toStandardDays().getDays());
  System.out.println("Hours: " + p.toStandardHours().getHours());
  System.out.println("Minutes: " + p.toStandardMinutes().getMinutes());
  System.out.println("Seconds: " + p.toStandardSeconds().getSeconds());

or use special static methods in classes Days, Hours, Minutes and Seconds
  System.out.println("Days: " + Days.daysBetween(dt1, dt2));
  System.out.println("Hours: " + Hours.hoursBetween(dt1, dt2));
  System.out.println("Minutes: " + Minutes.minutesBetween(dt1, dt2));
  System.out.println("Seconds: " + Seconds.secondsBetween(dt1, dt2));

A: I think you'll have to format the object of period. Refer this link
Period to string

A: You need to format your Period. A simple way is to use the default one like this:
PeriodFormat.getDefault().print(period)

You can also create your own format with PeriodFormatter.


text:
Q: How to get content of  with HtmlAgilityPack - C# I have html source:

    خلاصه داستان :
Content

I want to get the value of
 (not  and only the string "Content") with HtmlAgilityPack. What is the best way to do this?
Here is what am I doing.  movieDesHTMLSource is given html source.  I don't know how to access the InnerHtml!
string movieDes;

//Exctact the movie's description HTML source
var movieDesHTMLSource = new HtmlAgilityPack.HtmlDocument();
movieDesHTMLSource.LoadHtml(postPageHTMLDes[95].InnerHtml);
var src = movieDesHTMLSource.DocumentNode.SelectNodes("//div[contains(@class,'lit-plot')]");

A: Use Xpath text() to retrieve just the text inside div tag.
var html = @"

                خلاصه داستان :
            Content

        ";

var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
var htmlNodes = htmlDoc.DocumentNode.SelectNodes("//div[contains(@class,'lit-plot')]/text()");
foreach (HtmlNode node in htmlNodes)
{
    Console.WriteLine(node.InnerText.Trim());
}

Fiddle here : https://dotnetfiddle.net/mXFs8k
I recommend that you wrap your content inside
 or  etc tags then you can easily target it using HtmlAgilityPack.


text:
Q: JQuery and Typescript click() doesn't work Ok so I have two JQuery functions inside a Typescript-file:
            $(window).scroll(function () {
            if ($(this).scrollTop() > 100) {
                $('.scrollToTop').fadeIn();
            } else {
                $('.scrollToTop').fadeOut();
            }

            console.log('Scroll');
        });

        //Click event to scroll to top
        $('#scrollToTopButton').on('click', function () {
            console.log("Click");
        })

The window scroll function works perfectly. However I don't get the click-event working. I tried $('#scrollToTopButton').click(function(){ ... and so on, doesn't seem to work. Here is the html:
 <button type="button" class="btn scrollToTop" id="scrollToTopButton">

A:
so on, doesn't seem to work.

It should work. A few tips for debugging

*

*add console.log($('#scrollToTopButton'))

*Check that you closed the button tag.

*Use an html validator to make sure the html is valid.


text:
Q: Заполнение пустого пространства QPixmap картинкой У меня есть painter, который рисует размытую картинку с учетом поворота, масштабирования и движения.
То есть получается, допустим, следующее:

Вопрос: как рассчитать количество передвижений вверх/вниз/в стороны, чтобы заполнить этой картинкой все пространство, включая маленький уголок сверху слева?

Сейчас я попробовал сделать на коленке, понимаю что это грязно, но оно и не работает.
main_rect - основной кадр с черным фоном;
transformed_rect - квадрат, в котором рисуется картинка.
    QRect frame_to_rect(transformed_painter.transform().mapRect(QRect(0, 0, main_rect.width() * w_scale, main_rect.height() * h_scale)));
    if (frame_to_rect != main_rect) {

      int left_count(0), right_count(0), top_count(0), bottom_count(0);
      while (frame_to_rect.topLeft().x() - (frame_to_rect.width() * left_count) >= 0 || frame_to_rect.bottomLeft().x() - (frame_to_rect.width() * left_count) >= 0) { // сколько раз рисовать слева

        left_count++;
        transformed_painter.drawPixmap(-(main_rect.width() * left_count), 0, main_frame);
      }
      left_count += 1;
      while (frame_to_rect.topRight().x() + (frame_to_rect.width() * right_count) <= main_rect.width() || frame_to_rect.bottomRight().x() + (frame_to_rect.width() * right_count) <= main_rect.width()) { // справа

        right_count++;
        transformed_painter.drawPixmap((main_rect.width() * right_count), 0, main_frame);
      }
      right_count += 1;
      while (frame_to_rect.topLeft().y() - (frame_to_rect.height() * top_count) >= 0 || frame_to_rect.topRight().y() - (frame_to_rect.height() * top_count) >= 0) { // сверху

        top_count++;
        for (int i(left_count); i >= 0; i--)
          transformed_painter.drawPixmap(-(main_rect.width() * i), -((main_rect.height() * top_count)), main_frame);
        for (int i(1); i <= right_count; i++)
          transformed_painter.drawPixmap((main_rect.width() * i), -((main_rect.height() * top_count)), main_frame);
      }
      top_count += 1;
      while (frame_to_rect.bottomLeft().y() + (frame_to_rect.height() * bottom_count) <= main_rect.height() || frame_to_rect.bottomLeft().y() + (frame_to_rect.height() * bottom_count) <= main_rect.height()) {// снизу
        bottom_count++;

        for (int i(left_count); i >= 0; i--)
          transformed_painter.drawPixmap(-(main_rect.width() * i), ((main_rect.height() * bottom_count)), main_frame);
        for (int i(1); i <= right_count; i++)
          transformed_painter.drawPixmap((main_rect.width() * i), ((main_rect.height() * bottom_count)), main_frame);
      }
    }

A: пока сделал следующим образом, работает, громоздко, но других вариантов не придумал
QRectF visible_rect(QPoint(0,0), additional_effect_.dev_rect_.size());
      QRectF transf_to_visible(transformed_painter.transform().map(QPoint(0, 0)),
                           transformed_painter.transform().map(QPoint(rect_width, rect_height)));

      if (transf_to_visible != main_frame.rect()) {

        int side_count(2);
        while (true) {

          bool all_outside(true);

          for (int count(-(side_count - 1)); count < side_count; count++) { // дорисовка сверху, снизу

            QPoint upper_top_left(rect_width * count, -rect_height * (side_count - 1)), lower_top_left(rect_width * count, rect_height * (side_count - 1));

            transf_to_visible = QRectF(transformed_painter.transform().mapRect(QRectF(upper_top_left, QSizeF(rect_width, rect_height))));
            if (visible_rect.intersects(transf_to_visible)) {

              transformed_painter.drawPixmap(rect_width * count, -rect_height * (side_count - 1), main_frame);
              all_outside = false;
            }
            transf_to_visible = QRectF(transformed_painter.transform().mapRect(QRectF(lower_top_left, QSizeF(rect_width, rect_height))));
            if (visible_rect.intersects(transf_to_visible)) {

              transformed_painter.drawPixmap(rect_width * count, rect_height * (side_count - 1), main_frame);
              all_outside = false;
            }
          }

          for (int count(-(side_count - 2)); count < side_count - 1; count++) { // дорисовка в стороны

            QPoint left_top_left(-rect_width * (side_count - 1), rect_height * count), right_top_left(rect_width * (side_count - 1), rect_height * count);
            transf_to_visible = QRectF(transformed_painter.transform().mapRect(QRectF(left_top_left, QSizeF(rect_width, rect_height))));
            if (visible_rect.intersects(transf_to_visible)) {

              transformed_painter.drawPixmap(-rect_width * (side_count - 1), rect_height * count, main_frame);
              all_outside = false;
            }
            transf_to_visible = QRectF(transformed_painter.transform().mapRect(QRectF(right_top_left, QSizeF(rect_width, rect_height))));
            if (visible_rect.intersects(transf_to_visible)) {

              transformed_painter.drawPixmap(rect_width * (side_count - 1), rect_height * count, main_frame);
              all_outside = false;
            }
          }

          if (all_outside) // если все расчитанные прямоугольники вышли за пределы области отрисовки - остановка
            break;

          side_count++; // количество
        }
      }


text:
Q: Append tag name (version number) to Zip file in git post-receive hook In Git, I'm trying to get the version number of my commit (by using tags) in a post-receive hook.
Once I get that tag, I want to zip a certain directory and append the version number to it (ex: myplugin-2.0.1.zip) but I'm not sure how to get the tag of the commit in the post-receive hook.
Does anyone know how to properly get the tag name of a commit inside a post-receive hook?
Here's what I have so far, but the SOME_WAY_OF_GETTING_TAG_NAME is where I'm confused.
#!/bin/bash
_version=SOME_WAY_OF_GETTING_TAG_NAME
zip -r myplugin-$_version.zip plugin_repo/

Any help would be appreciate. Thanks!

A: The post-receive hooks gets as input from stdin
<oldrev> <newrev> <refname>

refname always contain ref, if you tagged, it will be refs/tags/TAGNAME


text:
Q: Is a Z value of -4.703 statistically signficant? I was wondering, i have a Z value of -4.7 is this a significant positive skew based on a 1.96 cut off?
And for Z value of Kurtosis of -0.16 is this proving its non significant as its less than the 1.96 Cut off?
Many thanks


text:
Q: Changing the number of nodes on ssh cluster to improve time I'm using ssh to run a python program on a cluster, the cluster is configured to accept jobs using slurm. The sbatch script to run the .py is:
#!/bin/bash
#!/bin/bash
#SBATCH --job-name=cnn
#SBATCH --time=1:00:00
##SBATCH --output=cnn.out
#SBATCH --ntasks=8
source activate cnn
python3 cnn.py

I think the program is taking to long to finish so I wanna know if changing the number of nodes (4,16 or 32 instead of 8) can improve that.


text:
Q: Calculations from elements of two list of lists I have two list of lists
lst1=[['1', '1', '0'],['1', '-1', '0'],['1', '0', '-3'],['0', '1', '-0.5']]
lst2=[(1,1),(2,1),(3,2),(3,4)]

I want to do the multiplication of each element in list1 with lst2.
i.e, 1st elements in the 1st list of lst * all the lists in lst2
[1*1+1*1+0, 1*2+1*1+0, 1*3+1*2+0, 1*3+1*4+0]
etc.

I converted the first list elements into float and flattened the list of lists into a single list. My logic seems to be wrong. I am stuck here.
can somebody help me with a hint on how to proceed?
Thanks

A: This code uses the following operations.

*

*List comprehension with the outer loop for lst1 and the inner for lst2

*Use of map(float, l1) on the elements of the elements of lst1 to convert to int

*Concatenation of a 1-element tuple containing the number 0 l2+(0,) to create an implicit multiplier for the missing 3rd element in the elements of lst2, with the net effect of ignoring the 3rd element of each triple in lst1.

*Use of map(mul, ... to do the multiplication of the triples.

*Using sum to add the triples together to create the final list of results

from operator import mul

lst1=[['1', '1', '0'],['1', '-1', '0'],['1', '0', '-3'],['0', '1', '-0.5']]
lst2=[(1,1),(2,1),(3,2),(3,4)]

print([sum(map(mul, map(float, l1), l2+(0,))) for l2 in lst2 for l1 in lst1])

Result:
[2.0, 0.0, 1.0, 1.0, 3.0, 1.0, 2.0, 1.0, 5.0, 1.0, 3.0, 2.0, 7.0, -1.0, 3.0, 4.0]


text:
Q: Dojo Charting Tooltip not visible I am trying to create a chart with custom tool tip. You can see the JSFIDDLE example here.
I have added a custom tooltip which does not appear. I can see the event fires(with the help of console.log) but the tooltip somehow does not appear(as if the rendering is not not happening) :(
 var tip = new Tooltip(c, "default", {
            text: function (o) {
                console.log(o);
                return (o.y);
            }
        });

Any hint to help me going ?

A: It was just the case of missing CSS for the tooltip. I added the link to
http://archive.dojotoolkit.org/nightly/dojotoolkit/dijit/themes/claro/claro.css

and it worked fine. Thanks


text:
Q: Authorize.net: Manually re-charge a client after a failed ARB transaction We use Authorize.net's Automated Recurring Billing and when a client's subscription payment fails is there a way to manually re-attempt to charge the client for the subscription? The only way I've ever been able been able to make it work is to get their CC info and manually key in a transaction but for instances where a client's car simply had insufficient funds/etc it's a pain (and far from ideal) to have to ask them to re-enter their CC info so we can attempt to charge them again. Is there a way to trigger ARB to retry the transaction or create a one-off AIM transaction from the subscription w/o requiring their CC info?

A: I think there is some real misinformation on this question.
Authorize.NET allows you to "Store" customer billing information (CC info, etc) on their system (avoiding all the bad juju that happens when you store CC info locally).
You can do this using the CreateCustomerProfile method.
The response from this method is basically some key(s) to uniquely identify their account in Authorize.NET's system.
Use that account ID you can bill their CC ad-hoc whenever/however you'd like using the CreateCustomerProfileTransaction method.
If one of their payments fails due to, for example, not enough funds - then you can try to rebill them later using this approach.
If, however, their CC info changes - you need to let the customer update their CC info - and use Authorize.NET's methods to update their profile.

A: After research I've determined there are two options:

*

*Store credit card #s encrypted

*Do nothing.

Since storing them encrypted is more than I wanted to mess with at this time I'm going to have to go for option 2.
Authorize.net has a pretty weak API. If anyone has a recommendation for a payment gateway whose API isn't in the stone age I'd love to hear about it.
Cheers,
Dan

A: Use the Authorize.net CIM API to store your customer credit card information rather than storing it locally. If for some reason an ARB transaction fails, you can use the CIM API to charge your customer on a one-time basis (cf create_customer_profile_transaction in the CIM API).

A: If the transaction failed because the card is no longer valid, expired, or at its limit, then you won't be able to recharge it even if you had the credit card information. You would need to have the customer provide you with a new credit card anyway so you can update their subscription and charge them for the missed payment at that point in time.


text:
Q: Principal is null for every Spring websocket event I'm trying to get the the Principal user name from Spring websocket SessionConnectEvent but it is null on every listener. What I can be doing wrong?
To implement it I followed the answers you will find here: how to capture connection event in my webSocket server with Spring 4?
@Slf4j
@Service
public class SessionEventListener {

    @EventListener
    private void handleSessionConnect(SessionConnectEvent event) {
        SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(event.getMessage());
        String sessionId = headers.getSessionId();
        log.debug("sessionId is " + sessionId);
        String username = headers.getUser().getName(); // headers.getUser() is null
        log.debug("username is " + username);
    }

    @EventListener
    private void handleSessionConnected(SessionConnectEvent event) {
        SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(event.getMessage());
        String sessionId = headers.getSessionId();
        log.debug("sessionId is " + sessionId);
        String username = headers.getUser().getName(); // headers.getUser() is null
        log.debug("username is " + username);
    }

    @EventListener
    private void handleSubscribeEvent(SessionSubscribeEvent event) {
        SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(event.getMessage());
        String sessionId = headers.getSessionId();
        log.debug("sessionId is " + sessionId);
        String subscriptionId = headers.getSubscriptionId();
        log.debug("subscriptionId is " + subscriptionId);
        String username = headers.getUser().getName(); // headers.getUser() is null
        log.debug("username is " + username);
    }

    @EventListener
    private void handleUnsubscribeEvent(SessionUnsubscribeEvent event) {
        SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(event.getMessage());
        String sessionId = headers.getSessionId();
        log.debug("sessionId is " + sessionId);
        String subscriptionId = headers.getSubscriptionId();
        log.debug("subscriptionId is " + subscriptionId);
        String username = headers.getUser().getName(); // headers.getUser() is null
        log.debug("username is " + username);
    }

    @EventListener
    private void handleSessionDisconnect(SessionDisconnectEvent event) {
        SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(event.getMessage());
        log.debug("sessionId is " + event.getSessionId());
        String username = headers.getUser().getName(); // headers.getUser() is null
        log.debug("username is " + username);
    }

}

This is my security config:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .anyRequest()
            .permitAll()
            .and().csrf().disable();
    }
}

A: As I'm not implementing an authentication mechanisim, Spring has no enough information to provide a Principal user name. So what I had to do is to configure a HandshakeHandler that generates the Principal.
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    public static final String ENDPOINT_CONNECT = "/connect";
    public static final String SUBSCRIBE_USER_PREFIX = "/private";
    public static final String SUBSCRIBE_USER_REPLY = "/reply";
    public static final String SUBSCRIBE_QUEUE = "/queue";

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker(SUBSCRIBE_QUEUE, SUBSCRIBE_USER_REPLY);
        registry.setUserDestinationPrefix(SUBSCRIBE_USER_PREFIX);
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint(ENDPOINT_CONNECT)
                // assign a random username as principal for each websocket client
                // this is needed to be able to communicate with a specific client
                .setHandshakeHandler(new AssignPrincipalHandshakeHandler())
                .setAllowedOrigins("*");
    }

}

/**
 * Assign a random username as principal for each websocket client. This is
 * needed to be able to communicate with a specific client.
 */
public class AssignPrincipalHandshakeHandler extends DefaultHandshakeHandler {
    private static final String ATTR_PRINCIPAL = "__principal__";

    @Override
    protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
        final String name;
        if (!attributes.containsKey(ATTR_PRINCIPAL)) {
            name = generateRandomUsername();
            attributes.put(ATTR_PRINCIPAL, name);
        } else {
            name = (String) attributes.get(ATTR_PRINCIPAL);
        }
        return new Principal() {
            @Override
            public String getName() {
                return name;
            }
        };
    }

    private String generateRandomUsername() {
        RandomStringGenerator randomStringGenerator =
                new RandomStringGenerator.Builder()
                    .withinRange('0', 'z')
                    .filteredBy(CharacterPredicates.LETTERS, CharacterPredicates.DIGITS).build();
        return randomStringGenerator.generate(32);
    }
}

A: Looking into the implementation of AbstractSubProtocolEvent (the superclass of all the events you're interested in) you can see that the user is hold in a seperate field. So you can simply access the user by calling event.getUser(). You don't need to get it from the message.
E.g. for the SessionConnectedEvent you can see that the user gets populated in the event but not the message.
Update:
You can only access the user when you authenticated the http upgrade. So you need to have a WebSecurityConfigurerAdapter that configures something like:
@Configuration
public static class UserWebSecurity extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatchers()
                .antMatchers(WebsocketPaths.WEBSOCKET_HANDSHAKE_PREFIX); //You configured the path in WebSocketMessageBrokerConfigurer#registerStompEndpoints

        http
                .authorizeRequests()
                .anyRequest().authenticated();
    }

}


text:
Q: syntax for ancestor:: in Xpath expression xpath -e '//attribute::vo/../text()' books.xml
returns the content of each element having an attribute named vo.
For example, with this book.xml :
<bookstore>
<book category="cooking">
  <title lang="en" vo="it">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>
<book category="children">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>
<book category="web">
  <title lang="en" vo="fr">XQuery Kick Start</title>
  <author>James McGovern</author>
  <author>Per Bothner</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</author>
  <year>2003</year>
  <price>49.99</price>
</book>
<book category="web">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
</book>
</bookstore>

then the request :
xpath -e '//attribute::vo/../text()' books.xml
gives :
Found 2 nodes in /tmp/books.xml:
-- NODE --
Everyday Italian
-- NODE --
XQuery Kick Start

What should be the syntax of the request having the same result, but with ancestor:: in place of .. ?

A: I understand that //attribute::vo/../text() is not an natural Xpath expression.
//*[@vo]/text() is better.
So no need to introduce ancestor:: or parent:: in place of ...

A: If you still want to know how ancestor works, it takes parent of current node, grand parent of current node and so on up to the root. So your query with ancestor would look like
//attribute::vo/ancestor::*[1]/title/text()

Where ancestor means that you're going to collect all the (grand)parents, * means that you do not care of what nodes those (grand)parents would be, and [1] means that you need the "closest" one to the current node.
The same result would be produced by the following query:
//attribute::vo/ancestor::book/title/text()

Since it doesn't take root element because it is not book node. So that we have "flat" hierarchy here.
The following query would take only the books with "Web" category (this is not what you asked actually but probably will give more clear vision on how to work with axes):
//attribute::vo/ancestor::book[@category='web']/title/text()


text:
Q: graphics magicks rotation 90 when bytes is passed from stdin and read from stdout When I try to pass a jpeg which have exif rotation as 90 and try to resize my resize image gets corrupted. The fix for now is passing the image as a file and reading the output also as file. Currently I am reading and writing the bytes from stdin and stdout directly from my Java processBuilder.
Does anyone know why this problem occurs?
gm convert -limit threads 4 -limit Memory 512M -limit Map 1024M -limit Disk 1024M -size 2048x1458 - -flatten -sharpen 1.00x0.95 -rotate 90 -scale '2048x2048>' +profile !icm,* -interlace None -type TrueColor -quality 93 -sampling-factor 1x1 jpeg:-
UPDATE:
This has nothing to do with rotation.
The problem is since the jpegs have some trailer in the end of the file.
.........
JPEG RST7
JPEG RST0
JPEG EOI
Samsung trailer (129 bytes at offset 0x1ba3ed):
gm identify gives below result
rotate_1_37658078940_605a46_o.jpg JPEG 2592x1944+0+0 DirectClass 8-bit 1.7M 0.000u 0:01
gm identify: Invalid SOS parameters for sequential JPEG (rotate_1_37658078940_605a46_o.jpg).

A: There is no problem with Graphics Magick convert. The redirectError stream was set to true due to which the stderr was clubbed with stdout(bytes).


text:
Q: First Person Shooter box collider problem I'm creating a FPS game and I have the following issue:
Sometimes, when I shoot at the enemies the hit is not recognized, even if the player is shooting in front of them. However, when they attack the player, the hit is recognized normally.
They have a box collider and a rigidbody attached to them.
This script is attached to the player:
using System.Collections.Generic;
using UnityEngine;

public class DisparaArma : MonoBehaviour
{
    private GerenciaArma gerenciaArma;

    public float nDisparo = 15f;
    private float TempoProximoDisparo;
    public float damage = 20f;

    private Animator ZoomCameraIn;
    private bool zoomed;

    private Camera Maincamera;
    private GameObject mira;
    // Start is called before the first frame update
    void Start()
    {
        gerenciaArma = GetComponent<GerenciaArma>();
        ZoomCameraIn = transform.Find(Tags.LOOK_ROOT).transform.Find(Tags.ZOOM_CAMERA).GetComponent<Animator>();

        mira = GameObject.FindWithTag(Tags.MIRA);
        Maincamera = Camera.main;
    }

    // Update is called once per frame
    void Update()
    {
        Atira();
        ZoomInAndOut();
    }

    void Atira()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if(gerenciaArma.SelecionaArma().tipoBala == WeaponBulletType.BULLET)
            {
                gerenciaArma.SelecionaArma().AnimacaoTiro();
                DisparaBala();

            }

        }
    }

    void ZoomInAndOut()
    {
        if (gerenciaArma.SelecionaArma().mira_tipo == TipoMira.AIM)
        {
            if (Input.GetMouseButtonDown(1))
            {
                ZoomCameraIn.Play(Animacoes.ZOOM_IN_ANIM);
               // gerenciaArma.SelecionaArma().Aim(true);
                mira.SetActive(false);
                print("VaiZoom");
            }

            if (Input.GetMouseButtonUp(1))//
            {
                ZoomCameraIn.Play(Animacoes.ZOOM_OUT_ANIM);
                //gerenciaArma.SelecionaArma().Aim(false);
                mira.SetActive(true);
            }
        }
    }

    void DisparaBala()
    {
        RaycastHit hit;
        if(Physics.Raycast(Maincamera.transform.position, Maincamera.transform.forward, out hit))
        {

            if (hit.transform.tag == Tags.ENEMY_TAG)
            {
                hit.transform.GetComponent<ScriptVida>().DanoAplicado(damage);
            }
        }
    }
}

And this one is attached to the enemies:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class ScriptVida : MonoBehaviour
{
    private IndioAnimações indio_Anim;
    private NavMeshAgent navAgent;
    private IndioController indio_Controller;

    public float vida = 100f;
    public bool is_Player, is_Cannibal, is_Tiger;

    private bool morto;
    // Start is called before the first frame update
    void Awake()
    {
        if (is_Tiger || is_Cannibal)
        {
            indio_Anim = GetComponent<IndioAnimações>();
            indio_Controller = GetComponent<IndioController>();
            navAgent = GetComponent<NavMeshAgent>();
        }

        if (is_Player)
        {

        }
    }

    public void DanoAplicado(float damage)
    {
        if (morto)
            return;
        vida -= damage;

        if (is_Player)
        {

        }

        if (is_Tiger || is_Cannibal)
        {
            if (indio_Controller.EnemyState == EnemyState.PATROL)
            {
                indio_Controller.chase_Distance = 50f;
            }
        }

        if (vida <= 0)
        {
            JogadorMorre();
            morto = true;
            print(vida);
        }

    }

    void JogadorMorre()
    {
        if (is_Cannibal)//
        {
            GetComponent<Animator>().enabled = false;
            GetComponent<BoxCollider>().isTrigger = false;
            GetComponent<Rigidbody>().AddTorque(-transform.forward * 50f);

            indio_Controller.enabled = false;
            navAgent.enabled = false;
            indio_Anim.enabled = false;
        }

        if (is_Tiger)
        {
            GetComponent<Animator>().enabled = false;
            GetComponent<BoxCollider>().isTrigger = false;
            GetComponent<Rigidbody>().AddTorque(-transform.forward * 50f);

            indio_Controller.enabled = false;
            navAgent.enabled = false;
            indio_Anim.enabled = false;
        }

        if (is_Player)
        {
            GameObject[] enemies = GameObject.FindGameObjectsWithTag(Tags.ENEMY_TAG);
            for (int i = 0; i < enemies.Length; i++)
            {
                enemies[i].GetComponent<IndioController>().enabled = false;
            }

            GetComponent<Movimentação>().enabled = false;
            GetComponent<DisparaArma>().enabled = false;
            GetComponent<GerenciaArma>().SelecionaArma().gameObject.SetActive(false);
        }

        if (tag == Tags.PLAYER_TAG)
        {
            Invoke("RestartGame", 3f);
        }

        else
        {
            Invoke("TurnOffGameObject", 3f);
        }
    }

    void RestartGame()
    {
        UnityEngine.SceneManagement.SceneManager.LoadScene("Gameplay");
    }

    void TurnOffGameObject()
    {
        gameObject.SetActive(false);
    }

}

I think the problem is related to the box collider.
How could I solve this guys?


text:
Q: Performance improvement in the query I have the below query that does a self join on the Locations table. When I run this query on a million records, it takes more than 2 hours to execute. Would really appreciate if any performance improvement can be done on this query so that execution time be improved.
SELECT
    a.Id1, a.Id2, a.LocationStart, a.LocationEnd
FROM
    Locations AS a
JOIN
    Locations AS b
ON
    a.Id1= b.Id1 AND a.Id2 = b.Id2
WHERE
    a.DateTime = (
        SELECT
            MIN(DateTime)
        FROM
            Locations
        WHERE
            Id1 = a.Id1
            AND Id2 = a.Id2)

A: I would observe that your query doesn't really make sense.  I assume it is oversimplified, so I'll include columns from both table references.
I would start by using window functions:
SELECT l.Id1, l.Id2, l2.id1, l2.id2, l.LocationStart, l.LocationEnd
FROM (SELECT l.*,
             ROW_NUMBER() OVER (PARTITION BY id1, id2 ORDER BY datetime ASC) as seqnum
      FROM Locations l
     ) l JOIN
    Locations l2
    ON l.Id1 = l2.Id1 AND l.Id2 = l2.Id2 AND l.seqnum = 1;

This assumes that you are looking for a unique value from the first table (that is, there are no date time duplicates).
Next, I would observe that you simply want the first value for the l1 fields.  Guess what?  You don't need a join at all.
select first_value(l.id1) over (partition by id1, id2 order by datetime),
       first_value(l.id2) over (partition by id1, id2 order by datetime),
       l.id1,
       l.id2,
       first_value(l.locationstart) over (partition by id1, id2 order by datetime),
       first_value(l.locationend) over (partition by id1, id2 order by datetime)
from locations l;


text:
Q: Accessing elements in panda dataframe How do I iterate through this dataframe?  I want to know what the nameis (AAL, AAME, or AACG) and be able to access the everything highlighted in red for name.

A: You are trying to access the multi-index column. Accessing a multi-index column is pretty the same as the access a column in the general dataFrame. For example, if you want to access 2020-05-21 row in AAL then you have to...
df['AAL']['Date']['2020-05-21']


text:
Q: How can I DllImport a file from resources using VB.NET? Is there any way in VB.NET to DllImport a dll file from the resources?
I really don't want to add the dll with the executable path.

A: You can embed a DLL into an executable:
Jeffrey Richter: Excerpt #2 from CLR via C#, Third Edition

Many applications consist of an EXE file that depends on many DLL
  files. When deploying this application, all the files must be
  deployed. However, there is a technique that you can use to deploy
  just a single EXE file. First, identify all the DLL files that your
  EXE file depends on that do not ship as part of the Microsoft .NET
  Framework itself. Then add these DLLs to your Visual Studio project.
  For each DLL file you add, display its properties and change its
  "Build Action" to "Embedded Resource." This causes the C# compiler to
  embed the DLL file(s) into your EXE file, and you can deploy this one
  EXE file.
At runtime, the CLR won't be able to find the dependent DLL
  assemblies, which is a problem. To fix this, when your application
  initializes, register a callback method with the AppDomain's
  ResolveAssembly event.


text:
Q: Adding components from right to left I need to display a list of boxes with maximize, minimize and close button to the bottom right of the screen. The cards should be displayed from bottom right to left. The issue that I am having is cards are getting added from bottom left to right. Say on subsequent clicks of button 1, button 2, button 3 the cards should be in the card3, card2, card1 from bottom because button is clicked first. Here it is happening the other way.
Also I am unable to implement maxmize and minimize function. Cancel operation is working fine.
https://codesandbox.io/s/panel-item-addtion-using-redux-updated-hxmihq?file=/src/components/PanelAdder.jsx
App.tsx
import React from "react";
import { useSelector } from "react-redux";
import Header from "./src/components/Header";
import Footer from "./src/components/Footer";
import Content from "./src/components/Content";
import Panel from "./src/components/Panel";
import "./styles.css";

export default function App() {
  const panels = useSelector((state) => state.panel.panelItems);
  return (
    <>

      <Content />

        {panels.map((name) => (
          <Panel key={name} {...{ name }} />
        ))}

    </>
  );
}

PanelAdder
import React from "react";
import { useDispatch } from "react-redux";
import { useSelector } from "react-redux";
import { addPanel } from "../actions/counterActions";

export default function PanelAdder() {
  const dispatch = useDispatch();
  const panels = useSelector((state) => state.panel.panelItems);

  const handleClick = (name) => {
    if (panels.includes(name)) return;
    dispatch(addPanel(name));
  };

  return (
    <>
      <button onClick={() => handleClick("Panel 1")}> Add Panel 1</button>
      <button onClick={() => handleClick("Panel 2")}> Add Panel 2</button>
      <button onClick={() => handleClick("Panel 3")}> Add Panel 3</button>
    </>
  );
}

Panel
import React from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
  faSquareMinus,
  faWindowMaximize,
  faRectangleXmark
} from "@fortawesome/free-solid-svg-icons";
import { useDispatch } from "react-redux";
import { deletePanel } from "../actions/counterActions";

export default function Panel({ name }) {
  const dispatch = useDispatch();
  return (
    <>

          <FontAwesomeIcon icon={faSquareMinus} />
          <FontAwesomeIcon icon={faWindowMaximize} />
          <FontAwesomeIcon
            icon={faRectangleXmark}
            onClick={() => dispatch(deletePanel(name))}
          />

{name}

    </>
  );
}

A: case "ADD_PANEL":
  return {
    ...state,
    panelItems: [action.payload, ...state.panelItems]
  };

Just make the following changes to your reducer and you'll be able to achieve the desired card display.
Instead of adding the new panel to the end of the array, you add it to the start.

A: .cards-container {
      display: flex;
      /* making element one near the other */
      height: 100vh;
      /* setting the height of div to device_height (so we can put them in the end of the page) */
      align-items: flex-end;
      /* aligning the cards to the end of the page */
      justify-content: flex-start;
      /* aligning the cards to the end of the page */
      padding: 1rem;
      /* adding some padding to the end of the page */
      gap: 1rem;
      /* adding some gap between the cards */
    }

You just had to put justify-content: flex-start here.
Edit
Here is how you can max and min the card window.
https://codesandbox.io/embed/panel-item-addtion-using-redux-updated-forked-n5suqd?fontsize=14&hidenavigation=1&theme=dark
Just use useState to toggle between the two classes. First, set the initial class to be the one you see when you click on the addPanel button. Then, you add an onClick to the min and max buttons. The min button changes the style of the card to the new style, and the max button sets the style of the card back to the original one.

A: There is several way to do it.
A first one could be to add the new panel as first element instead of the last one in your reducer as Zarish Iqbal did it.
A second one would be to keep the list as is, and to play with the flexbox properties of your .cards-container. By using flex-direction: row-reverse; and justify-content: flex-start;, the items will be displayed in the order you want.
flex-direction: row-reverse; make the content go from right to left, and justify-content: flex-start; align the content at the start, so on the right.
More information about flex-direction


text:
Q: Setup HLS caching policy As soon as EXT-X-ALLOW-CACHE deprecated and removed from protocol specification is there alternative way to setup caching policy for a stream? (my goal is to enable caching on client)
Also I want to get rid of error while validating stream with mediastreamvalidator:
MUST fix issues
--------------------------------------------------------------
Error: #EXT-X-ALLOW-CACHE has been deprecated
--> Detail:  Line: #EXT-X-ALLOW-CACHE:NO

A: You can use AVFoundation on iOS 10+:

Playing Offline HLS Content
Starting with iOS 10, you can use AVFoundation to download HTTP Live Streaming assets to an iOS device. This new capability allows users to download and store HLS movies on their devices while they have access to a fast, reliable network, and watch them later without a network connection. With the introduction of this capability, HLS becomes even more versatile by minimizing the impact of inconsistent network availability on the user experience

Source: Working with HTTP Live Streaming

A: Old question, but perhaps will help someone:
The only thing that seems to work for HLS caching is running your own caching reverse-proxy within your app. Madness, but it really works well.
This proxy HLSCachingReverseProxyServer from devxoul as mentioned in this comment is a great drop in option, and starting point for optimising caching for your needs.
It's absurd that we need to do this to make Apple's component respect something as basic as eTags.


text:
Q: Symfony2 getLastUsername() function not working I'm creating my first Symfony2 login form and want to use the getLastUsername() function to set the value of the username textbox but when calling the function it simply returns an empty string.
This is my SecurityController.php file:
<?php
namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class SecurityController extends Controller
{
    /**
     * @Route("/login", name="login")
     */
    public function loginAction(Request $request)
    {
        $authenticationUtils = $this->get('security.authentication_utils');

        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();

        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();

        return $this->render(
            'security/login.html.twig',
            array(
                // last username entered by the user
                'last_username' => $lastUsername,
                'error'         => $error,
            )
        );
    }

    /**
     * @Route("/login_check", name="login_check")
     */
    public function loginCheckAction()
    {
    }
}
?>

and my Twig template for the form:
{# app/Resources/views/security/login.html.twig #}
{% extends 'base.html.twig' %}

{% block stylesheets %}
    {{ parent() }}
    <link href="{{ asset('css/login.css') }}" rel="stylesheet" />
{% endblock %}

{% block javascripts %}
    {{ parent() }}

{% endblock %}

{% block body %}

    {% if error %}

{{ error.messageKey|trans(error.messageData, 'security') }}

    {% endif %}

            <form id="loginform" action="{{ path('login_check') }}" method="post">

Enter username and password to continue.

                    <input class="form-control" type="text" name="_username" id="username" placeholder="Username" value="{{ last_username }}" />

                    <input class="form-control" type="password" name="_password" id="password" placeholder="Password" />

                        Create new account

                        Lost password?

                    <input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}" />
                    <input type="submit" class="btn btn-block btn-primary btn-default" value="Login" />

            </form>

{% endblock %}

Everything works fine. Logged in and out many times but the las username isn't showing. Thought Symfony might be using cookies to save the last used username but it isn't creating any cookies, only the PHP session is saved in a cookie. Is it a problem in the cookie configurations or may be something else?
Thanks,


text:
Q: HTML Mail Cursor Pointer Hack On Gmail According to This List Gmail is not supporting the cursor properties

now my question is if any body knows any hack to use in sending newsletters or HTML Mails with Cursor Pointer enable in Gmail?
Thanks


text:
Q: an application of the Poisson summation formula It is written in a paper that I was reading that "by an application of the Poisson summation formula" we have
$\sum_{n \ne 0} |n|^{-1} e^{inx} = C \ln |x| + \phi(x)$
with some smooth function $\phi$. Unfortunately, I tried hard but I could not really see to which function we need to apply the Poisson formula.


text:
Q: How to change the color of line plotted on y axis midway in plotly? I have a dataframe with 2 columns: 'Ground Truth' and 'Predicted Values', that I am plotting using plotly express.
timestamp                Ground Truth     Predicted Values
2012-04-01 00:30:00      251.71               NA
2012-04-01 00:15:00      652.782              NA
2012-04-01 00:00:00      458.099              NA
2012-03-31 23:45:00      3504.664             NA
2012-03-31 23:30:00      1215.76             1230
2012-03-31 23:15:00     -21.48               -19.99
2012-03-31 23:00:00     -8.538               -7.42
2012-03-31 22:40:00     -5.11                -5.2

Code for plot
fig = px.line(df, x = df.index, y = ['Ground Truth','Predicted Values'], markers='.')

fig.update_xaxes(
        rangeslider_visible=True,
        rangeselector=dict(
            buttons=list([
                dict(count = 1, label = "1H", step = "hour", stepmode ="backward"),
                dict(step="all")
            ])
        )
    )
fig.show()

With the current code, one line for each column is being plotted (As per given below). I am trying to change the graph, in which the blue line's changes to some other color from the start of the red line. Can someone please help? (In reference to the dataframe, the red line is for 'Predicted values' columns which starts after the NA values end).
Current graph (plotted on different values):

A: I managed to solve it based on the help from @r-beginners comment above. I'll add the code here, in case it might help anyone.
Use boolean indexing. I create a new column in the DataFrame called 'New Column' and fill it with NaN values. Then used boolean indexing to set the values in 'New Column' where 'Predicted Values' are not NaN to the corresponding values in 'Ground Truth'. The ~ operator inverts the boolean mask generated by the isna() method, so I am selecting rows where 'Predicted Values' are not NaN.
# Create a new column and populate it with 'Ground Truth' values where 'Predicted Values' are not NaN
df['New Column'] = np.nan
df.loc[~df['Predicted Values'].isna(), 'New Column'] = df.loc[~df['Predicted Values'].isna(), 'Ground Truth']


text:
Q: Create self-signed certificate with end-date in the past I would like to create self-signed certificates on the fly with arbitrary start- and end-dates, including end-dates in the past. I would prefer to use standard tools, e.g., OpenSSL, but anything that gets the job done would be great.
The Stack Overflow question How to generate openssl certificate with expiry less than one day? asks a similar question, but I want my certificate to be self-signed.
In case you were wondering, the certificates are needed for automated testing.

A: Or you could use something like this short python program ... (caveats apply)
It creates a key (test.key) and a certificate (test.crt) with inception time 10 years in the past (-10*365*24*60*60 seconds is -10 years) and expiration time 5 years in the past (-5*365*24*60*60).
Please note that it's a minimal demonstration program, so it does not bother to set any extensions, (e.g. basicConstraints) and uses fixed serial.
#!/usr/bin/env python

from OpenSSL import crypto

key = crypto.PKey()
key.generate_key(crypto.TYPE_RSA, 2048)
cert = crypto.X509()
cert.get_subject().CN = "Test"
cert.set_serial_number(666)
cert.gmtime_adj_notBefore(-10*365*24*60*60)
cert.gmtime_adj_notAfter(-5*365*24*60*60)
cert.set_issuer(cert.get_subject())
cert.set_pubkey(key)
cert.sign(key, 'sha384')

open("test.crt", "wb").write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
open("test.key", "wb").write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key))

A: You have two ways of creating certificates in the past. Either faking the time (1)(2), or defining the time interval when signing the certificate (3).
1) Firstly, about faking the time: to make one program think it is in a different date from the system, have a look at libfaketime and faketime
To install it in Debian:
sudo apt-get install faketime

You would then use faketime before the openssl command.
For examples of use:
$faketime 'last friday 5 pm' /bin/date
Fri Apr 14 17:00:00 WEST 2017
$faketime '2008-12-24 08:15:42' /bin/date
Wed Dec 24 08:15:42 WET 2008

From man faketime:

The  given  command  will  be  tricked  into believing that the
  current
         system time is the one specified in the timestamp. The wall clock  will
         continue to run from this date and time unless specified otherwise (see
         advanced  options).  Actually,  faketime  is  a  simple   wrapper   for
         libfaketime,  which  uses  the  LD_PRELOAD  mechanism  to  load a small
         library which intercepts system calls to functions such as time(2)  and
         fstat(2).

So for instance, in your case, you can very well define a date of 2008, and create then a certificate with the validity of 2 years up to 2010.
faketime '2008-12-24 08:15:42' openssl ...

As a side note, this utility can be used in several Unix versions, including MacOS, as an wrapper to any kind of programs (not exclusive to the command line).
As a clarification, only the binaries loaded with this method (and their children) have their time changed, and the fake time does not affect the current time of the rest of the system.
2) As @Wyzard states, you also have the datefudge package which is very similar in use to faketime.
As differences, datefudge does not influence fstat (i.e. does not change file time creation). It also has it´s own library, datefudge.so, that it loads using LD_PRELOAD.
It also has a  -s static time where the time referenced is always returned despite how many extra seconds have passed.
$ datefudge --static "2007-04-01 10:23" sh -c "sleep 3; date -R"
Sun, 01 Apr 2007 10:23:00 +0100

3) Besides faking the time, and even more simply, you can also define the starting point and ending point of validity of the certificate when signing the certificate in OpenSSL.
The misconception of the question you link to in your question, is that certificate validity is not defined at request time (at the CSR request), but when signing it.
When using openssl ca to create the self-signed certificate, add the options -startdate and -enddate.
The date format in those two options, according to openssl sources at openssl/crypto/x509/x509_vfy.c, is ASN1_TIME aka ASN1UTCTime: the format must be either YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ.
Quoting openssl/crypto/x509/x509_vfy.c:

int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time)
{
    static const size_t utctime_length = sizeof("YYMMDDHHMMSSZ") - 1;
    static const size_t generalizedtime_length = sizeof("YYYYMMDDHHMMSSZ") - 1;
    ASN1_TIME *asn1_cmp_time = NULL;
    int i, day, sec, ret = 0;

    /*
     * Note that ASN.1 allows much more slack in the time format than RFC5280.
     * In RFC5280, the representation is fixed:
     * UTCTime: YYMMDDHHMMSSZ
     * GeneralizedTime: YYYYMMDDHHMMSSZ
     *
     * We do NOT currently enforce the following RFC 5280 requirement:
     * "CAs conforming to this profile MUST always encode certificate
     *  validity dates through the year 2049 as UTCTime; certificate validity
     *  dates in 2050 or later MUST be encoded as GeneralizedTime."
     */

And from the CHANGE log (2038 bug?) - This change log is just as an additional footnote, as it only concerns those using directly the API.

Changes between 1.1.0e and 1.1.1 [xx XXX xxxx]
*) Add the ASN.1 types INT32, UINT32, INT64, UINT64 and variants prefixed
       with Z.  These are meant to replace LONG and ZLONG and to be size safe.
       The use of LONG and ZLONG is discouraged and scheduled for deprecation
       in OpenSSL 1.2.0.

So, creating a certificate from the 1st of January 2008 to the 1st of January of 2010, can be done as:
openssl ca -config /path/to/myca.conf -in req.csr -out ourdomain.pem \
-startdate 200801010000Z -enddate 201001010000Z

or
openssl ca -config /path/to/myca.conf -in req.csr -out ourdomain.pem \
-startdate 0801010000Z -enddate 1001010000Z

-startdate and -enddate do appear in the openssl sources and CHANGE log; as @guntbert noted, while they do not appear in the main man openssl page, they also appear in man ca:

-startdate date
       this allows the start date to be explicitly set. The format of the date is
       YYMMDDHHMMSSZ (the same as an ASN1 UTCTime structure).

   -enddate date
       this allows the expiry date to be explicitly set. The format of the date is
       YYMMDDHHMMSSZ (the same as an ASN1 UTCTime structure).

Quoting openssl/CHANGE:

Changes between 0.9.3a and 0.9.4  [09 Aug 1999]
*) Fix -startdate and -enddate (which was missing) arguments to 'ca'
       program.

P.S. As for the chosen answer of the question you reference from StackExchange: it is generally a bad idea to change the system time, especially in production systems; and with the methods in this answer you do not need root privileges when using them.

A: I'm almost surprised to find that the obvious thing works: whereas openssl takes as an argument the number of days for which the certificate should be valid, just supply a negative number!
openssl req -x509 -newkey rsa:4096 \
    -keyout key.pem -out cert.pem -days -365

Note that this actually results in something very strange: a certificate whose expiry timestamp precedes its start-of-validity timestamp. I don't actually recommend that you use this for your automated testing, since it's weird. You probably want a way to back-date the start-of-validity timestamp as well.

A: Step-1. Install faketime
sudo apt-get install faketime

Step-2. Generate expired certificate a day before currentdate.
faketime 'last friday 5 pm' /bin/bash -c 'openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 6 -nodes'

Step-3 Verify the certificate validity date
openssl x509 -noout -text -in cert.pem


text:
Q: Let $E$ be finite dim ext of a field $F$and let $G$ be a gp of $F$-automorphisms of $E$ s.t $[E:F]=|G|$ Show that $F$ is the fixed field of $G$.
Question: Let $E$ be finite dimensional extension of a field $F$and let $G$ be a group of $F$-automorphisms of $E$ such that $[E:F]=|G|$.  Show that $F$ is the fixed field of $G$.
$\DeclareMathOperator{\Aut}{Aut}$

My Thoughts: Let $K=\mathcal F(\Aut(E/F))$, thus we have $\Aut(E/K)\subseteq\Aut(E/F)$, but since $F\subseteq K$, we have $\Aut(E/F)\subseteq\Aut(E/K)$, so we get equality. So,
$$
|\Aut(E/F)|=[E:F]\geq[E:K]=|\Aut(E/K)|=|\Aut(E/F)|.
$$
Thus $[E:F]=[E:K]$ so $K=F$ and so $F=\mathcal F(\Aut(E/F))$, and since $E$ is finite dimensional and $[E:F]=|G|$, we have $F=\mathcal F(G)$.
But I am questioning my first sentence and my last sentence.  I am trying to do this without resorting to too much Galois Theory, but any help is greatly appreciated!  Thank you.

A: Ah, I have found a reference for the only needed fact: Proving the number of K-automorphisms is bounded by the degree of the extension by considering field embeddings.
The linked question asks for a proof for the bounding $|\mathrm{Aut}(L/K)|$ from above by $[L:K]$. It is a rather elementary argument as it turns out. Anyway, I will freely use this fact now.
Back to your question. Consider $E/F$ finite and $G\subseteq\mathrm{Aut}(E/F)$ with $|G|=[E:F]$. We then have
$$
|G|\le|\mathrm{Aut}(E/\mathcal F(G))|\le[E:\mathcal F(G)]
$$
by definition of $\mathcal F(G)$ and using the fact from above. But, $[E:\mathcal F(G)]\le[E:F]$ and $|G|=[E:F]$ implying that $[E:\mathcal F(G)]=[E:F]$ which is only possible for $\mathcal F(G)=F$.

By the way: In this case we have also have $|\mathrm{Aut}(E/F)|=[E:F]$, by the given inclusions and bounds, implying at once that $E/F$ is actually a Galois extension (and $G$ its Galois group).

A: We can use the standard result that if $G$ is a finite subgroup of group of automorphisms of any field $E$ then the the fixed field $E_G$ of $G$ has the property that $[E:E_G] =|G|$. The proof of this result involves showing that $[E:E_G]$ is finite and does not exceed $|G|$. Once we know that the extension $E/E_G$ is finite we can apply a little bit of Galois theory to get $[E:E_G] =|G|$.
We are given that $F\subseteq E_G$ and thus we get $F\subseteq E_G\subseteq E$. Now you can use the tower law to get $$[E_G:F] =\frac{[E:F]} {[E:E_G]} =\frac{|G|} {|G|} =1$$ and thus $E_G=F$.


text:
Q: Reference error variable not define on Object forEach I am getting reference error w is not defined in forEach object.
this.primaryfilterdata is product json object.
this.primaryfilterdata =[{"id":"Brand","filterValues":[{"id":" FIDO DIDO","count":1,"meta":""},{"id":"addidas","count":1,"meta":""},{"id":"hrx","count":3,"meta":""},{"id":"nike","count":1,"meta":""},{"id":"polo","count":2,"meta":""}]},{"id":"fit","filterValues":[{"id":"28","count":3,"meta":null},{"id":"30","count":5,"meta":null},{"id":"32","count":4,"meta":null},{"id":"34","count":3,"meta":null}],"checked":[]},{"id":"color","filterValues":[{"id":"black","count":3,"meta":null},{"id":"orange","count":3,"meta":null},{"id":"red","count":5,"meta":null},{"id":"yellow","count":6,"meta":null}],"checked":[]},{"id":"size","filterValues":[{"id":"l","count":3,"meta":null},{"id":"m","count":5,"meta":null},{"id":"s","count":3,"meta":null},{"id":"x","count":3,"meta":null},{"id":"xl","count":2,"meta":null}],"checked":[]}]
Here is code

    var pfquery={}
    Object.keys(this.primaryfilterdata).forEach(function(key,index){
      var x=this.primaryfilterdata[key].filterValues
      var atrval=this.primaryfilterdata[key].id
      var w=[];
      Object.keys(x).forEach(function(key1,value){
        //console.log("Original array:", key1);
        var y=x[key1]
        if(y.checked) {
          w.push(y.id);
          pfquery[atrval]=[];
          pfquery[atrval].push(w);
        }
      })

    }.bind(this));

    console.log(pfquery)
    console.log(w)

A: By seeing your code, i believe you are trying to get an object(pfquery) as a result which hold the id of the brands which is checked/selected.
Output like this :
{"Brand":["FIDO DIDO", "nike"]}

first the console.log(w) is mentioned in the wrong place, out of scope. So remove that line, that's the reason you are getting this error.
And i believe the "checked" field in your json object is not mentioned in the right place, i think it should be mentioned inside all the brands filtervalues. then only your code check (if(y.checked)) will work/execute.
Below is the Sample JSON which you have to specify to make your code work properly.
this.primaryfilterdata =[{"id":"Brand","filterValues":[{"id":" FIDO DIDO","count":1,"meta":"", "checked": true},{"id":"addidas","count":1,"meta":"", "checked": true} ]}]

I hope this is what you are expecting to do.


text:
Q: Maya API to C++ I was reading about the Maya API to C++ and didn't quite understand the idea.
Upon implementing the API, Can I create an environment, or a GUI in 3D world in Visual Studio?
This question is related to my previous one about the Maya API.
Question
If someone could give me a good place to begin, it would be great.
Thanks,
Oded.

A: You can't create 3D environment outside the Maya,
as well as you can do anything inside Maya with the API.
I recommend that you start with Maya python API instead of c++ it's way easier, and takes less development time.
you may read the "Complete Maya Programming" book, its example written in c++, but if you know some python you can write them in python.

A: Maya API allows you to extend Maya, and you can choose to use either c++ or python (the python just wraps same API, more or less). Now the extension framework is meant for you to implement your own nodes, importers/exporters and motion capture devices, mostly. The GUI layer is reserved to scripting components and QT neither which are exactly Maya APIS domain, tough it gives you hooks to do with with the script environment or QT.
As for the exact question can you create a GUI yes you can get a handle to the QT framework, but as i previously said its not the realm of the API per see. And as for the environment yes you could do that its just not the sort of thing you'd do as your first project. You do almost anything you like, inside or even a connection outside of Maya however from a practical standpoint you'd still have to quite intimately know Maya before starting to do so. The API doesn't exactly allow you to do anything you like it has certain no bounds limitations and its not a good idea to fight Mayas run time environment.
If on the other hand you want to control things within Maya externally then make a node or a motion capture server, that's what they are meant for.
Personally i find the complete Maya programming book a bit misleading on all levels but yes you could use it as basis. Just not terribly fruitful for any of the tasks you ask for.


text:
Q: Making a new column using loop in xts in R I'm new to R and facing a sort of problem.
I have xts data and I would like to make a new column according to these values.
Example:
>head(x1)
>                      Values
>"2014-09-01 00:00:01" -0.1
>"2014-09-01 00:00:02" 0.05
>"2014-09-01 00:00:03" 0.01
>"2014-09-01 00:00:04" -0.03
>"2014-09-01 00:00:05" 0.01
>"2014-09-01 00:00:06" -0.001

I would like to add a new column something like:
>                     Values  Signs
>"2014-09-01 00:00:01"  -0.1 Negetive
>"2014-09-01 00:00:02" 0.05  Positive
>"2014-09-01 00:00:03" 0.01  Positive
>"2014-09-01 00:00:04" -0.03 Negative
>"2014-09-01 00:00:05" 0.01  Positive
>"2014-09-01 00:00:06"-0.001 Negative

I've been trying some ways like
>x2 <- apply(x1, MARGIN = 1,
+if(x1 > 0){
+           paste("Positive")
+          }else{
+                if(x1<0){
+                         paste("Negative")
+                        }
+               }
+           )

And it didn't work at all.
I know it's a very basic question but it's hard for me.
Thanks for any help.
When I did dput(head(sep4diff1)) (sep4diff1 is the real name of my data object), I got:
x1 <- structure(c(NA, -0.00200000000000955, -0.000999999999990564,
0, 0, 0, NA, 0.000999999999990564, -0.00199999999999534, 0, 0,
0), class = c("xts", "zoo"), .indexCLASS = c("POSIXct", "POSIXt"
), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", index
=structure(c(1409756400.675,
1409756401.938, 1409756402.414, 1409756403.173, 1409756404.173,
1409756405.173), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(6L,
2L), .Dimnames = list(NULL, c("Bid", "Ask")))

In the previous example there is just one column but actually I have two columns.
And value could be zero, so I have to make a column whose "Positive", "Negative" or "Zero".
Thanks in advance.


text:
Q: lxml order of attributes As stated in this question:
lxml preserves attributes order?
And taking the @abarnet suggestion I wrote the following line of code:
root = ET.Element('{%s}Catalogo' % SATNS, OrderedDict([("Ano","2014"),("Mes","02"),("TotalCtas","219"),("RFC","XXX010101XXX"),("Version","1.0")]), nsmap={'catalogocuentas':SATNS})

I get this:
<catalogocuentas:Catalogo xmlns:catalogocuentas="http://www.sat.gob.mx/catalogocuentas" Ano="2014" Mes="02" TotalCtas="219" RFC="XXX010101XXX" Version="1.0"/>

which is great(it preserves the desired order), but when I want to add the missing information:
xmlns:xsi="link_2" xsi:schemaLocation="http://www.sat.gob.mx/catalogocuentas"

as part of my xml and then I add this info in my python code:
attrib={location_attribute: 'http://www.sat.gob.mx/catalogocuentas'}

so that it becomes:
root = ET.Element('{%s}Catalogo' % SATNS, OrderedDict([("Ano","2014"),("Mes","02"),("TotalCtas","219"),("RFC","XXX010101XXX"),("Version","1.0")]), nsmap={'catalogocuentas':SATNS}, attrib={location_attribute: 'http://www.sat.gob.mx/catalogocuentas'})

I get this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "lxml.etree.pyx", line 2558, in lxml.etree.Element (src/lxml/lxml.etree.c:52829)
TypeError: Element() got multiple values for keyword argument 'attrib'

How can I fix it?
Thanks in advance!!

A: The problem is you are sending the Element() init method the same keyword argument twice. For your initialization your second argument is being used as the attrib keyword. Which in this instance is your OrderedDict() which contains all your attributes. You then try to supply it again which is where it runs into a collision. You can remedy this one of two ways:
You can add this attribute to your attribute OrderedDict() like so:
root = ET.Element('{%s}Catalogo' % SATNS, OrderedDict([("Ano","2014"),("Mes","02"),("TotalCtas","219"),("RFC","XXX010101XXX"),("Version","1.0"),("location_attribute","http://www.sat.gob.mx/catalogocuentas")]), nsmap={'catalogocuentas':SATNS})

Alternatively you could add it on the next line as well by doing this:
root.attrib["location_attribute"] = "http://www.sat.gob.mx/catalogocuentas"


text:
Q: Publish to Alfresco task programmatically I am using Activiti 1.9.03 and Alfresco 5.2.4 enterprise versions. I have a requirement where I have to maintain the version of the generated report document and also uploaded document (if user edits it). Right now After each user tasks, I am adding two Publish to Alfresco tasks. This is making the workflow diagram unreadable.
I want to know the following things.

*

*Is there any other way to handle versioning in Activiti instead of pushing the content to the Alfresco?

*How can I upload the content programatically using JAVA or Javascript task in a listener, so that I don't have to keep the Publish to Alfresco tasks in the workflow definition. OR

*Is there any way to hide the Publish to Alfresco tasks on the workflow diagram?
Any help will be appreciated...
Thank you

A: In APS,There are Services like AlfrescoService,AlfrescoContentService.
You can autowire those services in your Listner and you can use REST Call.


text:
Q: Perform action when user clicks on map or marker in react-google-maps I am trying to implement google maps in my react project using react-google-maps package.
The map is visible however I am not able to perform other event actions like onClick.
The documentation and examples are not useful as they are using recompose. However recompose is no longer needed due to release of hooks in React v16.
Below is the code, please point out what I am doing wrong.
Also tips of how to write hooks based code instead of recompose will be extremely helpful.
Also I am a React newbie, so might have made obvious mistake

function handleMarkerClick() {
  console.log("function called");
}

const MyMapComponent = withScriptjs(
  withGoogleMap(props => ( <GoogleMap defaultZoom = {13} defaultCenter = {{ lat: 19.1998, lng: 72.8426 }}>
  {props.isMarkerShown && ( <Marker position = { { lat: 19.1998, lng: 72.8426 }} onClick = { props.onMarkerClick } />)}
  </GoogleMap>
  ))
);

function Register() {
  return ( <Wrapper>
      <MyMapComponent isMarkerShown = { true }
      googleMapURL = "https://maps.googleapis.com/maps/api/js?key=*******&v=3.exp&libraries=geometry,drawing,places"
      loadingElement = { < div style = {
          {
            height: `100%`
          }
        }
        />}
        containerElement = { < div style = {
            {
              height: `100vh`
            }
          }
          />}
          mapElement = { < div style = {
              {
                height: `100%`
              }
            }
            />} / >
             < /
            Wrapper>
          );
        }

export default Register;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

A: You need to update the code like onClick = { (event) => { props.onMarkerClick (event) } } in Marker component then you get output lat and lang from event in handleMarkerClick(event) { console.log(event.latLng.lat())}


text:
Q: Can I make iTunes stop asking to access my phone? I plug my phone (iPhone 5s, though I doubt it matters) into my laptop at work in order to charge it. Every time I do, if iTunes is open (it usually is, because music), it pops up a dialog to ask if I want to allow iTunes to access information on the phone.
I don't, and I'm getting tired of clicking through the dialog every time. Is there a way to get it to stop asking, either for this specific device, or in general?

A: Get a "charge only" or "data block" lightning cable.
One example: https://www.amazon.com/dp/B01F7AU62E/ref=cm_sw_r_cp_api_FZmiAbB2FJDDE
These cables only let power thru, data is blocked or not connected.


text:
Q: Datagridview filtering blank I don't know if there's something wrong with the code, but every time I enter a value into the text box the datagridview doesn't filter, meaning it just goes blank as if it didn't find anything. can someone help me with the right code for when I insert text into the textbox, the datagridview filters for instance lets say I enter the letter "M" into the textbox, the the DGV display's all the words that start with M
heres my code
If TextBox1.TextLength > 0 Then
        frmReportMenu.ProjectBindingSource.Filter = String.Format_
("[Register number] Like '&" & TextBox1.Text) & "&'"
    Else
        frmReportMenu.ProjectBindingSource.Filter = String.Empty
    End If

I cannot find anything to properly filter the data

A: I think your wildcard character is wrong.  Try using a * instead of the &
frmReportMenu.ProjectBindingSource.Filter = String.Format_
("[Register number] Like '*" & TextBox1.Text & "*'")


text:
Q: Detail view in Visual studio 2010 I have a detail view control in my aspx form.
I have the following field in my detail view:
NameId
Name
ContactNo
But i dont want to allow the user to edit the "NameId" field.
So i set it as READ ONLY and INSERT VISIBLE.
But setting it dosent allow me to update.
If all the fields are set to be allow for editing, the update work successfully.
How should i go about doing it?

A: Are you trying to pass that NameID field in the UpdateCommand?
Setting the field to ReadOnly=True won't pass the value to the underlying datasource.  So you may need to remove that field from the UpdateCommand.
See this link for some more information:
http://weblogs.asp.net/istofix/archive/2008/12/31/tips-amp-tricks-details-view-and-read-only-fields.aspx


text:
Q: Flex-box layout make no-stretching raw Is it possible to make dynamic content from database  not to stretch on height in wrapping raws. Here is what I've achieved.

.main-raw {
  width: 250px;
  height: 100%;
   display: -webkit-flex;
   display: flex;
   -webkit-justify-content: center;
   justify-content: center;
   -webkit-flex-direction: row;
   flex-direction: row;
   -webkit-flex-wrap: wrap;
   flex-wrap: wrap;
   -webkit-flex-flow: row wrap;
   flex-flow: row wrap;
   -webkit-align-content: flex-end;
   align-content: flex-end;
}

.item-1, .item-2, .item-3  {
  width: 100px;
  margin: 3px;
  background-color: black;
}

.item-1 {
  height: 100px;
}

.item-2 {
  height: 200px;
}

.item-3 {
  height: 150px;
}

&nbsp

&nbsp

&nbsp

And here is what I am looking for:

A: wasn't too sure by what you meant, when you said 'not stretch on height'
but I contained the elements in there own wrappers in order to properly position them.

&nbsp

&nbsp

&nbsp

&nbsp

&nbsp

&nbsp

here is an example:
https://jsfiddle.net/ax0mfc0p/2/


text:
Q: Universal Language Dictionary I want to create an efficient data structure that scales such that given two translations, say, (Hello, English, German, Hallo) and  (German, Hallo, French, Bonjour,) I'm able to quickly retrieve, How to say Hello, English in French. And also, if I only know Hallo, German, I'm able to retrieve it English through get_translation(hallo, german, english), despite the input mapping I provided only being from English to German and not vice-versa.
so given inputs (lang1, word1, lang2, word2) and (lang2, word2, lang3, word3) , the function will quickly return for args (lang1, word1, lang3) --> word3, despite us not having created the mapping for the word from lang1 to lang3.
What kind of hash map, graph hybrid could possible make for the cleanest solution here? I'm trying both be able to traverse a graph, and preserver O(1) look up.

A: how about:
{"hello":{"german":"hallo", "french": "bonjour"}}


text:
Q: Typescript object literal https://www.typescriptlang.org/docs/handbook/interfaces.html has this example:
interface LabeledValue {
  label: string;
}

function printLabel(labeledObj: LabeledValue) {
  console.log(labeledObj.label);
}

let myObj = { size: 10, label: "Size 10 Object" };
printLabel(myObj);

But if I pass an object literal to printLabel, instead of myObj, like so:
printLabel({ size: 10, label: "Size 10 Object" })

then  I get an error
>  error TS2345: Argument of type '{ size: number; label: string; }' is
> not assignable to parameter of type 'LabeledValue'.   Object literal
> may only specify known properties, and 'size' does not exist in type
> 'LabeledValue'.
>
> 11 printLabel({ size: 10, label: "Size 10 Object" });

Why is this? Why is this behavior different ?

A: As { size: 10, label: "Size 10 Object" } is a object literal.
When it comes to whether a ts object literal is assignable to another , it will compare the whole properties. Here, label is not acceptable.


text:
Q: How can i debug a xform submission? i'm having trouble debbuging an xform in a xhtml file. Previously it was working, but now i changed something in the namespaces of the xf:model and now when i press the submit button it doesn't do anything. I'll give a simple example in order for you to better understand my issue, but keep in mind that i'm working in a xhtml file with 400+ lines and i've been losing hours (almost 40 hours in the last week) debugging line by line, and trial and error to find out what's wrong with my forms.

       <title>Example</title>
       <xf:model schema="foobar.xsd">
         <xf:instance>
            <Persons xmlns="">
               <name></name>
            </Persons>
         <xf:/instance>
       </xf:model>
       <xf:bind id=name nodeset="/Person/aluno" type="xs:string"/>
       <xf:submission id="submit" action="http://localhost:8080/exist/rest/db/apps/foo/bar.xquery" method="post"/>

Type the name of the Person

      <xf:input bind="name">
       <xf:label>
                Name:
       </xf:label>
      </xf:input>
      <xf:submit submission="submit">
        <xf:label>SUBMIT</xf:label>
      </xf:submit>

Ok, this is a simple example (it can have some errors, doesn't matter), but imagine that everytime i press SUBMIT it doesn't do anything. How can i find what is causing the error?

A: @loveMeansNothing following the error message: "Unknown XML root element: wiki:article_container" you haven't declared the namespace xmlns:wiki="http://www.generic-wiki.org/Wiki" on the 'html' element? Further you are missing the xforms @replace attribute on your submission which means it defaults to replace="all" (following the XForms W3C recommendation), have you tried to use @repalce="none" or @replace="instance" here (depending on what you want to archive)?
Regarding debugging of betterFORM @adamretter already pointed out where to find the logs and how the enable the debug bar. Further you could add a xforms-submit-error handler to your submission:
<xf:submission id="..." ...>
  <xf:action ev:event="xforms-submit-error">
    <xf:message>Submit Error! Resource-uri: <xf:output value="event('resource-uri')"/>
                Response-reason-phrase: <xf:output value="event('response-reason-phrase')"/>
    </xf:message>
  </xf:action>
</xf:submission>

and I often use Firebug for debugging purposes.
If this all doesn't solve your issue it would be great to have a running example of your form to reproduce the error.

A: Finally i've found the solution!
It was missing a stupid slash on the xquery called by the
      <xf:submission id="submit" action="http://localhost:8080/exist/rest/db/apps/myapp/logic/action.xquery" method="post"/>

if looked like this:
let $store:=xmldb:store('db/apps/myapp/data','test.xml', $newArticle)

while it should look this (see the slash):
let $store:=xmldb:store('/db/apps/myapp/data','test.xml', $newArticle)

Also i've created a new user and added him to the 'dba' group throught the exist-db Java Admin Client. After that i've created a the new application on exide using the new username credentials. Also used that user here:
   let $login:=xmldb:login('/db/apps/myapp','user','password')

Thanks for the help people :)


text:
Q: What's a word to call a person who is involuntarily used? In an interaction, one person uses another against their will. Is there a word (noun) to refer to that person?
Example: Person A trips and grabs onto Person B, a stranger, in order to not fall to the ground. Person B had no choice in the matter. Person A would label Person B their _____.
Dupe, instrument, pawn, puppet, stooge, and tool have pretty negative connotations, so don't quite work. The interaction is more of a slight inconvenience.

A: One who saves from danger is a saviour (American savior).

savior = one that saves from danger or destruction
Merriam Webster

The question then arises: can a savior be involuntary?
Merriam Webster continues with an example "the policeman proved to be our savior, arriving on the scene just as we were about to be mugged". The policemen may easily have arrived by chance, making him an involuntary savior.
Another example where the savior is most certainly involuntary (even inimical) is:

James Murdoch wants to blow up the BBC. He could yet turn out to be its unwitting saviour.
Financial Times

"Oops! Sorry! I nearly fell in the mud. You are my saviour."

A: You are my (a):
Lifesaver
a thing that saves one from serious difficulty. Also, a person who rescues another from danger of death, especially from drowning. a person or thing that saves a person, as from a difficult situation or critical moment: That money was a lifesaver (www.dictionary.com › browse › lifesaver
).
Can also be used in a non-literal sense such as:
Guardian Angel
a spirit who is believed to protect and help a particular person (https://dictionary.cambridge.org/dictionary/english/guardian-angel)' or;
Knight in shining armour
https://dictionary.cambridge.org/dictionary/english/a-knight-in-shining-armour?topic=preserving-and-saving
More tentatively: http://onlineslangdictionary.com/meaning-definition-of/save-(one%27s)-butt

A: If it doesn't have to be possessive, maybe "solid" would work.  Literally true and metaphorically fitting for the example.  In this case, the involuntary use is just "using" the body as a solid.

"You're solid, thanks."

"Dude, you're solid."

"You're my solid"

Last one just doesn't flow off the tongue as well