text:
Q: SocketTimeoutException during signing process We have some trouble with our automated maven build process. From time to time the build is broken by the signing process of install4j. Sometimes it works very well sometimes we get the following exception:
...
[15:51:29] :         [myapp] [INFO]     Compiling launcher 'Standalone updater':
[15:51:29] :         [myapp] [INFO]       replaced variable 'launcher.name' with 'MyApp' in string '${compiler:launcher.name} Update'
[15:51:29] :         [myapp] [INFO]       using icon file D:\BuildAgent7\work\1c0ed506bc73bcb4\target\install4j\resource\updater.ico
[15:51:29] :         [myapp] [INFO]       replaced variable 'sys.fullName' with 'My Application' in string 'Starts the ${compiler:sys.fullName} update'
[15:51:29] :         [myapp] [INFO]       Creating GUI mode application.
[15:51:29] :         [myapp] [INFO]       Signing executable
[15:51:37] :         [myapp] [INFO]   Creating media file:
[15:51:37] :         [myapp] [INFO]     replaced variable 'launcher.name' with 'MyApp' in string '${compiler:launcher.name} Uninstall'
[15:51:37] :         [myapp] [INFO]     output file is D:\BuildAgent7\temp\buildTmp\install4j374202026546155444_dir\set1\launcheruninstaller\app.ico
[15:51:37] :         [myapp] [INFO]     replaced variable 'sys.fullName' with 'My Application' in string 'Remove the ${compiler:sys.fullName} installation'
[15:51:37] :         [myapp] [INFO]     Creating GUI mode application.
[15:51:37] :         [myapp] [INFO]     Signing executable
[15:51:47] :         [myapp] [INFO] com.a.a.d: error during counter signing
[15:51:47] :         [myapp] [INFO]     at com.install4j.c.b.d.a(ejt:137)
[15:51:47] :         [myapp] [INFO]     at com.install4j.c.b.d.a(ejt:94)
[15:51:47] :         [myapp] [INFO]     at com.install4j.c.b.g.a(ejt:68)
[15:51:47] :         [myapp] [INFO]     at com.install4j.b.g.c.a(ejt:189)
[15:51:47] :         [myapp] [INFO]     at com.install4j.b.g.c.a(ejt:82)
[15:51:47] :         [myapp] [INFO]     at com.install4j.b.g.g.a(ejt:60)
[15:51:47] :         [myapp] [INFO]     at com.install4j.b.b.d(ejt:392)
[15:51:47] :         [myapp] [INFO]     at com.install4j.b.b.c(ejt:360)
[15:51:47] :         [myapp] [INFO]     at com.install4j.b.b.a(ejt:135)
[15:51:47] :         [myapp] [INFO]     at com.install4j.b.h.a(ejt:440)
[15:51:47] :         [myapp] [INFO]     at com.install4j.b.h.a(ejt:214)
[15:51:47] :         [myapp] [INFO]     at com.install4j.b.h.d(ejt:106)
[15:51:47] :         [myapp] [INFO]     at com.install4j.Install4JApplication.c(ejt:436)
[15:51:47] :         [myapp] [INFO]     at com.a.a.a(ejt:286)
[15:51:47] :         [myapp] [INFO]     at com.install4j.Install4JApplication.main(ejt:93)
[15:51:47] :         [myapp] [INFO]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[15:51:47] :         [myapp] [INFO]     at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at java.lang.reflect.Method.invoke(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at com.exe4j.runtime.LauncherEngine.launch(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at com.exe4j.runtime.WinLauncher.main(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at com.install4j.runtime.launcher.WinLauncher.main(Unknown Source)
[15:51:47] :         [myapp] [INFO] Caused by: java.io.IOException: Read timed out
[15:51:47] :         [myapp] [INFO] You can set a different timestamp signing service by setting the VM parameter -Dinstall4j.timestampUrl=http://... in bin/install4j.vmoptions
[15:51:47] :         [myapp] [INFO]     at com.install4j.c.b.d.b(ejt:174)
[15:51:47] :         [myapp] [INFO]     at com.install4j.c.b.d.a(ejt:110)
[15:51:47] :         [myapp] [INFO]     ... 21 more
[15:51:47] :         [myapp] [INFO] Caused by: java.net.SocketTimeoutException: Read timed out
[15:51:47] :         [myapp] [INFO]     at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
[15:51:47] :         [myapp] [INFO]     at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at java.lang.reflect.Constructor.newInstance(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at sun.net.www.protocol.http.HttpURLConnection$6.run(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at sun.net.www.protocol.http.HttpURLConnection$6.run(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at java.security.AccessController.doPrivileged(Native Method)
[15:51:47] :         [myapp] [INFO]     at sun.net.www.protocol.http.HttpURLConnection.getChainedException(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at com.install4j.runtime.installer.helper.content.Downloader.connect(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at com.install4j.c.b.d.b(ejt:156)
[15:51:47] :         [myapp] [INFO]     ... 22 more
[15:51:47] :         [myapp] [INFO] Caused by: java.net.SocketTimeoutException: Read timed out
[15:51:47] :         [myapp] [INFO]     at java.net.SocketInputStream.socketRead0(Native Method)
[15:51:47] :         [myapp] [INFO]     at java.net.SocketInputStream.read(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at java.net.SocketInputStream.read(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at java.io.BufferedInputStream.fill(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at java.io.BufferedInputStream.read1(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at java.io.BufferedInputStream.read(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at sun.net.www.protocol.http.HttpURLConnection.getHeaderField(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at java.net.URLConnection.getHeaderFieldLong(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at java.net.URLConnection.getContentLengthLong(Unknown Source)
[15:51:47] :         [myapp] [INFO]     at java.net.URLConnection.getContentLength(Unknown Source)
[15:51:47] :         [myapp] [INFO]     ... 24 more
[15:51:47] :         [myapp] [INFO] install4j: compilation failed. Reason: error during counter signing
[15:51:47] :         [myapp] [Maven Watcher]
[15:51:47]E:         [myapp] Failed to execute goal org.sonatype.install4j:install4j-maven-plugin:1.0.5:compile (build-installer) on project myapp: null returned: 1
...

That's a problem to stabilize our continuous build. The SocketTimeoutException leads me to the conclusion of a missing connection to the verisign server. But for the updater there was already a connection during signing execution. Now I am not sure if this may be a problem of our build environment or the signing process of install4j itself. What value is set as the default for the connection timeout? Is it possible to override this value?
For the signing we are using a pfx-file and install4j with version 5.1.12.

A: The read timeout is set to 10000 milliseconds by default. You can increase it by adding the line
-Dinstall4j.readTimeout=20000

to the file bin/install4j.vmoptions in your install4j installation.
Just for reference, there is a similar VM parameter install4j.connectTimeout for the connect timeout, also with a default value of 10000 ms.

Update (2014-11-20):
Since install4j 6.0, a failed counter signature is retried 10 times with a pause of 3 seconds. The maximum number of retries can be increased with the VM parameter
-Dinstall4j.counterSignRetry=20


text:
Q: If $b$ is tautology and $c$ is contradiction why isn't $a\to (b\to c)$ a contradiction?
Let $a$ be neither tautology nor contradiction, $b$ is tautology and $c$ is contradiction . What is the value of $a\to (b\to c)$?

It's a multiple choice question where there're following options:

*

*the expression is a contradiction

*the expression is equivalent to the negation of $a$
The second answer is correct but I don't understand why. $b\to c$ is always false. Therefore $a\to (b\to c)$ is always false. So why isn't it a contradiction?
I derived my conclusion by using the truth table in this Wikipedia article.

A: $(b→c)$  is FALSE because - being $b$ a tautology, i.e. always TRUE, and $c$ a contradiction, i.e. always FALSE, it is :

(TRUE → FALSE), i.e. FALSE.

But $a$ can be either TRUE or FALSE.
Thus $a→(b→c)$ can be either (TRUE → FALSE) or (FALSE → FALSE).
More specifically, we have that :

$a→(b→c)$ is $a \to$ FALSE.

Thus, when $a$ is TRUE, we have that  $(a \to$ FALSE) is FALSE, and when $a$ is FALSE, $(a \to$ FALSE) is TRUE.
Thus :

$a→(b→c)$ is equivalent to $\lnot a$.

A: Your error is here.
$b\to c$ is always false. CORRECT
Therefore $a\to (b\to c)$ is always false.  INCORRECT

A: $b \to c$ has its truth value specified because $b$ and $c$ each have their truth value specified. By definition $\top \to \bot$ is false, so you have $a \to \bot$ which is by definition equivalent to $\neg a$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What does the EXE do in the Visual Studio setup project output We are working on a winforms app in Visual Studio 2005 and the setup project we created output both an MSI and an EXE.  We aren't sure what the EXE file is used for because we are able to install without the EXE.

A: It's a bootstrapper that checks to make sure that the .NET Framework is installed, before launching the MSI. It's pretty handy.
I suggest using something like SFX Compiler to package the two together into one self-extracting .exe and then launch the extracted setup.exe. This way you retain the benefits of the bootstrapper, but your users only download a single thing.
Edit: also see

*

*The official line: MSDN documentation

*Some bootstrapper customization: some guy's blog post about what he did

A: The EXE checks if Windows Installer 3.0 is present and downloads and installs it if it's not. It's needed only for Windows 2000 or older. Windows XP and newer all have Windows Installer 3.0 out of the box.
Other prerequisites, like .NET, are checked for by the MSI itself.

A: I think the EXE is just a wrapper/bootstrapper for the MSI in case you don't have Window Installer. If you have the requisite Windows Installer version installed then the MSI should work fine on its own.


text:
Q: date minus another date in xslt Hope someone can help. I am trying to compare 2 dates inside an XML file and using a XSLT to do some calculation:
For example I have 2 dates in XML: 2011-05-23 and 2011-04-29. I want to do calculation inside XSLT like below:
('2011-05-23'-'2011-04-29')*30 = 24*30= 720
Can anyone shed any light?

A: An XSLT 2.0 solution
<?xml version="1.0"?>
<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xsl:template match="/">
<xsl:value-of select="days-from-duration(
                                         xs:date('2011-05-23')
                                         - xs:date(xs:date('2011-04-29'))
                      )*30"/>
</xsl:template>
</xsl:stylesheet>

Yields: 720

*

*xs:date() function evaluates the dates, which can be used to perform date operations

*subtracting the second date from the first yields the xdt:dayTimeDuration P24D (24 days)

*days-from-duration() extracts the days component from the xdt:dayTimeDuration (24)

*then you can use that number to perform normal arethmatic (e.g. 24*30=720)

A: It might be worth looking at the EXSLT - date:difference solution. I believe that should do what you want, and there's even a straight XSLT implementation available.
Be aware though that the returned value is in duration format as specified in the XML Schema Part 2: Datatypes Second Edition, so it's likely you will need to process the result to derive the unit you wish to use in calculation (for instance in your example above you're expecting a result detailing the number of days difference - so you would need to pull out the relevant unit you want to work with, the result from date:difference in that case would most likely be "P24D").

A: Here's two templates I sometimes use for date calculations:
<xsl:template name="calcseconds">
  <xsl:param name="date" />
  <xsl:value-of select="(((substring($date,1,4) - 1970) * 365)+floor((substring($date,1,4) - 1970) div 4)+substring('000,031,059,090,120,151,181,212,243,273,304,334,365',substring($date,6,2)*4-3,3)+(substring($date,9,2)-1)+(1-floor(((substring($date,1,4) mod 4) + 2) div 3))*floor((substring($date,6,2)+17) div 20))*86400+(substring($date,12,2)*3600)+(substring($date,15,2)*60)+substring($date,18,2)" />
</xsl:template>

<xsl:template name="calcdays">
  <xsl:param name="date" />
  <xsl:value-of select="(((substring($date,1,4) - 1970) * 365)+floor((substring($date,1,4) - 1970) div 4)+substring('000,031,059,090,120,151,181,212,243,273,304,334,365',substring($date,6,2)*4-3,3)+(substring($date,9,2)-1)+(1-floor(((substring($date,1,4) mod 4) + 2) div 3))*floor((substring($date,6,2)+17) div 20))" />
</xsl:template>

They're a bit of a mouthful, but they'll calculate the number of seconds/days since midnight 1st January 1970 as an integer, which you can then do straight arithmetic on. They rely on the date format being yyyy-mm-dd hh:mm:ss, but manipulation of the parameters of the substring calls should allow you to process dates in any format you need.


text:
Q: Can you figure out why section 2 is going behind the video? Section 2 is going behind my video background. Resizing the browser messes everything up.
I really don't know CSS, so?
HTML:

    <video autoplay muted id="myVideo">
        <source src="Images/banner.mp4" type="video/mp4">
    </video>

        "*"

 Section 2
 jb
 jb
 jb
 jb
 jb
 jb
 jb
 jb
 jb
 jb

I have it so some text types out a few small sentences over a video.
CSS:
body {
  background-color: black;
  text-align: center;
  color: #FFF;
  /* padding-top: 10em; */
}
* {
    color: #FFF;
    text-decoration: none;
    font-family: 'CustomFont';
    font-weight: 80;
    font-size: 80px;
}

#slide {
  background-color: red;
  padding: 0;
  position: absolute;
}

/* Style the video: 100% width and height to cover the entire window */
#myVideo {
  position: absolute;
  right: 0;
  bottom: 0;
  min-width: 100%;
  min-height: 100%;
  overflow: hidden;
}

/* Add some content at the bottom of the video/page */
.content {
  overflow: hidden;
  position: absolute;
  font-size: 800;
  font-family: 'CustomFont';
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  color: #F1F1F1;
  width: 100%;
  padding: 0px;
}

A: The video tag is on top of other elements by default, and you can send it to back by:
#myVideo {
  z-index: -1;
}

body {
  background-color: black;
  text-align: center;
  color: #fff;
  /* padding-top: 10em; */
}

* {
  color: #fff;
  text-decoration: none;
  font-family: 'CustomFont';
  font-weight: 80;
  font-size: 80px;
}

#slide {
  background-color: red;
  padding: 0;
  position: absolute;
}

/* Style the video: 100% width and height to cover the entire window */

#myVideo {
  position: absolute;
  right: 0;
  bottom: 0;
  min-width: 100%;
  min-height: 100%;
  overflow: hidden;
}

/* Add some content at the bottom of the video/page */

.content {
  overflow: hidden;
  position: absolute;
  font-size: 800;
  font-family: 'CustomFont';
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #f1f1f1;
  width: 100%;
  padding: 0px;
}

#myVideo {
  z-index: -1;
}

<video autoplay muted id="myVideo">
   <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
</video>

   "*"

 Section 2
 jb
 jb
 jb
 jb
 jb
 jb
 jb
 jb
 jb
 jb

You can also see it here.


text:
Q: Magento 2 - How to create a custom product listing grid in admin?
I want to create a custom page for product listing in admin like the image using my custom module. How could i do that? If anyone have any solution please lighten me up.


text:
Q: How can I found the circles on image avoiding the internal circles? How can I found the circles on image using the method minEnclosingCircle but avoid the internal circles?
I'm using the opencv with c++ to detect circles on a image. I was using the method HoughCircles but sometimes it lost some circles or it detected false circles.
Therefore I'm replacing it for the minEnclosingCircle. Now the algorithm is finding all circles, but in some cases it found circles inside other circles and I want avoid this.
The image 1 is a example of input and the image 2 is it output.

The code used to process those images is this:
Start of code:

vector < Circle > houghCircles(Mat thresholdImage, float minRadius, float maxRadiuss) {

  vector < vector < Point > > contours;
  vector < Vec4i > hierarchy;

  findContours(thresholdImage, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));

  vector < vector < Point > > contours_poly(contours.size());
  vector < Circle > circlesTMP(contours.size());
  for (int i = 0; i < contours.size(); i++) {

    Point2f detectedCenter;
    float detectedRadius;

    approxPolyDP(Mat(contours[i]), contours_poly[i], 3, true);
    minEnclosingCircle((Mat) contours_poly[i], detectedCenter, detectedRadius);

    if (minRadius != 0 && detectedRadius < minRadius) {
      continue;
    }
    if (maxRadiuss != 0 && detectedRadius > maxRadiuss) {
      continue;
    }

    sf::Circle _circle(detectedCenter, detectedRadius);
    circlesTMP.push_back(_circle);
  }

  vector < Circle > circles;
  for (int i = 0; i < circlesTMP.size(); i++) {
    sf::Circle _circle = circlesTMP[i];
    if (_circle.getRadius() > 0) {
      circles.push_back(circlesTMP[i]);
    }
  }

  cout << "Circles found: " << circles.size() << endl;
  Mat drawing = Mat::zeros(thresholdImage.size(), CV_8UC3);
  for (int i = 0; i < circles.size(); i++) {
    sf::Circle _circle = circles[i];
    Scalar color = Scalar(200, 187, 255);
    circle(drawing, _circle.getCenter(), (int) _circle.getRadius(), color, 2, 8, 0);
  }

  imshow(drawing, "OpenCVUtil");
  waitkey();

  return circles;
}

A: you can check this link out and change your mode parameter and test your code:
http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=findcontours#findcontours
check out the results you obtain for CV_RETR_EXTERNAL instead of CV_RETR_TREE as the mode.


text:
Q: Error when using a generic type with a constraint in Typescript - 2536 I have the following types:
interface IFilterField <T extends FilterFieldValue > {
    defaultValue: T
    displayStr?: string
}

interface IFilterFields = {
   costMax: IFilterField<number>
   costMin: IFilterField<number>
   .....
}>

When I try to type an object that will link between the filterField and the type of its` value, this works:
export type IFiltersState<FiltersKeys extends keyof IFilterFields> = {
    [K in keyof FiltersKeys]: IFilterFields["costMin"|"costMax"]["defaultValue"]

}
But this fails:
export type IFiltersState<FiltersKeys extends keyof IFilterFields> = {
   [K in keyof FiltersKeys]: IFilterFields[K]["defaultValue"]
}

Even though the constraint is pretty much the same.
Error:
[ts] Type 'K' cannot be used to index type 'IFilterFields'. [2536]
[ts] Type '"defaultValue"' cannot be used to index type 'IFilterFields[K]'. [2536]

Why is this error occuring?
How can I acheive the purpose of a mapped type, which follows this principles: A new type T2 has some of the keys of type T1, and for each such key typeof T1[key] equals typeof T2[key][SomeFieldName]?

A: I found my error. Since FiltersKeys is already a union of keys/strings, there is a reduntand keyof in [K in keyof IfilterFields].

A: Because FiltersKeys is extended from IFilterFields, therefore it could contain different keys. You can use
export type IFiltersState<FiltersKeys extends keyof IFilterFields> = {
    [K in keyof IFilterFields]: IFilterFields[K]["defaultValue"]
}


text:
Q: An example of two random variables that are mean independent but not independent In probability theory class I was asked the following question:

Let X,Y be two random variables (could be discrete or continuous) such that they are mean independent, that is for all $ y \in \mathbb{R} $ we have the equality:
  $ E[X|Y=y] = E[X] $ and we are asked to prove or give a counterexample that X and Y are independent random variables.

I figured since I tried to prove it but could not succeed so I am inclined to think that it is false but I cannot find a counterexample. Could someone then please provide an example of random variables that are dependent but mean independent? Thank you all.

A: Pick $Y$ uniformly from $[0,1]$. Then pick $X$ uniformly from $[-y,y]$.
Then $E(X)=0$ and $E(X\mid Y=y)=0$, but $P\left(X<\frac{-1}{2}\mid Y=\frac{1}{4}\right)=0$, and $P\left(X<\frac{-1}{2}\right)=\frac{1}{8}$, so they are not independent.
In general, pick $Y$ first, and then let $Y$ determine a distribution for $X$ with the same mean.
For example, the case given by comments above, of picking $X$ uniformly from $(-1,1)$ and $Y=X^2$ can be seen this way - first pick $Y$ from $(0,1)$ with $P(Y<y)=\sqrt{y}$ and then pick $X$ uniformly from $-\sqrt{Y}$ or $\sqrt{Y}$.


text:
Q: Probabilistic Treasure hunt game I am designing a treasure hunt game where users start of at a fixed number of steps (x) away from the treasure. The user responses are either a or b. A correct answer places the user one step closer to the treasure, a wrong answer takes the user one step away from the treasure. (maximum steps away from the treasure is x.). The two options have a 50% chance of being right on each question.
The Game ends when player is 0 steps from the treasure.
Is it correct that the user will always get to the treasure in 2x moves? Or is it 2^x (2 power x)?
Is there anything a player can do to increase their chances of winning? Is there a way I  can make the game harder. (Apart from increasing x)?
Please keep the answer simple.

A: The stochastic process you are describing is well known to be a random walk. I know OP said that he doesn't know about stochastic processes, but for the audience, consider the transition matrix in his problem, with state space $\{0,1,\cdots,x\}$ :
$$
P = \underset{x+1 \text{ columns }}{\underbrace{\begin{pmatrix}
1/2 & 1/2 & 0 & \cdots & 0 \\
1/2 & 0 & 1/2 & 0 & \vdots \\
0 & 1/2 & 0 & \ddots & \vdots \\
\vdots & \vdots & \ddots & \ddots & \vdots \\
0 & \cdots & \cdots & 0 & 1 \\
\end{pmatrix}
}}
$$
From this matrix we get the matrix $Q$ of probabilities in transient states :
$$
Q = \underset{x \text{ columns }}{\underbrace{
\begin{pmatrix}
1/2 & 1/2 & 0 & \cdots & 0 \\
1/2 & 0 & 1/2 & 0 & \vdots \\
0 & 1/2 & 0 & \ddots & \vdots \\
\vdots & \vdots & \ddots & \ddots & 1/2 \\
0 & \cdots & \cdots & 1/2 & 0 \\
\end{pmatrix}
}}
$$
and thus the fundamental matrix becomes the inverse of
$$
I-Q = \begin{pmatrix}
1/2 & -1/2 & 0 & \cdots & 0 \\
-1/2 & 1 & -1/2 & 0 & \vdots \\
0 & -1/2 & 1 & \ddots & \vdots \\
\vdots & \vdots & \ddots & \ddots & -1/2 \\
0 & \cdots & \cdots & -1/2 & 1 \\
\end{pmatrix}
$$
One can guess by looking at the inverses of the matrix for small $x$ (using a computer to compute inverses for greater $x$ if his eyes are blind) that
$$
(I-Q)^{-1} = \begin{pmatrix}
2x & 2(x-1) & 2(x-2) & \cdots & 2 \\
2(x-1) & 2(x-1) & 2(x-2) & \cdots & \vdots \\
2(x-2) & 2(x-2) & 2(x-2) & \ddots & \vdots \\
\vdots & \vdots & \ddots & \ddots & 2 \\
2 & \cdots & \cdots & 2 & 2 \\
\end{pmatrix}
$$
which means that the expected number of steps to go from $0$ to $x$ is
$$
\sum_{k=1}^x 2k = 2\frac{x(x+1)}2 = x^2 + x.
$$
Furthermore, if it is of interest in your case, if your player has reached state $n$ and you want to know the expected number of steps before he reaches state $x$, that would be
$$
\sum_{k=1}^n 2k + (x-n)2n = 2n(x-n) + n^2 + n.
$$
Hope that helps,

A: It may happen that the (2k) first answers are abababa... in which case you will not have reached 0 after (2k) steps, hence no uniform deterministic bound on the time needed to reach 0 can hold. But the expected time needed to reach 0 starting from x is x^2+x (this can be explained rather elementarily if you wish).
If the probabilities of a step in each direction are the same at each site but unequal, the expected time becomes linear in x if the chances to make a step towards 0 are more than 50% but it becomes exponential in x if the chances to make a step towards 0 are less than 50% (and I guess some physicists would call this a phase transition).

A: I hope I understand your problem correct. On each step the right answer is either $a$ or $b$ with probability $0.5$ - so the player can be at positions $0,1,2,...,x$.
First of all, player cannot do anything here since his choice does no influence at all - the random number generator in average will do the same. Second, there is always non-zero probability not to find the treasure in $n$ steps, no matter how great is $n$. Third, to make the game more harder you may want to make it more interesting - namely incorporate the nice dependence on the player's decisions.


text:
Q: User action for send oush notifications in firebase on android Is possible to send push notifications with firebase without using the console,I mean can I send a push notifications when some user makes some action in the app?

A:
Is possible to send push notifications with firebase without using the
  console

Yes you can use Firebase API

I mean can I send a push notifications when some user makes some
  action in the app?

You can subscribe to a topic when user makes some action in the app
FirebaseMessaging.getInstance().subscribeToTopic("news");

and send a notification from Firebase web console or use Firebase API to all topic subscribers.

A: You can send a message to a topic from the Firebase Cloud Messaging API.
But this requires the use of your FCM server key, which means it should only be done from an app server. You should never embed your server key in the client-side app. This means that direct device-to-device notifications are not possible at the moment, you will always need an app server for that.
For a tutorial explaining one possible scenario, see: https://firebase.googleblog.com/2016/08/sending-notifications-between-android.html


text:
Q: How does Multiple Active Result Set (MARS) work in SQL Server? Just wondering if someone could explain how Multiple Active Result Set (MARS) works in SQL Server as it is not very clear on the MSDN site.
(A) On a MARS connection, do queries execute async or do requests go in async but still execute sequentially?
(B) What is the difference when executing 10 threads that call 1 stored proc concurrently in the following scenarios:

*

*using 1 MARS connection for all threads (that implicitly creates 10 sessions)

*using 10 connections (1 for each thread)?

(C) If using a MARS connection how do you see what SQL each session is executing?

A: This answers all your questions.
A. Queries execute in parallel, as if multiple clients had connected and executed them, only now you can do this from a single connection. Apparently the actual way its processed is "complicated", but as far as a client is concerned, they run simultaneously.
B. The difference between 1 connection or 10 connections is shared server resources. You only need a single security context for example.
C. Use SQLServer Profiler.

A: Just want to a bit clarify to the first point of the accepted answer, from the same resourse

The third thing you need to understand is that multiple active requests are not actually running in parallel, they are running in an interleaving way. From client application point of view, server supports running multiple requests in parallel, and client can pull result from multiple requests at their will. But at server, out of multiple requests sent to server, only one request can actually make progress at a given time, other requests have to wait for this request to give up its connection resource.


text:
Q: How do I sync a Git-Svn clone through cron?
For reference, I'm running CentOS 5.5 on the server.

I'm working on a distributed project with several other developers, and we're using Git to manage our repositories.  Everything's hosted live on Gitorious and working beautifully.  However, we need a branch in our repository to stay synchronized with an external Subversion repo - kind of like a "vendor branch" within Git.  Reason is: we're building several things based on this existing open source project (WordPress) and want our working copy to inherit any bugfixes they publish in their own repo.
I've got things set up so that we have a separate branch called "wordpress" that can be kept in sync with the live Subversion repo.  To do so, it's as simple as:
git checkout wordpress
git svn rebase
git gc
git push origin wordpress

These commands will:

*

*Make sure we're on the WordPress branch

*Re-sync the branch with the live Svn repo

*Run garbage collection (otherwise the repository progressively gets unmanageably large)

*Push the updated branch to our hosted repository on Gitorious

It's easy enough to run these four commands whenever WordPress trunk updates, but that's annoying and a hassle.  I'd love to set this up as a cron job, but I can't seem to figure out how!
I've written a script called wordpress.sh and placed it in the /etc/ folder on the server:
#!/bin/bash
cd /var/www/git/wordpress
git checkout wordpress
git svn rebase
git gc
git push origin wordpress

The script runs just fine.  I can SSH into my server, log in as root, and type . /etc/wordpress.sh and everything works just fine.  But how can I set this up so that cron does things for me?
I've tried manually adding it to crontab (unsuccessfully), using the Webadmin interface in CentOS to add it as an hourly script (unsuccessfully), and now I'm at a loss!  My system logs claim that it's firing (log below):
Feb  4 07:00:01 ---- crond[27745]: (root) CMD (/etc/wordpress.sh    #WordPress mirror)
Feb  4 07:01:01 ---- crond[27773]: (root) CMD (run-parts /etc/cron.hourly)
Feb  4 08:00:01 ---- crond[29095]: (root) CMD (/etc/wordpress.sh    #WordPress mirror)
Feb  4 08:01:01 ---- crond[29142]: (root) CMD (run-parts /etc/cron.hourly)
Feb  4 09:00:01 ---- crond[29708]: (root) CMD (/etc/wordpress.sh    #WordPress mirror)
Feb  4 09:01:01 ---- crond[29718]: (root) CMD (run-parts /etc/cron.hourly)
Feb  4 10:00:01 ---- crond[30328]: (root) CMD (/etc/wordpress.sh    #WordPress mirror)
Feb  4 10:01:01 ---- crond[30337]: (root) CMD (run-parts /etc/cron.hourly)

But nothing actually happens unless I log in and run the script manually.  Ideas?

A: Cron runs with another environment than a login shell so a likely error is that git is not in the path. The easiest is usually to use the full path of every command in a crontab (/usr/bin/git or wherever your git is installed).
Errors in scripts run by cron is usually mailed to the user, so try to look in root's mailbox.

A: Do you run your sites as root? Do you manually run the script as root? I hope you don't.
Now look at cron output: it runs your script from root account, and it probably fails to find the repository. Add it to your account's crontab, not root's.


text:
Q: Root directory when linking css file to html file While learning about paths I found out that "/" takes you to the root directory. I made .html and .css files in the same directory to test how it behaves for different paths. When linking the css file, href = "app.css" and href = "./app.css" both work fine but when I try href = "/app.css" it doesn't link. I know "/" is suposed to take you to the root directory and from what I understand the directory of the html file is the root directory. So why isn't the css file linking properly?

A: / means the root of the current drive
./ means the current directory
../ means the parent of the current directory

A: No need to add the "/" or "./"  because your app.css file is in your current directory.


text:
Q: display message before login screen on windows? I have an program that is supposed to run on all computers when a fire alarm is trigger and display a full screen message and play a .mp3 file. I can get the sound to play on computers were no one has logged in and it is still at the "press ctrl alt del to log in" screen but I can't get a full screen message to open up because there is no active session to open it in. Does anyone know if there is a way to get a message to display at the "press ctrl alt del to log in" screen before someone logs in to windows.
My current application is written in C# but I will rewrite it is another language if someone knows a way I can get this message to display, using another language.
All the computers will be windows 7 machines.
I have found the you can customise the login screen http://msdn.microsoft.com/en-gb/magazine/cc163489.aspx but that is still before the the ctrl alt del screen. I have also read that viruses can put a screen in before the computer loads the ctrl alt del screen but this seems to be booting to a different screen and I want it to be able to be display when it gets a message.
If I can't get a screen to display at the ctrl alt del screen, would it be possible to login and load a full screen message before the desktop loads?


text:
Q: Skipping specific rows while reading an excel file using Pandas Objective is to load 'Energy Indicators.xls' file using pandas.
I need to skip a single specific row while reading the sheet. How can it be done?
I have skipped the first 16 rows, after which i require the 17th row, but the 18th row has to be skipped and the remaining after row no. 18 are needed:
import pandas as pd
energy= pd.read_excel('Energy Indicators.xls', header= [0,1], index_col= 0, skiprows= 16, usecols= "C:F", skipfooter= 38,
                      na_values= "...")
energy

So, how do i skip the 18th row?

A: You can drop the row after reading the whole file
dataframe.drop(17, axis=0)

A: I tried using the pd.read_excel attributes to obtain the motive, and avoiding drop() and got the result using this:
import pandas as pd
skipr= list(range(0,16))
skipr.append(17)
energy= pd.read_excel('Energy Indicators.xls', skiprows= skipr, usecols= "C:F", skipfooter= 38, na_values= "...")

Thanks, for those who answered earlier!


text:
Q: Error when compiling: Declaration of X must be compatible with Y I'm new to Magento and working on upgrading an existing project to 2.4.3. When running php -dmemory_limit=5G bin/magento setup:di:compile I'm encountering an error:
Fatal error: Declaration of X\RecurringService\Model\Export\MetadataProvider::getHeaders(Magento\Framework\View\Element\UiComponentInterface $component) must be compatible with Magento\Ui\Model\Export\MetadataProvider::getHeaders(Magento\Framework\View\Element\UiComponentInterface $component): array in /code/X/RecurringService/Model/Export/MetadataProvider.php on line 82

That points to the following:
/**
 * Retrieve Headers row array for Export
 *
 * @param UiComponentInterface $component
 * @return string[]
 */
public function getHeaders(UiComponentInterface $component)
{
    return array(
        'Next Delivery Date',
        'Service?',
        'Diaper#',
        'Wipes',
        'Doublers',
        'Name',
        'Address 1',
        'Address 2',
        'Exchange Notes',
        'Old #s',
        'Action Date',
        'Action Req',
        'Driver Date',
        'Driver Action',
        'Driver',
        'Status'
    );
}

I'm guessing this is the result of something changing in the new version, but can't seem to find any explanation or docs referencing it.

A: Change your function code with below as your function is not compatible with the Magento's core function.
You missed the function as array : array
Then run setup:di:compile command
/**
 * Retrieve Headers row array for Export
 *
 * @param UiComponentInterface $component
 * @return string[]
 */
public function getHeaders(UiComponentInterface $component): array
{
    return array(
        'Next Delivery Date',
        'Service?',
        'Diaper#',
        'Wipes',
        'Doublers',
        'Name',
        'Address 1',
        'Address 2',
        'Exchange Notes',
        'Old #s',
        'Action Date',
        'Action Req',
        'Driver Date',
        'Driver Action',
        'Driver',
        'Status'
    );
}

Hope this will hep you!


text:
Q: Find $\lim_{x\to 2} \frac{x - \sqrt{3 x - 2}}{(x^2 - 4)}$ Can you help me with this limit?
What do I have to do ?
I tried to multiply by the conjugate expression but it didn't work
$$
\lim_{x\to 2} \frac{x - \sqrt{3 x - 2}}{(x^2 - 4)}.
$$
Thanks

A: Hint: After multiplying by the conjugate note that $x^2-(3x-2)=x^2-3x+2=(x-1)(x-2)$.


text:
Q: Signed applet not working I make a applet:
     import java.awt.*;
     import java.awt.event.*;
     import javax.swing.*;
     import java.net.*;
     import Java.io.*;
     public class a extends JApplet
     {
        public void init()
        {
           EventQueue.invokeLater(new Runnable()
           {
                 public void run()
           {
          add (new MaxC());
        }
              });
        }
     }

     class MaxC extends JPanel
     {
         public MaxC()
{
     maxlink = new JTextField(40);
     JButton download = new JButton("Pobierz");
     JButton play = new JButton("Odtwórz online");

     download.addActionListener(new ActionListener()
     {
        public void actionPerformed(ActionEvent event)
        {
            try
            {
                URL url = new URL("http://www.google.com");
                InputStream response = url.openStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(response));
                for (String line; (line = reader.readLine()) != null;)
                {
                    maxlink.setText("yes");
                }
                reader.close();
            }
            catch (Exception e) {maxlink.setText(""+e);}
        }
     });

     add(maxlink);
     add(download);
     add(play);
}

public JTextField maxlink;
    }

It's working in Firefox and AppletViewer but, when I signed it it's not working (http://java.sun.com/developer/onlineTraining/Programming/JDCBook/signed.html)
It ask me about the permissions and start but then loading is stopped. Where is mistake?


text:
Q: What is the main use of self? I am working on a ARC based project. I am  just wondering what is the main use of self ?
I am having an array as follows
@property(strong,nonatomic)NSMutable *dataArray;

I am initializing the array as follows
-(void)viewDidLoad{

 self.dataArray=[[NSMutableArray alloc]initWithObjects:@"one",@"two",nil];  //first method

}

or
-(void)viewDidLoad{

 dataArray=[[NSMutableArray alloc]initWithObjects:@"one",@"two",nil];  //second method

}

Can anyone tell me what is the difference between my first and second method ?

A: The first invocation: self.dataArray = ... invokes the accessor method of self, like this: [self setDataArray:...]
The second invocation: dataArray = ... defines the content of the instance variable (ivar) named dataArray.
That's not the same thing.

A: After lot googling I found the answer to my question ,
@property (nonatomic, retain) NSDate *timestamp;
Objective C will generate the getter and setter as follows
(NSDate *)timestamp
{
   return timestamp;
}

(void)setTimestamp:(NSDate *)newValue
{
   if (timestamp != newValue)
   {
      [timestamp release];

      timestamp = [newValue retain];
   }
}

The setter method can be invoked only as follows
self.timestamp = [NSDate date];
where as
timestamp=[NSDate date];
does not invoke the setter method.
Without the self object and the dot we are no longer sending an object a message but
directly accessing the ivar named timestamp.
Conclusion: When we don't use self , the old value won't be released ,because the setter
method won't be invoked i.e Prior to ARC.But in ARC I am not pretty sure about this.As far
as I heard , With ARC either way of setting the ivar is correct as far as memory management
is concerned.


text:
Q: Automatically Subscribe to Youtube Channel After it gets a certain amount of subscribers my question is is it possible to have a Python bot checking every second the subscribers a certain YouTube channel has and after the channel gets a desired amount of subscribers to subscribe us to it?
For example I am looking at channel X that has 1490 subscribers and I want to be exactly the 1500th subscriber. So the code needs to refresh the number every few minutes or seconds.
How do I do that?
I have a basic Python subscriber count code but I am stuck at moving things forward.
If you have any code in any language that can do this automatically I will be forever grateful to you
My current code
from googleapiclient.discovery import build

# Create YouTube Object
youtube = build('youtube', 'v3',
                developerKey='Enter API key')

ch_request = youtube.channels().list(
    part='statistics',
    id='Enter Channel ID')

# Channel Information
ch_response = ch_request.execute()

sub = ch_response['items'][0]['statistics']['subscriberCount']
vid = ch_response['items'][0]['statistics']['videoCount']
views = ch_response['items'][0]['statistics']['viewCount']

print("Total Subscriber:- ", sub)
print("Total Number of Videos:- ", vid)
print("Total Views:- ", views)

A: Use selenium, find the subscribe button in html and then click it. Example of selenium code (for a different website, from the selenium docs):
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

driver = webdriver.Firefox()
driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element(By.NAME, "q")
elem.clear()
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
driver.close()

Get more info at: https://selenium-python.readthedocs.io/
As for running it continuously, just use a loop and break out when the desired sub count is reached.

A: Note that you can only get the three significant figures of the subscriber count.
@Game Developement shared a solution that may be quite heavy due to the need of having a web-browser dedicated for this purpose, in addition to be interpreted by YouTube as spam traffic.
I would instead recommend you to use Channels: list using part=statistics to get the subscriber count in item["statistics"]["subscriberCount"] and then Subscriptions: insert to subscribe to the given YouTube channel.


text:
Q: AppleScript - echo into openssl AES encryption - is there a way to crack/snoop thru logs? Don't know if this question is better off here, or in the Linux world...but I need a decent answer.. :)
I am using Applescript to pull data from fields in a spreadsheet or database, shove them directly into terminal for encryption.
My Applescript includes a line like:
echo "thisismydatastring and my saltbits"  | openssl aes-256-cbc -k thisismypassword -base64

My question:  is there a way one could filter thru log files to catch this plaintext instance of the password?
Is there a better way to prevent hacking?
If sending an "echo" into terminal is traceable, is there another way I could push something into Terminal where it doesn't hit any logs (and where AppleScript can get the results)?

A: I overcome the password issue in my bash scripts by sourcing (including) another file with a predetermined variable already set.
For example.  Say you have a "config" file  ~/config.conf and in it you assign some variables:
# Config file for MyScript.sh

$user = Me
$pass = S3cr3t5!

In your script you source the file so you can use the variables you defined:
#!/bin/bash

source /Path/to/config.conf

stuff= "thisismydatastring and my saltbits"

echo  $stuff | openssl aes-256-cbc -k $pass -base64

Personally, I like to keep the line that executes the command as clean as possible using variables (like stuff in the example above) so that it's easier to see what the command is doing and consequently easier to debug.
Is this safe from prying eyes?  Yes, for the most part.  You can set the permissions so that only the user can read and write the file and deny it to everyone else:
chmod 600 config.conf

Anyone snooping through logs (which is your question) won't be able to see the plain text passwords.


text:
Q: Scrape a webpage and navigate by clicking buttons I want to perform following actions at the server side:
1) Scrape a webpage
2) Simulate a click on that page and then navigate to the new page.
3) Scrape the new page
4) Simulate some button clicks on the new page
5) Sending the data back to the client via json or something
I am thinking of using it with Node.js.
But am confused as to which module should i use
a) Zombie
b) Node.io
c) Phantomjs
d) JSDOM
e) Anything else
I have installed node,io but am not able to run it via command prompt.
PS: I am working in windows 2008 server

A: Zombie.js and Node.io run on JSDOM, hence your options are either going with JSDOM (or any equivalent wrapper), a headless browser (PhantomJS, SlimerJS) or Cheerio.

*

*JSDOM is fairly slow because it has to recreate DOM and CSSOM in Node.js.

*PhantomJS/SlimerJS are proper headless browsers, thus performances are ok and those are also very reliable.

*Cheerio is a lightweight alternative to JSDOM. It doesn't recreate the entire page in Node.js (it just downloads and parses the DOM - no javascript is executed). Therefore you can't really click on buttons/links, but it's very fast to scrape  webpages.

Given your requirements, I'd probably go with something like a headless browser. In particular, I'd choose CasperJS because it has a nice and expressive API, it's fast and reliable (it doesn't need to reinvent the wheel on how to parse and render the dom or css like JSDOM does) and it's very easy to interact with elements such as buttons and links.
Your workflow in CasperJS should look more or less like this:
casper.start();

casper
  .then(function(){
    console.log("Start:");
  })
  .thenOpen("https://www.domain.com/page1")
  .then(function(){
    // scrape something
    this.echo(this.getHTML('h1#foobar'));
  })
  .thenClick("#button1")
  .then(function(){
    // scrape something else
    this.echo(this.getHTML('h2#foobar'));
  })
  .thenClick("#button2")
  thenOpen("http://myserver.com", {
    method: "post",
    data: {
        my: 'data',
    }
  }, function() {
      this.echo("data sent back to the server")
  });

casper.run();

A: The modules you listed do the following:

*

*Phantomjs/Zombie - simulate browser (headless - nothing is actually displayed). Can be used for scraping static or dynamic. Or testing of your html pages.

*Node.io/jsdom - webscraping : extracting data from page (static).

Looking at your requirements, you could use phantom or zombie.

A: Short answer (in 2019): Use puppeteer
If you need a full (headless) browser, use puppeteer instead of PhantomJS as it offers an up-to-date Chromium browser with a rich API to automate any browser crawling and scraping tasks. If you only want to parse a HTML document (without executing JavaScript inside the page) you should check out jsdom and cheerio.
Explanation
Tools like jsdom (or cheerio) allow it to extract information from a HTML document by parsing it. This is fast and works well as long as the website does not contain JavaScript. It will be very hard or even impossible to extract information from a website built on JavaScript. jsdom, for example, is able to execute scripts, but runs them inside a sandbox in your Node.js environment, which can be very dangerous and possibly crash your application. To quote the docs:

However, this is also highly dangerous when dealing with untrusted content.

Therefore, to reliably crawl more complex websites, you need an actual browser. For years, the most popular solution for this task was PhantomJS. But in 2018, the development of PhantomJS was offically suspended. Thankfully, since April 2017 the Google Chrome team makes it possible to run the Chrome browser headlessly (announcement).
This makes it possible to crawl websites using an up-to-date browser with full JavaScript support.
To control the browser, the library puppeteer, which is also maintained by Google developers, offers a rich API for use within the Node.js environment.
Code sample
The lines below, show a simple example. It uses Promises and the async/await syntax to execute a number of tasks. First, the browser is started (puppeteer.launch) and a URL is opened page.goto.
After that, a functions like page.evaluate and page.click are used to extract information and execute actions on the page. Finally, the browser is closed (browser.close).
const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  await page.goto('https://example.com');

  // example: get innerHTML of an element
  const someContent = await page.$eval('#selector', el => el.innerHTML);

  // Use Promise.all to wait for two actions (navigation and click)
  await Promise.all([
    page.waitForNavigation(), // wait for navigation to happen
    page.click('a.some-link'), // click link to cause navigation
  ]);

  // another example, this time using the evaluate function to return innerText of body
  const moreContent = await page.evaluate(() => document.body.innerText);

  // click another button
  await page.click('#button');

  // close brower when we are done
  await browser.close();
})();


text:
Q: .PPT macro-enabled show path I am trying to save a presentation as a macro-enabled show in PowerPoint, and I'm running into a problem when I do. This code that I'm using works great when I'm save as a macro-enabled presentation - but not as a macro-enabled show:
Dim oPPTApp As PowerPoint.Application
Dim oPPRFile As PowerPoint.Presentation
Dim oPPTShape As PowerPoint.PlaceholderFormat
Dim oPPTSlide As PowerPoint.Slide

Set oPPTApp = CreateObject("PowerPoint.Application")
oPPTApp.Visible = msoTrue

'opening an existing presentation

Dim spath2 As String
Dim strpath2 As String
spath2 = ActivePresentation.Path <--
strpath2 = spath2 + "\Resources\AIT Diplomas\AIT Diplomas.pptx"

The problem is that when I save it as a macro-enabled show and try to run it, it stops at the <--- line of code because there "is no active presentation. When you save powerpoint as a macro-enabled show, then no "presentation" (powerpoint window) opens, just the slideshow window.
I need a way of finding the active show path that doesn't reference an activepresentation, which doesn't exist.
Thank you for your time!
Respectfully, Dustin

A: Since you haven't answered my question about where the code is running FROM, I'm going to assume that it's from within PPT and that there are no other applications involved.  That being the case, this works fine, either from a PPTM or PPSM:
Sub MittedForYourApproval()

' if the code is running within PPT, you don't need to do it this way:
' PPT has a reference to itself.
'Dim oPPTApp As PowerPoint.Application
'Dim oPPRFile As PowerPoint.Presentation
'Dim oPPTShape As PowerPoint.PlaceholderFormat
'Dim oPPTSlide As PowerPoint.Slide

Dim oPPRFile As Presentation
' I don't know where you're going with this
' but PlaceholderFormat <> a shape
Dim oPPTShape As PlaceholderFormat
Dim oPPTSlide As Slide

'Set oPPTApp = CreateObject("PowerPoint.Application")
'oPPTApp.Visible = msoTrue

'opening an existing presentation

Dim spath2 As String
Dim strpath2 As String
spath2 = ActivePresentation.Path '<--
'strpath2 = spath2 + "\Resources\AIT Diplomas\AIT Diplomas.pptx"
MsgBox spath2

End Sub


text:
Q: The difference between total error, prediction error and fitted error via residual Consider a regression model $Y=E(Y|X)+Prediction \ Error$ i.e $Prediction \ error = Y-E(Y|X)$. Now, define an estimate of the regression function $E(Y|X)=\hat{Y}+ Fitted \ error$ i.e. Fitted error = $E(Y|X)-\hat{Y}$. Further, define residual = $Y-\hat{Y}$. Now, we have $Total \ error = Residual
 \ error + Fitted \ error$.
Therefore, the total error can be expressed as $Total \ error = Prediction \ error + 2 \times Fitted
 \ error$.
Is the above derivation regarding errors, is right or wrong?


text:
Q: Scroll to specific div on click, after applying a jQuery filter on portfolio items I'm building a website and I've accomplished to be able to filter my portfolio/projects with a click on a link in a sidebar (with a little help).
Now I would like the page to scroll down to the specific projects div after/or while this filter is being applied.
I'm using the following code for the filtering:
jQuery('#mk-filter-portfolio li a[data-filter="'+portfolio_category+'"]').click();
});

And i would like to use something simple like this for scrolling down:
$("#button").click(function() {
$('html, body').animate({
    scrollTop: $("#projects").offset().top
}, 2000);
});

Could you guys please help me combine the two to something functional? Or offer a better solution?
Thanks!


text:
Q: Convert string datetime into Java Long with XStream I'm trying to get XStream to be able to convert a string that contains a datetime (such as 2013-01-23 16:50:39.495855) into a java.lang.Long instance.
Currently, I have XML like so:
<widget>
    <timestamp val="2013-01-23 16:50:39.495855"/>
</widget>

I want to convert this into a standard Unix epoch timestamp (number of millis since Jan 1, 1970). Since the above datetime translates into a Unix epoch timestamp of (if my math is right) 1358959839000, I'd like XStream to convert this into a new Long(1358959839000) instance.
I don't believe this is possible with XStream's alias methods, and I would probably need to write my own Converter, however a com.thoughtworks.xstream.converters.basic.LongConverter already exists, so I'm not sure how to write my own UnixEpochLongConverter seeing that both converters are attempting to convert a String to a Long. Any ideas? Thanks in advance!

A: Either register your Custom converter as local using registerLocalConverter or with priority above XStream.PRIORITY_NORMAL.
xstream.registerLocalConverter(
    Widget.class,
    "timestamp",
     new UnixEpochLongConverter());

A: You could use the DateFormat object to convert the string to a java.util.Date object and then do date.getTime() to return a long value . Below is an example. You could write a method in your object that basically converts the string to long.
 String date = "2013-01-23 16:50:39.495855";
 DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
 Date datem = format.parse(date);
 long longDate = datem.getTime();
 System.out.println(longDate);


text:
Q: ORM: Article, revisions and main revisions What is the best practice in ORM to store articles and their revisions? When storing in SQL by myself, I used to have following structure:
 articles [id, parent_id, name, text]

and by parent_id I could easily recognize parent article:
 SELECT * FROM articles WHERE parent_id = 0;

would select parent revisions and,
 SELECT * FROM articles WHERE parent_id = 330;

would select all the revisions of article #330.
What is the right way of doing this in ORM? Shall I rather have:

*

*Integer parentId

*Article parentArticle

*List revisions
I will appreciate any suggestions.

A: translate your sql to hibernate/jpa entity:
@Entity
@Table.....
public class Article {

    @Id
    @Column
    private Integer id,

    @OneToMany(mappedBy="parentArticle")
    private Set<Article> childArticles;

    @ManyToOne
    @JoinColumn(name="parent_id")
    private Article parentArticle

    @Column
    private String name,text
    ...

I don't know your exact requirement. Have you checked hibernate entity auditing? is it helpful for you? it will store a copy with revision number everytime you change the "article".
link of hibernate envers:
http://docs.jboss.org/envers/docs/index.html


text:
Q: Dealing with declined / rejected pull requests So, I'm quite fluent with git in general but I've only never used branch based workflows, and mostly with Gerrit. I'm pretty much new to Pull Requests.
Pull Requests mostly resemble to me as a branch pushed to Gerrit, awaiting review. In Gerrit, if there's a problem with one of my commits, comments are left on it and it receives a non-positive score. With a Pull Request comments can be left on it and it can be declined. In Gerrit, to address the issues the comments raised I amend the offending commit(s) and push them up again (well, new commits with the same Change-Id). What do I do to update a Pull Request? Just push a fix commit on top? Cancel the pull request (is this possible?), amend my commits and push up a new one?
We're using Bitbucket for our project and right now we're planning on avoiding forks and just making the pull request to master (our "production" branch) from feature branches, mostly because that feels closer to what I'm familiar with.

A:
What do I do to update a Pull Request? Just push a fix commit on top?

On GitHub, yes, you can add new commits, or even reorder/modify the existing commit of your dedicated branch, force push that branch to your fork (git push --force) and the existing pull request will get updated, any Travis CI job will run again, and the original repo maintainer will be notified.
But even on BitBucket, pull requests are for commits proposed from a fork, not from a branch from the same repo. See "Fork a Repo, Compare Code, and Create a Pull Request"
The pro is mainly for preventing contributors to modify a repo, and force them to work in their own repo (the fork, that they then clone on their local computer).


text:
Q: Yii CList error - do not have a method or closure named "setReadOnly" I have a basic function that is using CList - for some reason I get the following error:
CList and its behaviors do not have a method or closure named "setReadOnly".

My php code
$list = new CList(array('python', 'ruby'));
$anotherList = new Clist(array('php'));
    var_dump($list);
$list->mergeWith($anotherList);
    var_dump($list);
$list->setReadOnly(true); // CList and its behaviors do not have a method or closure named "setReadOnly".

Can anyone explain why I am getting this error?
P.S i copied this code directly from a recent Yii book... so I am abit puzzled
// Update: added the var_dump before and after the mergeWith()
object(CList)[20]
  private '_d' =>
    array (size=2)
     0 => string 'python' (length=6)
     1 => string 'ruby' (length=4)
  private '_c' => int 2
  private '_r' => boolean false
  private '_e' (CComponent) => null
  private '_m' (CComponent) => null

object(CList)[20]
  private '_d' =>
    array (size=3)
    0 => string 'python' (length=6)
    1 => string 'ruby' (length=4)
    2 => string 'php' (length=3)
  private '_c' => int 3
  private '_r' => boolean false
  private '_e' (CComponent) => null
  private '_m' (CComponent) => null

A: The CList method setReadOnly() is protected and thus cannot be called from the scope you're using, only from within itself or inheriting classes. See http://php.net/manual/en/language.oop5.visibility.php#example-188.
However, the CList class allows the list to be set as read only in its constructor
public function __construct($data=null,$readOnly=false)
{
    if($data!==null)
    $this->copyFrom($data);
    $this->setReadOnly($readOnly);
}

So...
$list = new CList(array('python', 'ruby'), true); // Passing true into the constructor
$anotherList = new CList(array('php'));
$list->mergeWith($anotherList);

Results in the error
CException The list is read only.

I'm not sure if that's the result you're looking for, but if you want a read only CList that's one way to get it.
You might think when merging subsequent CLists you could set readonly true at the end, however mergeWith() only merges the _d data array, not the other class variables, so it remains false.
$list = new CList(array('python', 'ruby'));
$anotherList = new CList(array('php'));
$yetAnotherList = new CList(array('javacript'), true);

$list->mergeWith($anotherList);
$list->mergeWith($yetAnotherList);

var_dump($list); // ["_r":"CList":private]=>bool(false)


text:
Q: How do I get certain buttons working? How do I get a button working?
from tkinter import *

window=Tk()
window.title=title("Test")

button=button(window, text='Increase variable', command=Var)
button.pack()

variable=0
def Var():
    variable=variable+1

I get an error saying Var is not defined. If I put the function before the button code I get an error when clicking the button.
from tkinter import *

variable=0
def Var():
    variable=variable+1

window=Tk()
window.title=title("Test")

button=button(window, text='Increase variable', command=Var)
button.pack()

Clicking on the button will yield an error local variable referenced before assignment. How do I get this to work?

A: If variable is a global variable, you need to indicate to Var that this is the case.


text:
Q: What does EL5 and EL6 means in term of packages? I am using CentOS with Citrix XenServer.
[root@xen01 shm]# uname -a
Linux xen01 2.6.32.43-0.4.1.xs1.8.0.855.170800xen #1 SMP Mon Jul 21 05:12:35 EDT 2014 i686 i686 i386 GNU/Linux

[root@xen01 shm]# lsb_release -a
LSB Version:    :core-4.0-ia32:core-4.0-noarch
Distributor ID: XenServer
Description:    XenServer release 6.2.0-70446c (xenenterprise)
Release:    6.2.0-70446c
Codename:   xenenterprise

I installed apcupsd package, from http://sourceforge.net/projects/apcupsd/files/rpms%20-%20Stable/3.14.10/apcupsd-3.14.10-1.el5.i386.rpm/download
But there was a new version the past year, and seems that RPM wasn't updated to 3.14.12.
I found this version however: https://admin.fedoraproject.org/updates/FEDORA-EPEL-2014-4191/apcupsd-3.14.12-1.el6
I would like to know what exactly EL5 and EL6 means in term of packages. The latter fails because of dependencies, but am I able to instal EL6 packages?

A: If you still can't find your version with this answer, you can try this:
cat /etc/*-release

A: EL5 stands for Enterprise Linux 5 (Red Hat Enterprise Linux version or CentOS version) and EL6 accordingly for Enterprise Linux 6.
You can find the current release you are running in:
cat /etc/redhat-release
or
cat /etc/centos-release
Depending on the version your system is running with you are able to install the packages.


text:
Q: MongoDB find documents with duplicate field in an array I have a very large "customer" database of documents.  Each of those documents has an array called "activities".  Inside that array are objects with multiple fields. One of those fields is called types, so activities.types. I would like to just get a count of how many documents have more than 1 activity where the type field is "postcards". Basically when we send out marketing material it saves each one as an activity and I want to know how many customers have received more than one postcard. I've tried aggregates like the below code but that doesn't specify postcards or how many documents meet this criteria. I don't need the actual documents.  Just a count.
db.getCollection('contacts').aggregate([
  { $unwind: "$activities" },
  {
    $group: {
      _id: {
        _id: "$_id",
        same_type: "$activities.type"
      },
      sum: { $sum: 1 }
    }
  },
  { $match: { sum: { $gt: 1 } } },
])

A: Here's one way to get the total count of customers who received more than one "postcards" contact.
db.contacts.aggregate([
  {
    "$match": {
      "activities.types": "postcards"
    }
  },
  {
    "$project": {
      "_id": 0,
      "postcardsCount": {
        "$reduce": {
          "input": "$activities",
          "initialValue": 0,
          "in": {
            "$cond": [
              {"$eq": ["$$this.types", "postcards"]},
              {"$add": ["$$value", 1]},
              "$$value"
            ]
          }
        }
      }
    }
  },
  {
    "$match": {
      "$expr": {"$gt": ["$postcardsCount", 1]}
    }
  },
  {"$count": "totalCount"}
])

Example output:
[
  {
    "totalCount": 23
  }
]

Try it one mongoplayground.net.


text:
Q: Created a symbolic link to /usr/bin/clang++-5.0, but the link only compiles C files Ubuntu 16.04, no GCC. Installed clang:
sudo apt install clang-5.0
Created two links:
sudo ln -s /usr/bin/clang-5.0 clang
sudo ln -s /usr/bin/clang++-5.0 cclang
Compile a simple C file, helloworld.c. Either clang or cclang works fine.
Try to compile a C++ file:   cclang helloworld.cpp
Got errors. Same error messages as clang helloworld.cpp (C compiler to compile a C++ file)
However, /usr/bin/clang++-5.0 helloworld.cpp works fine.
Anything wrong in my symbolic link creation?


text:
Q: Picking correct function to run I currently have 2 functions, one is LoginButton(); and the other is LogoutButton(); and I also have an if statement like this:
If (CODE){

}else{

}

I want the function to be called at a specific place as I want the buttons to appear there. So how can I assign the functions to a variable so I can call the correct one later on?
I am currently referencing the functions like this:
<?php echo logoutbutton(); ?>
<?php echo loginbutton(); ?>

But I only want the correct one showing.
Thanks,
Matt

A: You can use the following code:
$button = (condition) ? loginbutton() : logoutbutton();

The above expression is equal to:
$function;
if (condition) {
    $button = loginbutton();
}
else {
    $button = logoutbutton();
}

A: Use session here to keep track of user has logged in or not. Something like this
$function = (isset($_SESSION['logged_in'])) ? logoutbutton() : loginbutton();


text:
Q: What do voltage limits on MOSFETs mean? I want to include a MOSFET in a schematic I'm designing. I want to manufacture the finished board at JLCPCB, but it seems they they have a very limited set of options for MOSFETs or transistors in general.
This is a part of my schematic:

I want to turn on 4 LEDs with an Arduino. I tried doing this without a MOSFET but the output-wattage of about 2 W is way too low for driving all my LEDs (250 mW each). Here is the datasheet of the MOSFET I chose for now.
I'm not sure if this MOSFET suits my needs. The input to the gate (C01) comes from the Arduino, so 5 V. The VCC would be the same power adapter as the Arduino, so also 5 V, but with way more current available. Each LED would consume 20 mA of current according to the datasheet.
Would the AO3414 be suitable for this? The datasheet states it can handle 20 V, but I'm not sure if that means it can handle 5 V as well? The voltage from gate to source is ±8 V. Is 5 V still possible? If not, could you maybe suggest another MOSFET? If the voltage from gate to source is below 5 V, what would happen if I'd use 5 V anyway?
Edit: I changed the orientation of the MOSFET, would this setup work:

Edit: Since PStechPaul pointed out that the voltage drop is too much, I gave each LED a resistor. Would it be OK this way:

I calculated the resistance with this calculator.

A:
simulate this circuit – Schematic created using CircuitLab
That MOSFET will work fine but you should put it on the low side between the LEDs and GND. Not only was it upside down (source/drain swapped) but it was also on the high side of the load when it should be on the low side of the load. After you build it, you can fine-tune the LED current by adjusting R1-R4. If the current is too high, use a larger resistor. If the current is too low use a smaller resistor.
Hope that helps.


text:
Q: Can I use multiple intro.js with more than 2 pages? I want to use intro.js with more than two pages.
Is it a simple way to do it?

A: Yes, you can. If you look at code for intro.js example with multiple pages https://github.com/usablica/intro.js/tree/master/example/multi-page you can see that first page has code that redirects to second page after user click the button:
<script type="text/javascript">
  document.getElementById('startButton').onclick = function() {
    introJs().setOption('doneLabel', 'Next page').start().oncomplete(function() {
      window.location.href = 'second.html?multipage=true';
    });
  };
</script>

And on the second page we use regex to check if user is going through intro. You will need  to add code like that to each page, with url address to the page that should be shown next.
If you want to have more than one "intro flows" (since the question title said multiple), you can give them names or numbers. Then, instead of adding multipage=true you can use multipage=beta_version or multipage=1 and use reqex to check if user should see intro, and if yes, which one.
<script type="text/javascript">
  if (RegExp('multipage', 'gi').test(window.location.search)) {

    document.getElementById('startButton').onclick = function() {
      introJs().setOption('doneLabel', 'Next page')
        .start().oncomplete(function() {
          if (RegExp('multipage=2', 'gi').test(window.location.search)) {
            window.location.href = 'third.html?multipage=2';
          }
          else {
            window.location.href = 'unicorn.html?multipage=3';
          }
        });
      };
  }
</script>

That might be not the nicest code ever :), but ( like Rich said ) without more information I can only guess this is what you want to do? But hopefully, it will give a general idea.

A: if (RegExp('multipage', 'gi').test(window.location.search)) {
    introJs().setOption('doneLabel', 'Next Page →').start().oncomplete(function() {
        window.location.href = 'nextpage?multipage=true';
    });
}

A: I was able to use intro.js for a complex multipage use (more complete than their official multipage example). See the issue I opened about it associated to my React solution on Codesandbox.


text:
Q: Why is my port 25 so active? Using netstat -na I notice that I have a lot of connections like
tcp        0      0 XXX.XXX.XXX.XXX:25        YYY.YYY.YYY.YYY:13933     ESTABLISHED
tcp        0      0 XXX.XXX.XXX.XXX:25        ZZZ.ZZZ.ZZZ.ZZZ:9528     ESTABLISHED

Those are to addresses to USA, Brasil etc, despite that my server is located in UK.
Can that be some "illegal" activity, like spamming or something?
[root@myserver ~]# tcpdump port 25
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), capture size 96 bytes
20:54:33.842388 IP g224057157.adsl.remotehost1.de.23970 > XXX.XXX.XXX.XXX.smtp: S 3343584823:3343584823(0) win 8192 <mss 1360,nop,wscale 2,nop,nop,sackOK>
20:54:33.842431 IP XXX.XXX.XXX.XXX.smtp > g224057157.adsl.remotehost1.de.23970: S 583530268:583530268(0) ack 3343584824 win 5840 <mss 1460,nop,nop,sackOK,nop,wscale 7>
20:54:33.904660 IP g224057157.adsl.remotehost1.de.23970 > XXX.XXX.XXX.XXX.smtp: . ack 1 win 16660
20:54:34.036073 IP XXX.XXX.XXX.XXX.smtp > g224057157.adsl.remotehost1.de.23970: P 1:90(89) ack 1 win 46
20:54:34.304356 IP g224057157.adsl.remotehost1.de.23970 > XXX.XXX.XXX.XXX.smtp: . ack 90 win 16637
20:54:34.304433 IP XXX.XXX.XXX.XXX.smtp > g224057157.adsl.remotehost1.de.23970: P 90:110(20) ack 1 win 46
20:54:34.568451 IP g224057157.adsl.remotehost1.de.23970 > XXX.XXX.XXX.XXX.smtp: . ack 110 win 16632

A: Port 25 is the standard port SMTP traffic runs on. If you intend for you system to be an email server than those might be legit servers trying to send you or your users email. If you do not intend your system to be an email server, figure out how to get port 25 turned off.
Historically email servers would be configured to politely send on email for other servers. Today this is bad, bad, bad. It's called being an open email relay. It would be wise for you to verify that you are not doing this. But, don't go to far and try to block port 25 traffic if you do mean to accept email from the outside world.

A: Yes.
Or at least, it's being attempted. If you have port 25 open, you can be guaranteed someone's trying to relay mail through you. If you have port 80 open, you can be guaranteed someone's trying to exploit your site. If you have port 22 open, you can be guaranteed someone's trying to brute force you. Notice a pattern?
Lucky for you, they're almost entirely amateurish. Use tools like your log files, telnet, and tcpdump to verify that these are only attempts and you're not successfully being used to relay spam.

A: If you need it open, you need it open. Try to lock down who you accept smtp connections from. YOu can get an offsite spam/virus filter, which hosts the DNS MX recorded servers.  Then only accetp smtp from their network.
Note that tcp port 587 is an RFC mail submission port.

A: Have you an email server on this machine?
If not, close the port (firewall) and that should be sufficient.
If yes, then look in your mail.log (/var/log/mail.log) to see what is it happening there. It will say who connected and what was done.
If the IPs are trying to send a lot of email to unexistent users on your domain or to other domains or other "ilegal" activity (blocked or successful) I would drop them in the firewall if they do this a lot and everyday but it's only a personal choice, not a necessary option and you cannot stay there all the day looking at all the connections to block everybody!!!

After that, I think you should investigate to see if your e-mail is relaying e-mail for who ask for it or not. Anyways if you have a mail server, people will try to use it. Nothing you can do against them trying... but you should be able to see in the log if they succeeded to relay or if they were blocked. Make sure your email server is configured to not relay for untrusted or unknown servers (or known and not allowed of course! :)).

Edit: just remembered now... if you do not have an email server and port 25 is open, I think you need to have a look at the other ports too and close the unused.

A: If your server/computer is mail server please verify it with http://mxtoolbox.com/ to see if it's not an open relay. If MxToolbox will say it's not you're good to assume most likely the incoming connections are not doing you any harm (except for trying to relay thru you which is unsuccessful). You could check your server if it's on the spam list to verify you're not sending spam yourself.


text:
Q: Problem when deploying project with web socket on Jetty 9.2.13.v20150730 I've experienced a problem while migrating an app from PrimeFaces 5.2 to 10.
This problem is related to migration of web socket implementation from Primefaces to Omnifaces.
The versions I'm using:

*

*PF: 10.0.0

*PF extensions: 10.0.6

*Omnifaces 2.7.7

*CDI 1.1

*JSF 2.2

I don't have anything fancy, just a simple PushBean which sends a message.
I've tried downgrading to PF8, but, as expected, the result is the same.
The configuration is made as requested in the documentation, in my web.xml file having this flag enabled:
<context-param>
    <param-name>org.omnifaces.SOCKET_ENDPOINT_ENABLED</param-name>
    <param-value>true</param-value>
</context-param>

However, when I try to deploy my app to jetty, I'm receiving the following error:
java.lang.IllegalStateException: OmniFaces failed to initialize! Report an issue to OmniFaces.
    at org.omnifaces.ApplicationListener.contextInitialized(ApplicationListener.java:88)
    at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:800)
    at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:444)

.
.
.
Caused by: java.lang.RuntimeException: Cannot load platform configurator
    at javax.websocket.server.ServerEndpointConfig$Configurator.fetchContainerDefaultConfigurator(ServerEndpointConfig.java:123)
    at javax.websocket.server.DefaultServerEndpointConfig.<init>(DefaultServerEndpointConfig.java:85)
    at javax.websocket.server.ServerEndpointConfig$Builder.build(ServerEndpointConfig.java:301)
    at org.omnifaces.cdi.push.Socket.registerEndpointIfNecessary(Socket.java:1114)
    at org.omnifaces.ApplicationListener.contextInitialized(ApplicationListener.java:85)
    at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:800)
    at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:444)
    at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:791)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:294)

I'm guessing that there is something that I'm not doing right, but, I don't know exactly what is it.
Can you please, give a little hand?
Thanks in advance!

A: The stacktrace / exception ...
Caused by: java.lang.RuntimeException: Cannot load platform configurator
    at javax.websocket.server.ServerEndpointConfig$Configurator.fetchContainerDefaultConfigurator(ServerEndpointConfig.java:123)
    at javax.websocket.server.DefaultServerEndpointConfig.<init>(DefaultServerEndpointConfig.java:85)
    at javax.websocket.server.ServerEndpointConfig$Builder.build(ServerEndpointConfig.java:301)

This is coming from the javax.websocket API jar, when it attempts to find the Server Container Default Configuration (in other words, the implementation specific defaults, which would be Jetty)
If you are running Jetty, you need to be including the jetty support jar for javax.websocket.server in your classpath.
Which on Jetty 9.2.x would be the javax-websocket-server-impl-<ver>.jar file (and associated dependencies).
Per @BalusC, omnifaces is just a web-fragment deployed in your WAR's WEB-INF/lib.
That means you have to enable support for websocket on the Jetty server side.
For standalone (using ${jetty.base} and ${jetty.home} split) this means enabling the correct module for your version of Jetty.

Jetty ver
WebSocket spec
Module

Jetty 8.x and older
n/a
n/a

Jetty 9.0.x
n/a
n/a

Jetty 9.1.x
javax.websocket (beta)
websocket

Jetty 9.2.x - 9.4.x
javax.websocket 1.0
websocket

Jetty 10.0.x
javax.websocket 1.1
websocket-javax

Jetty 11.0.x
jakarta.websocket 2.0
websocket-jakarta

To do that you'll use the command line.
Jetty 9.x
[~]$ cd /path/to/my-jetty-base
[my-jetty-base]$ java -jar /path/to/jetty-home/start.jar
   --add-to-start=websocket

Jetty 10+
[~]$ cd /path/to/my-jetty-base
[my-jetty-base]$ java -jar /path/to/jetty-home/start.jar
   --add-module=websocket-javax


text:
Q: Error Says "Expected :" in Image Upload Capability I am trying to create an image upload capability in my app.
In the last line of this bit of code I am getting an error that says "expected :"
Any ideas what I should do to resolve it?
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data;
boundary=%@",boundary];

[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"rn--%@rn",boundary]
dataUsingEncoding:NSUTF8StringEncoding]];

Below is where I get the error:
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data;
name="userfile"; filename="ipodfile.jpg"rn"] dataUsingEncoding:NSUTF8StringEncoding]];

A: You need to escape the quotes in the string.
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data;name=\"userfile\"; filename=\"ipodfile.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

A: Replace this
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data;
name="userfile"; filename="ipodfile.jpg"rn"] dataUsingEncoding:NSUTF8StringEncoding]];

With
[body appendData:[@"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile.jpg\"r\n" dataUsingEncoding:NSUTF8StringEncoding]];

A: Use Single quotes instead of your inner double quotes
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data;  name='userfile'; filename='ipodfile.jpg'rn"] dataUsingEncoding:NSUTF8StringEncoding]];

A: " (double quote) is the escape character in objective-c(and even in c and c++) and escape character are character combinations that comprise a backslash ("\") followed by some character. They are called escape sequences because the backslash causes an "escape" from the normal way characters are interpreted by the compiler.
so simply, to define a string in a objective-c , you need that string inside @"" and what if the " (double quote) sign is already there in the string. In that case compiler take that " (double quote) sign (that is actually a part of string) as ending of string. So in such situation we need to tell compiler that escape that character. so that reason ahead of escape character we use backslash ("\").
in your case you can use backslash ("\") as...
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile.jpg\"rn"] dataUsingEncoding:NSUTF8StringEncoding]];


text:
Q: How to find all the namespaces with incorrect relatively to their location names in a solution? I am looking for a technique to find all the wrong namespace in solution.
With wrong namespace I mean all the namespaces that have a different from the current location.
For e.g.: If I have a project called MyCompany.MyProject.Frontend and I have a class under the Controller folder, the final namespace should be:
MyCompany.MyProject.Frontend.Controller
How can I find all the namespaces that doesn't follow this standard?
I know that Resharper offers this feature but currently we don't have a license for it.
Is there any free solution to this problem?

A: Why not just download and install the trial version, do what you need, and be then get rid of R#?
Otherwise, writing a simple parser with a search and replace shouldn't be hard, just "fiddly" and time-consuming to get exactly right.
However, as soon as you do this, you are going to run into the problem that all of your previous includes statements will need to be modified to include the new namespaces, which R# will do for you as part of it's operations.
Seriously, just use R# as a free trial, and get what you need from it.  Even better, just buy  a copy for yourself... I've gotten my $150 worth.


text:
Q: Make my notification clickable I made an app with a notification that is triggered by an alarmmanager, only the notification is'nt clickable. How do I do this?
Code from MainActivity:
private void scheduleNotification(Notification notification, int delay) {

    Intent notificationIntent = new Intent(this, NotificationPublisher.class);
    notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, 1);
    notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    long futureInMillis = SystemClock.elapsedRealtime() + delay;
    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
}

    private Notification getNotification(String titel, String content) {
    Notification.Builder builder = new Notification.Builder(this);
    builder.setContentTitle(titel);
    builder.setContentText(content);
    builder.setSmallIcon(R.mipmap.ic_launcher);
    return builder.build();
}

code from my notification publish class:
public class NotificationPublisher extends BroadcastReceiver {

public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";

public void onReceive(Context context, Intent intent)
{

    NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);

    Notification notification = intent.getParcelableExtra(NOTIFICATION);
    int id = intent.getIntExtra(NOTIFICATION_ID, 0);
    notificationManager.notify(id, notification);

}

}

A: You are probably looking for the method
setContentIntent(PROVIDE_YOUR_PENDING_INTENT);

You will need to provide a pending intent to where you want to redirect the user when he click on the notification.
Reference: http://developer.android.com/reference/android/app/Notification.Builder.html#setContentIntent(android.app.PendingIntent)


text:
Q: Inclusion or element? Hello people I want to make sure my work is correct !
{1} --- {1,{1,{1}}}
its a subset only since here the element {1} isn't inside that set however it is a subset.
{{1}} is not an element or subset of {1,{1,{{1}}}}

A: Notice here a good way of looking at it is for the first question is that {1} is the set of element 1, so we can see it is indeed a element of that set, and the second one is the set with element {1} and that particular element isn't in our set.


text:
Q: EJB Timer Service: order of timeouts I have two timeouts defined:
timeout A - every 30 seconds
timeout B - every 2 minutes
// scheduled for timeout A (every 30sec)
@Stateless
public class MyBeanA {
   (...)

   @Timeout
   public void onTimeoutA(javax.ejb.Timer timer) {
     // (...)
   }
}

// scheduled for timeout B (every 2min)
@Stateless
public class MyBeanB {
   (...)

   @Timeout
   public void onTimeoutB(javax.ejb.Timer timer) {
     // (...)
   }
}

It's easy to notice, that after every 2 minutes, both timeouts will be fired. I'd like to make sure that in this case, timeout A will be fired before timeout B:
(30sec): timeoutA, (60sec): timeoutA, (90sec): timeoutA, (120sec): timeoutA, timeoutB
Is it possible with standard EJB (3.0) Timer Service API?
My application server is JBoss.
Thanks in advance,
Piotr

A: There is no built-in way to order timers like that.  You could do it manually:

*

*Schedule a single-action timer for A in 30 seconds with info=1

*Schedule an interval timer for B for 120 seconds

*When A fires with info=1, schedule a single-action timer for A in 30 seconds with info=2

*When A fires with info=2, schedule a single action timer for A in 30 seconds with info=3

*When A fires with info=3, don't reschedule

*When B fires, call A, then do the work for B.  Schedule a single-action timer for A in 30 seconds with info=1

A: Solution I used is very similar to the one given by bkail.
There is one ejbTimeout() method scheduled to be fired every 30seconds. Timeout is scheduled with Serializable object containing counter:
createTimer(Date initialExpiration, long intervalDuration, Serializable info)

Every time ejbTimeout is called, counter is increased. If it reach 3, then method which should be fired after 2 minutes is invoked, and also counter is set back to 0. It works as below:

ejbTimeout after 30sec (counter == 0): call A(); counter++;
ejbTimeout after 30sec (counter == 1): call A(); counter++;
ejbTimeout after 30sec (counter == 2): call A(); counter++;
ejbTimeout after 30sec (counter == 3): call A(); call B(); counter = 0;


text:
Q: Rails precompile vendor/asset I am trying to precompile files in vendor assets folder.
In rails console in production I am getting this:
puts Rails.application.config.assets.precompile
#<Proc:0x000000023b2110@/home/pills/.rvm/gems/ruby-2.1.0/gems/sprockets-rails-2.1.3/lib/sprockets/railtie.rb:40 (lambda)>
(?-mix:(?:\/|\\|\A)application\.(css|js)$)
(?-mix:.*.png)

puts Rails.application.config.assets.paths
/media/pills/be3eb155-9e10-4a71-9737-c82606a3dbd4/home/ububtu/code/ccr/app/assets/fonts
/media/pills/be3eb155-9e10-4a71-9737-c82606a3dbd4/home/ububtu/code/ccr/app/assets/images
/media/pills/be3eb155-9e10-4a71-9737-c82606a3dbd4/home/ububtu/code/ccr/app/assets/javascripts
/media/pills/be3eb155-9e10-4a71-9737-c82606a3dbd4/home/ububtu/code/ccr/app/assets/stylesheets
/media/pills/be3eb155-9e10-4a71-9737-c82606a3dbd4/home/ububtu/code/ccr/vendor/assets/chosen
/media/pills/be3eb155-9e10-4a71-9737-c82606a3dbd4/home/ububtu/code/ccr/vendor/assets/javascripts
/media/pills/be3eb155-9e10-4a71-9737-c82606a3dbd4/home/ububtu/code/ccr/vendor/assets/stylesheets
/home/pills/.rvm/gems/ruby-2.1.0/gems/turbolinks-2.2.2/lib/assets/javascripts
/home/pills/.rvm/gems/ruby-2.1.0/gems/jquery-rails-3.1.0/vendor/assets/javascripts
/home/pills/.rvm/gems/ruby-2.1.0/gems/coffee-rails-4.0.1/lib/assets/javascripts

The last part in precompile is got in production by:
config.assets.precompile += [/.*.png/]

Why is the png file in chosen folder not being precompiled?
If I copy the png to app/assets/images, it works, I will solve the problem that way for now.

A: Try this:
config.assets.precompile << /\.(?:png)\z/

I don't know where is feature here, but when I changed my code from like yours version to this, it suddenly started to work as expected. I can only suggest, that it happens because you put unescaped dot character in regexp and it can not match filename.


text:
Q: repo : fatal: cannot create directory at 'pathtools/testdata/escapes/**': Invalid argument / > rsync error: some files/attrs were not transferred I'm trying to create an AOSP image intended to be run on the Nvidia Jetson Nano platform. To to this,I need to clone the repo from this page :
https://github.com/antmicro/kvm-aosp-jetson-nano
According with the tutorial,these are the commands that should be issued :
Fetch and install the repo tool
mkdir -p ~/bin
PATH=~/bin:$PATH
curl https://storage.googleapis.com/git-repo-downloads/repo > ~/bin/repo
chmod a+x ~/bin/repo

Fetch the AOSP sources

mkdir aosp
cd aosp
repo init -u https://github.com/antmicro/kvm-aosp-manifest.git -b kvm-aosp
repo sync

.......
the problem is that at some point I see this error message :
error: unable to create file pathtools/testdata/escapes/*: Invalid argument
fatal: cannot create directory at 'pathtools/testdata/escapes/**': Invalid argument
error: Cannot checkout platform/build/blueprint: GitError: Cannot initialize work tree for platform/build/blueprint
Updating files: 100% (595/595), done.
Updating files: 100% (12659/12659), done.

and the download FREEZED. I would like to know how to fix this. thanks. I'm using ubuntu 20.10 and this version of repo :
root@ziomario-Z390-AORUS-PRO:/home/ziomario# repo --version
<repo not installed>
repo launcher version 2.12
       (from /usr/bin/repo)
git 2.27.0
Python 3.8.6 (default, Jan 27 2021, 15:42:20)
[GCC 10.2.0]
OS Linux 5.8.0-44-generic (#50-Ubuntu SMP Tue Feb 9 06:29:41 UTC 2021)
CPU x86_64 (x86_64)

As u can see below,there are some special characters inside this folder :

I think that repo sync is not able to get them from the server. I have the same problem when I try to copy the whole repository from from a place to another one on my disk using this command :
sudo rsync -avxHAX source destination

In this case the error is this :

rsync error: some files/attrs were not transferred (see previous
errors) (code 23) at main.c(1330) [sender=3.2.3]

its happened one time only that I've been able to copy the whole repo from the server without getting errors. So I have those characters correctly copied on my disk. But I can't copy them to another place of my disk and when I try again to clone the repo,it always give the error. I think that's an odd behavior and I want to understand the reasons behind this.

A: I encountered the same problem while trying to sync with a different android manifest. The drive I was trying to sync to was formatted in ntfs (mounted in linux via udisksctl).
To ensure compatibility with windows systems udiksctl (or whatever tool your installation uses manage mountpoints) mounts ntfs filesystems with the windows_names option which blocks any files with symbols not supported by windows.
Try remounting your drive without this option.
For example:
umount /dev/sdx
mkdir /mnt/ntfs
ntfs-3g /dev/sdx /mnt/ntfs


text:
Q: read every 5th line in a data file and append to a new list I am trying to seperate every 5th line to append to a new file, the first line of each five line has the data I need, this is the only way that I have not had any errors but the output when I print the second line (as a test) of the new datafile which should be the sixth line of my original file, returns the second line of the original file and the len of my new data should only be around 2400 line not 202571 lines. Once I get just the line needed I can get the data to put into a kml file.
dataList = []
line_count = 0
for line in lineList:
    line_count+= 5
    dataList.append(line)
    line_count += 5
print (format(len(dataList)))
print (dataList [1])

202571
M010176A         B:  0    0   0 S:  0    0   0 M: 12   30 135 CMT: 1 BOXHD:          9.4

A: I think you are using wrong logic while iterating loop. Your code looks like following.
dataList = []
line_count = 0
for line in lineList:
    line_count+= 5
    dataList.append(line)
    line_count += 5

In above code, you are appending every line to dataList, no matter what! Because there is no logic to check if it's fifth line and then append to a list.
Following changes may let you achieve your goal.
line_count = 4
for line in lineList:
    line_count += 1
    if line_count == 5:
        line_count = 0
        dataList.append(line)

Rest of your code will work fine after applying these changes. Hope it helps!

A: Here's an easy way to do it:  It will iterate through all the lines and check to see if the line is divisible by 5, hence the % 5. If you want it to start at 0, simply remove the + 1 . If you are just trying to output this to a file, I think it would be better to simply speed up the process by writing as you read the other file.  If you want me to, I can modify it back, just comment if you need any help.
dataList = []
with open("in.kml", "r") as fi:
    for i, line in enumerate(fi):
        if (not (i % 5)):
            dataList.push(line)

A: If you just want to output every fifth line, then the Python islice() function will help you as follows:
from itertools import islice

with open('input.txt') as f_input, open('output.kml', 'w') as f_output:
    for fifth in islice(f_input, 0, None, 5):
        f_output.write(fifth)


text:
Q: Tag DIV excedendo a largura tenho meu portfólio e tenho alguma <div> está estourando a largura, porém não encontro.
Link para o site

na imagem o overflow

A: O div que está "estourando" a width está localizado na linha 473(basicamente é o div que introduz a informação do facebook).
Adicione:
style="width:auto;"

No Div em causa e o problema deverá ficar resolvido.
Caso não fique, utilize a funcionalidade 3D oferecida pelo firefox e procure pelo elemento que está a sair da resolução do display.


text:
Q: Can we replace find_packages with find_namespace_packages in python 3.3 onwards and get rid of the empty init.py files? I have a distribution with multiple package and sub packages. There are many empty __init__.py files used to tell setuptools that the folders are packages.
In python 3.3 onwards, setuptools supports find_namespace_packages. So is it a good idea to get rid of the empty __init__.py files and replace the find_packages with find_namespace_packages?

A: There are three ways to namespace packages, each with its own pros and cons. It is true that find_namespace_packages is the recommended solution for Python3+ projects; though remember that this does not mean you omit all __init__.py files, you only remove the __init__.py in the namespace root.


text:
Q: Get a c++ object in QML and use it in javascript I'm making an application in which I'd like to call a function from QML in C++ source, and that c++ function to return me and object which I can use it with the same properties in the javascript part of QML. I've made the connection and everything. I've tried to send a QVariantMap and tried to use that object in javascript, but I don't get the properties of that object

A: There are two ways for exporting QObject based types from C++ to QML:

*

*Return standalone QObject directly from property READer or Q_INVOKABLE function. Note, object returned as a property has C++ ownership, Q_INVOKABLE-object has JS ownership. You can change this default behaviour via http://doc.qt.nokia.com/4.7/qdeclarativeengine.html#setObjectOwnership.

*Return array of QObjects. In that case you should use QObjectList, QDeclarativePropertyMap (not QVariantMap) or QAbstractListModel.

A: Your classes to be exposed have to inherit from QObject (or QDeclarativeItem if they are UI components) and you will have to register their types in your main() or in a Qt plugin before loading the QML code.
Have a look at http://developer.qt.nokia.com/doc/qt-4.7/declarative-tutorials-extending-chapter1-basics.html

A: To pass an object from C++ to QML as a function return value, the return value type needs to be QVariant, not QVariantMap, even though that is the type in the C++ code. So just change your initialize function signature to
QVariant initialize();

without changing anything else, and then you can access the properties.
Regarding your later comment on wanting to call methods on that returned object, that is not possible; the returned object is just a set of name-value pairs. If you want the object to have, say, an id property, you need to insert a value with that key to the QVariantMap in C++ before returning it.