text:
Q: How can I avoid adding item template twice or more in project template? I have a project template and whenever I try to add an item template, it's created in the right place (folder) but also adds the item in the first folder added to the project. How can i fix this?
Code:
if (project.Kind == PrjKind.prjKindCSharpProject) {
 itemPath = solution.GetProjectItemTemplate("PriClass.zip", "CSharp");
 fileExtension = ".cs";
} else {
 itemPath = solution.GetProjectItemTemplate("PriClass.zip", "VisualBasic");
 fileExtension = ".vb";
}

if (!String.IsNullOrEmpty(itemPath)) {
 foreach(MyTreeNode type in selectedTypes) {
  string[] namespaceParts = type.Namespace.Split('.');

  if (namespaceParts.Length == 4) {
   this.Module = namespaceParts[2];
   this.ModuleType = namespaceParts[3];
   this.ClassName = type.NodeName;

   ProjectItem rootFolder = project.ProjectItems.Cast < ProjectItem > ()
    .FirstOrDefault(i => i.Name == this.Module) ? ? project.ProjectItems.AddFolder(this.Module);

   switch (this.ModuleType) {
    case "Editors":
     rootFolder.ProjectItems.AddFromTemplate(itemPath, "Ui" + this.ClassName + fileExtension);
     break;

    case "Services":
     rootFolder.ProjectItems.AddFromTemplate(itemPath, "Api" + this.ClassName + fileExtension);
     break;
   }
  }
 }

Project after created:

A: Try removing the "Template Data" content that is located in your case from the "PriClass.zip" folder.
This should be enough so that the "PriClass" folder does not come to seem like when you add an Item / Class.
Example:


text:
Q: Find limit of Fibonacci numbers. Let $\{a_n\}$ be the sequence of Fibonacci numbers, i.e. $a_1 = a_2 = 1, a_n = a_{n-1} + a_{n-2}, n \ge 3$. Find $$\lim_{n\to\infty}\sqrt[n]{a_n}.$$

A: All terms are strictly positive, hence a strictly increasing sequence of integers. Conclude.
UPDATE after problem statement modified.
Using the well known formula $F_n=\frac1{\sqrt5}\left(\phi^n-\frac1{(-\phi)^n}\right)$ obtained by solving the linear recurrence, you easily get that the limit is $\phi$.

A: Hint : for every $n \in \mathbb N$  ,  $F_n =\frac {(1+\sqrt 5)^n- (1-\sqrt 5)^n}{2^n\sqrt 5} $

redpajama_set_name: RedPajamaStackExchange


text:
Q: Integer vectors in the kernel of an integer matrix Let $A$ be a non-zero symmetric $n \times n$-matrix with integer entries and suppose that $\det(A) =0$.

Question: How long is the shortest non-zero integer vector in the kernel of $A$?

Example: If $A$ has non-zero eigenvalues $\xi_1,\dots,\xi_k$ (not necessarily counting with multiplicities), then the polynomial $p(t) = (\xi_1-t) \cdots (\xi_k -t)$ has integer coefficients. Hence, $p(A) \in M_n {\mathbb Z}$ and at the same time $Ap(A)=0$. Clearly,
$$p(A) = {\rm det}'(A) \cdot Q_{\ker(A)},$$
where $\det'(A) := \xi_1 \cdots \xi_k$ and $Q_{\ker(A)}$ denotes the orthogonal projection onto the kernel of $A$. Hence, we get for the operator norm $\|p(A)\| = |\det'(A)|$. Now, there exists an index $1 \leq i \leq n$, such that $v:=p(A)e_i \neq 0$ and one gets $\|v\| \leq \det'(A)$. At the same time $v$ has integer entries and lies in the kernel of $A$.
In many examples one can do much better. I would hope someone is able to bound the length in terms of the operator norm of $A$ alone. Is that possible?
The problem can also be phrased in terms of additive combinatorics. Indeed, if one identifies the image of ${\mathbb Z}^n$ under $A$ with ${\mathbb Z}^{k}$ for some $k < n$, then injectivity of $A$ on the set $X=\lbrace-m,\dots,m\rbrace ^n$ implies that $X$ can be embedded in ${\mathbb Z}^k$ preserving the addition whenever it made sense on $X$. This alone seems to require a lot of distortion, i.e. a large operator norm of $A$.
What kind of literature can be recommended?

A:
I would hope someone is able to bound the length in terms of the operator norm of   alone. Is that possible?

This is not possible. Consider the group ring $\mathbb ZC_k$ of the cyclic group $C_k$ of order $k$.
Consider $1-t\in \mathbb ZC_k$. As an operator on $l^2C_k$ it has 1-dimensional kernel generated by $v_k:=1+t+\ldots +t^{k-1}$.  Vector $v_k$ has arbitrary large length, yet the oeprator $1-t$ has a bounded norm.
If you want to get a symmetric operator use the standard trick, i.e. take $(1-t^{-1})(1-t)$ which has the same kernel and only slightly bigger norm.
I also thought about this question in relation to my recent question. I don't know what application do you have in mind, but maybe what you're looking for is a statement like this (using notation from my question): let $\mathcal M$ be a regular family of matrices recognized by an automaton $A$. Suppose there exists $M\in \mathcal M$ such that $\det M=0$. Then there exists a matrix $N\in \mathcal M$ and a vector $v\in \mathbb Z^{\dim N}$ such that $Nv=0$ and the length of $v$ can be bounded by "size of $A$".
"Size of $A$" is some function which depends only on number of letters in the alphabet of $A$ and number of states of $A$. I'm not sure yet the above statement is true but, well, I'm "convinced" it is :-).
The family of operators $1-t$ above gives rise to a regular family of matrices if we allow finite automata which work with a circular tape.


text:
Q: Drop caps resulting in different letter height in Firefox My entire website looks nice on Chrome. When I tested it in Firefox however, I noticed the height of the drop cap is too high. Examine the good positioning height left in Chrome, and the way too high positioning on the right in Firefox:
Chrome:    . . . . . . . . . . . . . . . .  . .           Firefox:
   . . . . .
column:first-of-type p:first-of-type:first-letter{/* Drop Caps */
    font-size: 3.4em;
    margin: 0 0 -0.1em 0;
    padding: 0 0 0 .75em;
    line-height: 1em;
    float: left;
}

What can be tweaked here just for Firefox specifically to bring the height back a little, making it mimic the Chrome rendering?
I don't care about the other differences, I just want the black letter on Firefox to be a little lower.


text:
Q: Solution of $y''+5y'+6y=2e^{-x}$ I need to find the solution for $y''+5y'+6y=2e^{-x}$.
I already found the $Yh y=Ae^{-2x}+Be^{-3x}$.
But I am stuck to find the $Yp$. How can I find it?
I just assume $Y=kxe^{-x}$ is solution and find the $Y'$ and $Y''$.
But after I substitute $Y$, $Y'$, and $Y''$ to the first equation, I am stuck to $3k+2kx = 2$. What should I do?
It is said that the $Yp$ is $e^{-x}$.How?

A: To try a particular solution (Particular Integral) of this differential equation, you should look for terms involved in $f(x)=2e^{-x}$ and its derivatives and those would be only be the constant multiples of $e^{-x}$
So, we take $y_p=ce^{-x}$, where c is a constant.
Here, it is noted that there is no duplication between the terms of $y_p$ and the terms involved in the complementary function of the given non-homogeneous equation. ($\because e^{-x}$ and either of $e^{-2x},e^{-3x}$ are linearly independent.) So, you don't have to multiply each term of $y_p$ by any power of $x$ to eliminate duplication.
After that, we substitute $y_p=ce^{-x}$ for $y$,  $y'_p=-ce^{-x}$ for $y'$, $y''_p=ce^{-x}$ for $y''$ in the non-homogeneous equation $y''+5y'+6y=2e^{-x} \tag{i}$
to get, $2ce^{-x}=2e^{-x} \implies c=1$
$\therefore y_p=e^{-x}$ satisfies the given differential equation (i).
In case you think that a term like $kxe^{-x}$ should be there in the particular solution, you can add that too but you can't drop the term $ce^{-x}$ which should be there to satisfy the differential equation (i). Thus by taking $y_p=kxe^{-x}+ce^{-x}$ and after doing the substitutions you'll see that this $y_p$ too satisfies (i) for $k=0, c=1$. The coefficient of any term which should not be there in the P.I. will eventually turn out to be zero.
The complementary function of (i) you got, $y_c=Ae^{-2x}+Be^{-3x}$ is correct. Hence the general solution of (i) is given by $y=y_c+y_p$
$\therefore y= Ae^{-2x}+Be^{-3x}+e^{-x}$ is the required general solution.

A: In general when the equation is of the form
$\phi(D)y=(D-m_{1})(D-m_{2})...(D-m_{n})y = e^{ax}$ where $D\equiv \frac{d}{dx}$ and $m_{1},m_{2},...m_{n}$ are non repeated distinct roots of the auxiliary equation and $\phi(D)$ denotes the polynomial in $D$ then the complimentary function(C.F) is given by :-
$C_{1}e^{m_{1}x}+C_{2}e^{m_{2}x}+...+C_{n}e^{m_{n}x}$ .
And the Particular Integral(P.I) = $\frac{1}{\phi(D)}e^{ax}=\frac{e^{ax}}{\phi(a)}$. Provided $\phi(a)$ is not zero. In cases of repeated roots and a being a zero of the polynomial of $kth-$order then there is a method to generalize this.
For your particular question the $\phi(D)=(D+2)(D+3)y=2e^{-x}$
So the solution is y=CF+PI :-
$$\displaystyle y=C_{1}e^{-2x}+C_{2}e^{-3x}+\frac{1}{(D+2)(D+3)}2e^{-x}=C_{1}e^{-2x}+C_{2}e^{-3x}+\frac{2}{(-1)\cdot (-2)}e^{-x}$$ .
You should read up on the operator method of solving differential equations. That would make things easier and more systematic to deal with.

A: Well, let's solve a more general DE using Laplace transform:
$$x''(t)+\text{n}x'(t)+(\text{n}+1)x(t)=\text{k}\exp\left(-x\right)\tag1$$
Taking the Laplace transform of both sides, gives:
$$\text{s}^2\text{X}\left(\text{s}\right)-\text{s}x(0)-x'(0)+\text{ns}\text{X}\left(\text{s}\right)-x(0)+(\text{n}+1)\text{X}\left(\text{s}\right)=\frac{\text{k}}{1+\text{s}}\tag2$$
Solving for $\text{X}\left(\text{s}\right)$ yields:
$$\text{X}\left(\text{s}\right)=\frac{\frac{\text{k}}{1+\text{s}}+\text{s}x(0)+x'(0)+\text{n}x(0)}{\text{s}^2+\text{ns}+\text{n}+1}=\frac{\frac{\text{k}}{1+\text{s}}+(\text{s}+\text{n})x(0)+x'(0)}{\text{s}^2+(\text{s}+1)\text{n}+1}\tag3$$
I let you find the inverse Laplace transform.


text:
Q: With what can I replace http deprecated methods? I was following a tutorial and I got to a point where a lot of the code is deprecated.
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("name", user.name));
dataToSend.add(new BasicNameValuePair("age", user.age));

HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParamas.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParamas.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);

HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "Register.php");

try{
    post.setEntity(new UrlEncodedFormEntity(dataToSend));
    client.execute(post);
}catch (Exception e){
    e.printStackTrace();
}

and another POST method that is returning a result
    HttpResponse httpResponse = client.execute(post);

    HttpEntity entity = httpResponse.getEntity();
    String result = EntityUtils.toString(entity);
    JSONObject jObject = new JSONObject(result);

I found that I can replace NameValuePair with
ContentValues values = new ContentValues();
values.put("name", user.name);
values.put("age", user.age + "");

but I have no idea about the others.

A:
I found that I can replace NameValuePair with

Not really.

but I have no idea about the others

The entire HttpClient API that ships with Android itself is deprecated. The solution is to use a different HTTP client:

*

*HttpUrlConnection, from standard Java

*third-party ones, like OkHttp

*Apache's repackaged HttpClient for Android
With respect to the tutorial, either:

*

*Use tutorials that do not use a deprecated HTTP API, or

*Port the tutorial to use Apache's repackaged HttpClient for Android, or

*Ignore the deprecation warnings

A: As CommonsWare told already in his answer the entire http client package has been deprecated with Android 23.0.0 build tool version. So we should better use some other API like HttpUrlConnection or any third part library like Volley or okHttp or retrofit.
But if you still want those all packages; you could add following dependency to your app's module gradle script:
dependencies {

compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'

}

and don't forget to add mavenCentral() in your project gradle script:
allprojects {
    repositories {
        jcenter()
        mavenCentral()
    }
}

After adding these; Just synchronize the project with gradle. And you'll be able to import and use these APIs again.
UPDATE:
Thank you @rekire for mentioning that in comment. Here I am adding that too, instead of using above mentioned dependency, you can just add useLibrary 'org.apache.http.legacy' in your android DSL of module's gradle script. Add it like below:
android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"
    useLibrary 'org.apache.http.legacy'
    //rest things...
}

Hope this will help to someone.

A: You can replace apache's HttpClient with HttpURLConnection

A: You should try Retrofit, it's more simple to use that library instead of perform http requests. It was made for simplify communication between java and REST API.
square.github.io/retrofit/
I give you a sample from the documentation
public interface GitHubService {
   @GET("/users/{user}/repos")
   List<Repo> listRepos(@Path("user") String user);
}

The RestAdapter class generates an implementation of the GitHubService interface.
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://api.github.com")
.build();

GitHubService service = restAdapter.create(GitHubService.class);

Each call on the generated GitHubService makes an HTTP request to the remote webserver.
List<Repo> repos = service.listRepos("octocat");


text:
Q: Has anyone used version control on PeopleSoft? We are looking at installing version control. We have found three that integrate with PeopleSoft: Phire, Grey Sparling, and Stat. Has anyone used these, and what experiences do you have with them?

A: I have a lot of experience with STAT, but not the other products.
The product does indeed succeed on its promise to deliver a change control system for PeopleSoft; versioning for objects, check in/check out, restore, etc.
The user interface, however, often makes me want to run screaming while pulling all my hair out.  It's clunky, ugly, and requires way too many clicks to get something done.  In a nutshell, it gets in your way.
Migrations (to UAT and prod) have been simplified for sure, but we also spent a lot of time up front writing our own post-migration processing scripts to fill in the gaps of things STAT does not do out of the box:   building a project, granting permissions to database tables as necessary, execute data mover scripts and/or sql....   These are all things that generally happen on a migration.   STAT provides "hooks" for events to occur, but it's kind of clunky out of the box.
So from a migrator or auditor perspective, it's awesome.
From a user perspective, it causes pain and slows the development process.

A: We switched from Stat to Phire and have been very happy. Phire runs on the same architecture as PeopleSoft, so there is no fat client software and the interface is much more user friendly. Also, Phire has features such as automating project build and running SQL and DMS scripts. Our developers actually like Phire because it provides for much better code comparison reports and easy access to previous code versions. Our migrators  love it because it makes migrations so much simpler.

A: Stat! is the best and most expensive.  There appear to be more coming on the market at lower prices.

A: I concur 100% with Chip L.  Stat is excellent for a migrator or auditor, but clunky.
Clunkyness aside, the ability to sync App Designer projects into a Stat CSR is very nice.  For example, you can load up a project, start developing, adding new objects, etc. then just hop over to Stat, click "Sync Project" and Stat now has all your objects and (pending any object contention) is ready for you to snapshot.


text:
Q: SSDP Device Discovery for Application in Java I have some hardware devices connected to a specific network and I have a Java application also running in the same network. I now need to detect these devices from my Java application. The specification is like this:

*

*My Java program has to send a UDP packet with a host name
{"type":"HW-PROBER","hostname":"Host-NAME"}

*The hardware upon receipt of this message sends me back a response with the NOTIFICATION in the form of a Payload that looks like this:
{"type":"HW-NOTIFY","hostname":"Host-NAME","ip":"1.2.3.4"}
So this way, my Java application has to get the ip address of the hardware and start communicating with it. I'm totally unclear on how to do the device discovery. Would this mean that my Java application has to open a port say at 5000 (for example.,) and keep waiting for packets? What sort of API from the Java standard library should I be using?


text:
Q: Handling console close in MFC dialog based application I have written code that allocates a console and redirects the output of my MFC dialog based program to that console.  If I close the console window, it will close my program, I get a large memory leak. Is there a way to listen for the console closing and stop sending data to it? Below are the code snippets where I allocate the console and write to it. In my destructor I call FreeConsole().
if (consoleEnabled)
{
  AllocConsole(); //Allocate the console

  FILE* pCout;

  if (freopen_s(&pCout, "CONOUT$", "w", stdout) != 0)     //redirect the stdout
  {
    this->consoleEnabled = false;
  }
}

//in another function...
if (consoleEnabled)
{
  std::cout << outputMsg << std::endl;
}


text:
Q: Color in PDFs created from LaTeX that shouldn't be there I am a publisher who works with PDFs that authors submit that were created from LaTex. Often the PDF is in color and the author can't fix this issue. Has anyone had this issue and is there a quick fix I can point our authors too?

A: You could remove \usepackage{xcolor} or \usepackage{color} from the preamble, and see what breaks.  But the chances are that loading colour-support is actually done by the graphicx package (manual).  This package supports an option monochrome which should do what you want.  To apply this option just change \usepackage{graphicx} to
\usepackage[monochrome]{color}
\usepackage{graphicx}

The colour model used is unlikely to be the issue as a simple
\documentclass{article}
\begin{document}
Hello world
\end{document}

is in the sRGB colour space according to identify (ImageMagick):
test.pdf PDF 595x842 595x842+0+0 16-bit sRGB 1.503MB 0.000u 0:00.002
in fact even with \usepackage[cmyk]{xcolor} we still get sRGB according to ImageMagick.  This is all on Tex Live 2015/Windows.
As the expert (David Carlisle) pointed out in a comment below, none of this will deal with colour in images.  Some images may look monochrome but actually have colour components (scans for example).  In an answer to a related question I linked to a script that finds colour pages in a pdf by comparing the RGB channels of each pixel.  This may help you track down the offending pages, and hopefully the offending figures (if they are the issue).
For simply forcing pdfs to monochrome or greyscale, they are some suggestions at superuser, but they would need to be used with care.


text:
Q: Find a point, a given distance, along a simple cubic bezier curve. (On an iPhone!) Imagine you have a completely normal four-point bezier curve (two points and two control points) created using curveToPoint:controlPoint1:controlPoint2: in your cocoa application:

How do you find points (and the tangents), along the curve?

Later: for a complete, simplified, solution based on Michal's answer below, click to:
Find the tangent of a point on a cubic bezier curve (on an iPhone)
And just copy and paste the code from: https://stackoverflow.com/a/31317254/294884

A: There's some simple math behind calculating the positions, you can read about it in every paper discussing Bézier curves, even on wikipedia. Anyway, I can relate to everybody who's in trouble to actually implement it in code, so I wrote this sample UIView as it's probably the easiest way to get you started.
#import "MBBezierView.h"

CGFloat bezierInterpolation(CGFloat t, CGFloat a, CGFloat b, CGFloat c, CGFloat d) {
    CGFloat t2 = t * t;
    CGFloat t3 = t2 * t;
    return a + (-a * 3 + t * (3 * a - a * t)) * t
    + (3 * b + t * (-6 * b + b * 3 * t)) * t
    + (c * 3 - c * 3 * t) * t2
    + d * t3;
}

@implementation MBBezierView

- (void)drawRect:(CGRect)rect {
    CGPoint p1, p2, p3, p4;
    p1 = CGPointMake(30, rect.size.height * 0.33);
    p2 = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
    p3 = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));
    p4 = CGPointMake(-30 + CGRectGetMaxX(rect), rect.size.height * 0.66);

    [[UIColor blackColor] set];
    [[UIBezierPath bezierPathWithRect:rect] fill];

    [[UIColor redColor] setStroke];

    UIBezierPath *bezierPath = [[[UIBezierPath alloc] init] autorelease];
    [bezierPath moveToPoint:p1];
    [bezierPath addCurveToPoint:p4 controlPoint1:p2 controlPoint2:p3];
    [bezierPath stroke];

    [[UIColor brownColor] setStroke];
    for (CGFloat t = 0.0; t <= 1.00001; t += 0.05) {
        CGPoint point = CGPointMake(bezierInterpolation(t, p1.x, p2.x, p3.x, p4.x), bezierInterpolation(t, p1.y, p2.y, p3.y, p4.y));
        UIBezierPath *pointPath = [UIBezierPath bezierPathWithArcCenter:point radius:5 startAngle:0 endAngle:2*M_PI clockwise:YES];
        [pointPath stroke];
    }
}

@end

This is what I get:

A: The approximation that t is the distance along the curve that Michal is proposing can be troublesome with some curves and for some purposes. Sadly I've searched without luck for quite a while for an Obj-C implementation of the correct solution.
The solution is, however, described in a rather fantastic way by Mike "Pomax" Kamermans in his amazing Primer on Bezier Curves. It even has all the code, written in processing and in public domain. I'm astonished no one has converted this to Obj-C yet. Very tempted, that I am.

A: Any Beziér curve can be simply viewed as a polynomial function with vector or complex coefficients. A cubic Beziér curve such as the one in your screenshot, would then be generated by a polynomial function of order 3, and each point on the curve describes the result B(t) of the curve polynomial, evaluated for a particular input value t. If I'm not mistaken, once you know the polynomial used to create the curve, you can simply solve for B(t) = a+bi, where a+bi describes the point on the complex plane you want to find the t value for. Finding roots in polynomials like that is a well-understood problem, and can be solved algebraically for curves of order 2 or lower, and using some method like forward-newton for polynomials of higher degree. If you know the generating polynomial, it should of course also be very simple to find the derivatives. Beziér are usually drawn from "template polynomials" where only the coefficients are changed when a different curve is drawn, so you can probably look it up somewhere in the documentation.

A: Based on Michal's answer, wrote this in Swift for my project. Maybe will be helpful, just leave it here with explanation on original Fattie's screenshot:
let targetPoint = CGPoint(x: bezierInterpolation(t: distance, p1: sP1.point.x, cp1: sP1.nextMarker.x, cp2: sP2.previousMarker.x, p2: sP2.point.x),
                          y: bezierInterpolation(t: distance, p1: sP1.point.y, cp1: sP1.nextMarker.y, cp2: sP2.previousMarker.y, p2: sP2.point.y))

func bezierInterpolation(t: CGFloat, p1: CGFloat, cp1: CGFloat, cp2: CGFloat, p2: CGFloat) -> CGFloat {
    let t2: CGFloat = t * t;
    let t3: CGFloat = t2 * t;
    return p1 + (-p1 * 3 + t * (3 * p1 - p1 * t)) * t
    + (3 * cp1 + t * (-6 * cp1 + cp1 * 3 * t)) * t
    + (cp2 * 3 - cp2 * 3 * t) * t2
    + p2 * t3;
}


text:
Q: Set SSL connection for CachingConnectionFactory I want to set SSL connection factory for CachingConnectionFactory. I tried this:
com.rabbitmq.client.ConnectionFactory cf = new ConnectionFactory();
cf.setHost(HOST);
cf.setPort(PORT);
cf.setUsername(USERNAME);
cf.setPassword(PASSWD);
cf.setVirtualHost(VIRTUAL_HOST);
cf.setAutomaticRecoveryEnabled(false);
cf.setConnectionTimeout(10000);
if (useSSL) {
    try {
        cf.useSslProtocol(sslContextConfiguration());
        System.out.println("Configuring SSL context...");
        } catch (IOException | TimeoutException e) {
        e.printStackTrace();
        }
}
connectionFactory = new CachingConnectionFactory(cf);
connectionFactory.setAddresses(ADDRESSES);
connectionFactory.setChannelCacheSize(25);
admin = new RabbitAdmin(connectionFactory);

So far the only solution that I found is to set useSslProtocol for com.rabbitmq.client.ConnectionFactory and set it to CachingConnectionFactory(cf).
Is there some better way?

A: CachingConnectionFactory is now capable of auto-setting SSL by using URI instead of hostname:
connectionFactory.setUri("amqps://xxx");

enables SSL in the background

A: What you are doing is correct; the framework does provide a factory bean for the rabbit factory, but that's really to make is easier to configure when using spring XML configuration.

Is there some better way?

So, there is no "better way" to turn on SSL, except, as I've now said to you several times over the last couple of weeks...
connectionFactory = new CachingConnectionFactory(cf);
admin = new RabbitAdmin(connectionFactory);

...you really should let Spring manage these objects for you instead of using new....
EDIT
Also see the spring boot property in the appendix
spring.rabbitmq.ssl.enabled=false # Whether to enable SSL support.
and boot will auto-configure SSL for you.


text:
Q: How to muxing a HEVC Annex B raw video file into a TS containter without changing its start code with ffmpeg I researched for a while and had read Multiplex a HEVC-Video into a MPEG-Transportstream with FFMPEG and Convert H.264 Annex B to MPEG-TS
but non of these answer my question.
 I tried ffmpeg -y -f hevc -i out.h265   -c copy -f mpegts output1.ts
but it got 2 errors:
[mpegts @ 00000230d3bad2c0] Timestamps are unset in a packet for stream 0. This is deprecated and will stop working in the future. Fix your code to set the timestamps properly.
[mpegts @ 00000230d3bad2c0] first pts value must be set
av_interleaved_write_frame(): Invalid data found when processing input
How can i wrap a HEVC Annex B into .ts file without changing its start code?.
Thank you.


text:
Q: Is it portable to reference the request parameter map after a request-cycle? I'd like to know if its conform to the java servlet specification 2.5 to reference/save the return value of request.getParameterMap() between requests.
The final specification only states at page 203:
Returns: an immutable java.util.Map containing parameter names as keys
and parameter values as map values. The keys in the parameter map are of
type String. The values in the parameter map are of type String array.
But it's not clear to me:

*

*if the Map is only immutable to the application, not to the application server

*if it's allowed that the application server may re-use the instance for another request (for example, if the parameters and their values are the same as in the previous request)
EDIT:
The reason for this:
I'd like to save the request map of each request and in case of an error to print them out for diagnostic purposes.

A:
if the Map is only immutable to the application, not to the application server

It's immutable in the API, yes. It also makes sense, what's the point of changing the request parameter map? The servletcontainer implementation in turn can of course hold of a mutable map of it "behind the scenes". But you should not worry about the implementation specific details.

if it's allowed that the application server may re-use the instance for another request (for example, if the parameters and their values are the same as in the previous request)

No, the server doesn't do that. It just creates a new one. The parameters are bound to a specific request.
If you want to collect the parameters of every request during a session, then you need to do this yourself. The best place for this would be a Filter.
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
    HttpServletRequest hsr = (HttpServletRequest) request;
    List<Map<String, String[]>> allParameters = (List<Map<String, String[]>>) hsr.getSession().getAttribute("allParameters");
    if (allParameters == null) {
        allParameters = new ArrayList<Map<String,String[]>>();
        hsr.getSession().setAttribute("allParameters", allParameters);
    }
    allParameters.add(hsr.getParameterMap());
    chain.doFilter(request, response);
}

A: For all intents and purposes, you cannot modify the contents of the map. However, if you want to keep for future reference, you can always create a new map of your own, copy over all the key/value pairs, and keep it in the Session f.e. (That will cause funkiness if the user has 2 windows open at the same time, but that story is for another time...)

A: I think you can safely save it for next request. I do this all the time.
Not sure about other implementations. It creates a new HashMap for every requests in Tomcat,
    parameters = new HashMap();
    parameters = copyMap(getRequest().getParameterMap());
    mergeParameters();
    parsedParams = true;


text:
Q: Signing and Verifying rsa signature in polarssl c I am working on using RSA encryption in an embedded system. for this i'll be using polarssl code.
I had got the encryption working on 128 bit but i am having trouble with the signature part.
When i run the code, i get a padding error on the verify (POLARSSL_ERR_RSA_INVALID_PADDING                   -0x4100)
Below is the code. Problem code is towards the end and the top lines are about the encryption. Still helpful for background info.
int main()
{
    size_t len;
    rsa_context rsa;
    unsigned char rsa_plaintext[PT_LEN];
    unsigned char rsa_decrypted[PT_LEN];
    unsigned char rsa_ciphertext[KEY_LEN];
    unsigned char rsa_hash[PT_LEN];
    unsigned char rsa_sig_out[PT_LEN];
    unsigned char rsa_hash_result[PT_LEN];

rsa_init( &rsa, RSA_PKCS_V15, 0 );
rsa.len = KEY_LEN;

mpi_read_string( &rsa.N , 16, RSA_N  );
mpi_read_string( &rsa.E , 16, RSA_E  );
mpi_read_string( &rsa.D , 16, RSA_D  );
mpi_read_string( &rsa.P , 16, RSA_P  );
mpi_read_string( &rsa.Q , 16, RSA_Q  );
mpi_read_string( &rsa.DP, 16, RSA_DP );
mpi_read_string( &rsa.DQ, 16, RSA_DQ );
mpi_read_string( &rsa.QP, 16, RSA_QP );

// Checking the public and private keys
if( rsa_check_pubkey(  &rsa ) != 0 ||
    rsa_check_privkey( &rsa ) != 0 ) {
    printf( "Public/Private key error! \n" );
    exit(0);
}

memcpy( rsa_plaintext, RSA_PT, PT_LEN );

if( rsa_pkcs1_encrypt( &rsa, &myrand, NULL, RSA_PUBLIC, PT_LEN,
                       rsa_plaintext, rsa_ciphertext ) != 0 ) {
    printf( "Encryption failed! \n" );
    exit(0);
}
if( rsa_pkcs1_decrypt( &rsa, &myrand, NULL, RSA_PRIVATE, &len,
                       rsa_ciphertext, rsa_decrypted,
                       sizeof(rsa_decrypted) ) != 0 ) {
    printf( "Decryption failed! \n" );
    exit(0);
}
if( memcmp( rsa_decrypted, rsa_plaintext, len ) != 0 ) {
    printf( "Compare failed! \n" );
    exit(0);
}
printf("Oh when it all falls down!\n");

// Signing and Verifying message
sha2(rsa_plaintext, len, rsa_hash, 0); //hashing the message
if (rsa_pkcs1_sign( &rsa, &myrand, NULL, RSA_PRIVATE, SIG_RSA_SHA256, 0, rsa_hash, rsa_sig_out ) != 0) {
    printf( "Signing failed! \n" );
    exit(0);
}
/*
if (rsa_pkcs1_verify( &rsa, NULL, NULL, RSA_PUBLIC, SIG_RSA_SHA256, 0, rsa_sig_out, rsa_hash_result ) != 0) {
    printf( "Verifying signature failed! \n" );
    exit(0);
}
*/
printf("Error Message!:%d \n", rsa_pkcs1_verify( &rsa, NULL, NULL, RSA_PUBLIC,
SIG_RSA_SHA256, 0, rsa_sig_out, rsa_hash_result ));
exit(0);

if( memcmp( rsa_hash, rsa_hash_result, len ) != 0 )
{
    printf( "Signature not verified! \n" );
    exit(0);
}
rsa_free(&rsa);

return 0;

}
Anybody know how i can solve this and go on ahead. Please let me know. Thanks I am running this on MinGw gcc compiler for windows. The rsa code has dependencies on bignum, md and sha2.

A: The reason why the hash fails is because you didn't fill rsa_hash before signing or rsa_hash_result before verification.
rsa_pkcs1_sign() and rsa_pkcs1_verify() sign and verify the hash presented. They do not make the hash as they do not know the data. (i.e. rsa_plaintext and rsa_ciphertext never enter the sign or verify functions).
So before you call rsa_pkcs1_sign() you should run sha256(rsa_plaintext, rsa_hash); or sha256(rsa_ciphertext, rsa_hash); (depending on how your 'protocol' works).
Then before verify, you run sha256(XXX, rsa_hash_result); and provide that value to rsa_pkcs1_verify() so that it can actually verify your hash.


text:
Q: Basic expectation calculation logic Consider a random permutation $\sigma_{n}$ of $n$ distinct numbers from $1$ to $n$. Let $X_{n,k}$ denote the number of increasing subsequences of length $k$ over the random permutation $\sigma_{n}$. Find the expected value of $X_{n,k}$.
This problem is in the context of proving an upper bound on the expectation. This is discussed in the article here (Lemma 1.4, page 9). The argument and the answer is very trivial but I cannot wrap my head around that $$E(X_{n,k}) = {1 \over k!} {n \choose k}$$ This looks more like probability than expectation. Also, how does $X_{n,k}$ define over expectation? Is there a way to do the counting using some indicator variables?

A: Sure, we can use indicator functions here.
We are given a sequence $a_1, a_2, \dots, a_n$ which is a random permutation of $1,2,\dots,n$.
There are $\binom{n}{k}$ subsequences of this sequence of length $k$. For each such subsequence $s$, let $I_s$ be the random variable which is the indicator function of that subsequence being increasing, that is:
$$
I_s =
\left\{
 \begin{array}{ll}
  0  & \mbox{if } s \text{ not increasing} \\
  1 & \mbox{if } s \text{ increasing}
 \end{array}
\right.
$$
Now, $X_{n,k} = \displaystyle\sum_{s} I_s$, so we have:
$$
E(X_{n,k}) = \displaystyle\sum_{s} E(I_s)
$$
But the probability that a given subsequence $s$ of length $k$ is increasing is precisely $\frac{1}{k!}$, so for each $s$,
$$E(I_s) = \frac{1}{k!}$$
Thus we have:
$$E(X_{n,k}) = \displaystyle\sum_{s} E(I_s) = \frac{1}{k!} \binom{n}{k}$$


text:
Q: VMWare gets stuck after trying to copy a large file I'm using WMWare Workstation in a Windows 10 host, with a Windows 10 guest machine. I tried copying a large file (50 Mb.) from host to guest. The copy got stuck after a few minutes, and VMWare became unresponsive: whenever I tried stopping it I got the message "The guest VM is busy", or something like that. In the end I had to use Task Manager on the host to kill it.
So, I deleted the stuck VM with all the temp files and restored it from a backup, with all the .vmdk, .vmx, .vmxf, .nvram, .vmsd... files. But when I tried to start the fresh VM, it got stuck again: the VM didn't even boot, it just showed a black screen and became just as unresponsive as before.
So, what can I do to recover this VM? (And by "recover" I mean being able to boot it normally again). I thought I had "cleaned" everything up by deleting the VM's files, but perhaps I missed something?

A: (1) VM will not start.
Those files above are the correct files for a Windows guest.
Make sure your backup is secure.
Copy the folder to a new location within your Virtual Machine folder.
In VMware Workstation make a new VM and point it to settings file in this new folder. See if you can see the settings and make sure all the settings are correct.
See if you can open the guest machine.  Let us assume so.
If, however, the temp files you deleted included non-committed snapshots, then you may not be able to re-create the machine. In this case, you would need to build a new machine.
(2) Copy a large file:
Make sure you are using VMware Workstation V15.5.6 (newest) and update if you need to.
Map the folder of the host machine in the guest using the NET USE and IP address.
In the guest machine, make sure you see the host folder as a drive letter. This is a mapped connection, not a browsed connection.
See if you can copy the file. I just copied a 600 MB file from host to guest with VMware Workstation V15.5.6 with no difficulty. No stalling.


text:
Q: Clicking on a marker clicks the layer below it (Mapbox-gl) When I click a marker on the map, the click will also be registered by the onclick listener of the trail running below the marker. How could I stop this from happening? I want the click to only be registered by the marker's onclick listener.

Code for the marker:
var el = document.createElement('div');
    el.className = 'marker';
    el.addEventListener('click', () => {
        //functions
    })

    const marker = new mapboxgl.Marker(el)
      .setLngLat([location.longitude, location.latitude])
      .addTo(this.map);

Code for the layer:
map.addLayer({
        "id": "route",
        "type": "line",
        "source": {
          "type": "geojson",
          "data": path
        },
        "layout": {
          "line-join": "round",
          "line-cap": "round"
        },
        "paint": {
          "line-color": "#888",
          "line-width": 8
        }
      });

A: Try capturing the event and stopping its propagation:
el.addEventListener('click', e => {
    e.stopPropagation();
    //functions
}, true);


text:
Q: "Fun with Rotation" - Codechef September Long Challenge Whatz wrong with that answer?Plz help me
question is:
You are given an array A of N integers. You are to fulfill M queries. Each query has one of the following three types:
C d : Rotate the array A clockwise by d units.
A d : Rotate the array A anticlockwise by d units.
R d : Query for the value of the element, currently being the d-th in the array A.
Input
The first line contains two numbers - N and M respectively.
The next line contains N space separated Integers, denoting the array A.
Each of the following M lines contains a query in the one of the forms described above.
Output
For each query of type R output the answer on a separate line.
Constraints
1 ≤ N ≤ 100000
1 ≤ M ≤ 100000
1 ≤ d ≤ N, in all the queries
1 ≤ elements of A ≤ 1000000
The array A and the queries of the type R are 1-based.
Example
Input:
5 5
5 4 3 3 9
R 1
C 4
R 5
A 3
R 2
Output:
5
3
3
Solution:
#include<stdio.h>
//#include<iostream>
//using namespace std;
int a[100001];
int index=0,n;

void clock(int);
void ant_clock(int);
void display(int);

int main()
{
    unsigned int i,m;
    char x;
    int y;
    scanf("%d %d",&n,&m);
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    while(m--)
    {
        scanf(" %c%d",&x,&y);
        if(1 <= y <= n)
        {
            if(x=='R')
                display(y);
            else if(x=='A')
                ant_clock(y);
            else if(x=='C')
                clock(y);
        }
        else
            return 0;
    }
    return 0;
}

void display(int y)
{
    int j=index,x=0;
    while(1)
    {
        if(x==y-1)
            break;
        j++;
        x++;
        if(j==n)
            j=0;
    }
    printf("%d",a[j]);
}

void ant_clock(int y)
{
    int j;
    for(j=0;j<y;j++)
    {
        index--;
        if(index==-1)
            index=n-1;
    }
}

void clock(int y)
{
    int j;
    for(j=0;j<y;j++)
    {
        index++;
        if(index==n)
            index=0;
    }
}

A: It seems to be a problem with the query indices being 1-based. And your code has unnecessary loops in it.
#include <stdio.h>

int arr[100000];

int main() {
    int base = 0, size, i, m;
    char x;
    scanf("%d%d", &size, &m);
    for (i = 0; i < size; i++)
        scanf("%d", &arr[i]);
    while (m-- > 0) {
        scanf(" %c%d", &x, &i);
        if (x == 'R') {
            printf("%d\n", arr[(base + i - 1) % size]);
        } else if (x == 'A') {
            if ((base -= i) < 0)
                base += size;
        } else if (x == 'C') {
            base = (base + i) % size;
        }
    }
    return 0;
}


text:
Q: How to get more than 3 international clocks in Windows? Is there a way to get more than 3 international clocks in Windows Vista (or later)?
This How To Geek article describes how to add two extra international clocks but I'd like more.

A: Here are the steps:

*

*Right-click on the desktop

*Pick Gadgets

*Drag a Clock to the desktop

*Hover near the top right of the clock and click the spanner

*Pick your time zone

*Repeat until you have all the clocks you want.

A: Windows 7 supports only two additional time zones. If you want to set up more than two additional time zones, then you will have to install some 3rd party software like this one.

A: I found this freeware app from Microsoft, Microsoft Time Zone, but it requires .NET framework 1.1.
I've got .NET 4 installed but it doesn't seem to work with that, so I'm not sure this is viable on Windows 7, unless someone can suggest a fix.

I found this from this page, but most of the other apps listed look either sketchy, bloated or out of date.

A: In windows 10, you can use the alarms and clock apps with the Alarms & Clock.

You can add up to 10 clocks.
You can right click these to pin them to your start menu too =)

A: While it's not a complete answer to your question you may find something of value hiding in the registry at:

HKEY_CURRENT_USER\Control Panel\TimeDate\AdditionalClocks

Adding a 3rd entry doesn't seem to provide anything useful but it may well be a step in the right direction.

A: The World Clock - Orange desktop gadget, which I think is something to do with Orange France, is another option.

Plus points:

*

*It looks quite nice

*It's readable

*It's configurable to show 24/12 hour time and analogue/digital.

Minus points:

*

*It'll only show the day/date on mouse-over.

*GMT / UTC doesn't seem to be in the list, the best option seems to be using a city which is always on GMT (eg Rabat, Morocco).

*You can't configure the labels it has to be a city name.

*It doesn't list the country (this is actually genuine issue for me since I have one friend in Santiago, Chile and one in Santiago de Compostela, Spain!)

*I'd prefer something that sits in the system tray rather than on the desktop.

So overall this is about the best bet, but I am really surprised no-one has written anything better!

A: If you want more than one clock in your taskbar, you could try http://www.1stclock.com/

A: I was also looking for an app that can show more than 3 time-zones in the taskbar / tooltip.
I found this nice app, which also happens to be free:
World Time System Stray


text:
Q: Dynamic programing parallelisation/vectorization with OpenMP Im trying to write a function that computes minimum cost polygon triangulation using dynamic programing and parallize/vectorize it using OpenMP. The code I wrote so far, returns correct results but it is too slow - for polygons that are formed by more than 3000 points it does not even stops after 5 minutes. Here is the code:
#pragma omp declare simd
float dist(float x1, float y1, float x2, float y2)
{
    return sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));
}

float triangulate(const vector<Point> &points) {

int n = points.size();

vector<vector<float>> table (n, vector<float>(n, 0));

int threads = omp_get_max_threads();

for (int gap = 0; gap < n; ++gap)
{
    for (int i = 0, j = gap; j < n; ++i, ++j)
    {
        if (j < i+2)
            table[i][j] = 0.0;
        else
        {
            int size = j - i - 1;

            Point p1 = points[i], p2 = points[j];
            //Precompute distance between i and j
            float ij = dist(p1.x, p1.y, p2.x, p2.y);

            float minimum = MAX;
            #pragma omp parallel for simd schedule(static, 64) num_threads(threads) reduction(min:minimum) if(size > 300)
            for (int k = i+1; k < j; ++k)
            {
                Point p3 = points[k];

                float perimeter = ij + dist(p1.x, p1.y, p3.x, p3.y) + dist(p2.x, p2.y, p3.x, p3.y) + table[i][k] + table[k][j];

                if(perimeter < minimum)
                {
                    minimum = perimeter;
                }
            }

            table[i][j] = minimum;
        }
    }
}

return table[0][n-1];
}

The gap and i,j for loops imho cannot be parallelized so only the for loop over k is possible to parallelize. I tried to play along with schedule arguments, but with no improvement. Am I missing something or just this function cannot be faster within this approach?

A: Why not parallelize on i/j?
For a given i/j pair, computing the perimeter only relies on values of table[i][k] and table[k][j] where the gap between i and k or between kand j is smaller than between i and j. As long as the outermost loop on gap is done in order, the inner loop on i/j has embarrassing parallelism properties and can be parallelized without any precaution.
// Do this here so that we can dispose of the if/then/else in the loop later
table[0][0] = 0.0;
for (int i= 1; i < n; ++i){
    table[i][i-1] = 0.0;
    table[i][i]   = 0.0;
}

// spawn parallel threads here
#pragma omp parallel default(shared)
for (int gap = 2; gap < n; ++gap)
{
    // Loop on i will now be distributed among threads
    // Not sure that is possible to place two variables in the loop definition
    // so loop on i and compute the corresponding value of j
    #pragma omp for
    for (int i = 0; i < n-gap; ++i)
    {
        int j=i+gap;
        int size = gap - 1;

        Point p1 = points[i], p2 = points[j];
        //Precompute distance between i and j
        float ij = dist(p1.x, p1.y, p2.x, p2.y);

        float minimum = MAX;

        // remove of all directives but simd
        #pragma omp simd reduction(min:minimum)
        for (int k = i+1; k < j; ++k)
        {
            Point p3 = points[k];

            float perimeter = ij + dist(p1.x, p1.y, p3.x, p3.y) + dist(p2.x, p2.y, p3.x, p3.y) + table[i][k] + table[k][j];

            if(perimeter < minimum)
                minimum = perimeter;
        }

        table[i][j] = minimum;
    } // implicit barrier, all threads will wait here for loop completion before moving to next value of gap
} //end of loop, end of parallel region


text:
Q: Laravel relationship: query with multiple Foreign keys I have the following db schema:
    //Pages schema
    Schema::create('pages', function( $table )
        {

            $table->increments('id');
            $table->softDeletes();
            $table->timestamps();
            $table->integer('parent_id');
            $table->integer('ordination');
            $table->unsignedInteger('title_id'); //Refer to strings
            $table->unsignedInteger('description_id'); //Refer to strings
            $table->unsignedInteger('url_id'); //Refer to strings

            //Foreign key
            $table->foreign('title_id')->references('id')->on('strings');
            $table->foreign('description_id')->references('id')->on('strings');
            $table->foreign('url_id')->references('id')->on('strings');

        });

    //Strings
    Schema::create('strings', function( $table )
            {

                $table->increments('id');
                $table->softDeletes();
                $table->timestamps();
                $table->text('en');
                $table->text('de');

            });

How I can retrieve a Page Object from the correspondent url string?
I would have a page object or array like the follow:
$page['url']['en'] = 'about'
$page['title']['en']= 'About title'
$page['description']['en']= 'About description'
etc..

I can retrieve the page Object from the related url executing the following eloquent query:
    $page= Pages::whereHas('url', function( $url )
    {
        $url->where('en', '=', 'About');

    })->first();

With this Eloquent model:
 class Pages extends Eloquent {

    protected $table = 'pages';

    public function url()

        {

            return $this->belongsTo('Strings');

        }
}

This will not retrieve the string values for title, description and url, but only their id.
How I can do that?

A: The relationship looks correct. The only thing you need to do is actually load the relation(s). The best way here is eager loading. It will reduce the db queries to a minimum:
$pages = Page::with('url')->get();

$page = Page::with('url')->find(1);

$page = Pages::with('url')->whereHas('url', function($url){
    $url->where('en', '=', 'About');
})->first();

To eager load all your string relations simply add them to the with() call:
$pages = Page::with('url', 'title', 'description')->get();


text:
Q: MySQL query to get last 12 months data grouped by month including zero counts I have table orders (order_id, order_processed_date). I want the count of orders per month for last 12 months. If any month has 0 orders, then it should print 0.
Something like this:
Total Orders | Month
-----------------------
2            | OCT 2018
3            | SEP 2018
0            | AUG 2018
0            | JUL 2018
1            | JUN 2018
0            | MAY 2018
0            | APR 2018
0            | MAR 2018
5            | FEB 2018
5            | JAN 2018
0            | DEC 2017
0            | NOV 2017

I already searched in this website and get some queries but did not find exact solution for this. I get result using below query but it does not have year:
SELECT
SUM(IF(month = 'Jan', total, 0)) AS 'Jan',
SUM(IF(month = 'Feb', total, 0)) AS 'Feb',
SUM(IF(month = 'Mar', total, 0)) AS 'Mar',
SUM(IF(month = 'Apr', total, 0)) AS 'Apr',
SUM(IF(month = 'May', total, 0)) AS 'May',
SUM(IF(month = 'Jun', total, 0)) AS 'Jun',
SUM(IF(month = 'Jul', total, 0)) AS 'Jul',
SUM(IF(month = 'Aug', total, 0)) AS 'Aug',
SUM(IF(month = 'Sep', total, 0)) AS 'Sep',
SUM(IF(month = 'Oct', total, 0)) AS 'Oct',
SUM(IF(month = 'Nov', total, 0)) AS 'Nov',
SUM(IF(month = 'Dec', total, 0)) AS 'Dec'
FROM (SELECT DATE_FORMAT(order_processed_date, '%b') AS month,
COUNT(order_id) as total
FROM orders
WHERE order_processed_date <= NOW() and order_processed_date >=
Date_add(Now(),interval - 12 month)
GROUP BY DATE_FORMAT(order_processed_date, '%m-%Y')) as sub

Can please someone help me to give me result as I required.

A: The following query builds a list of 1st day of month for previous 12 months. For example on Oct 19 2018 the list will contain dates from Oct 01 2018 to Nov 01 2017. Left join does the rest:
SELECT date, COUNT(orders.primary_key)
FROM (
    SELECT LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 1 MONTH AS date UNION ALL
    SELECT LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 2 MONTH UNION ALL
    SELECT LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 3 MONTH UNION ALL
    SELECT LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 4 MONTH UNION ALL
    SELECT LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 5 MONTH UNION ALL
    SELECT LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 6 MONTH UNION ALL
    SELECT LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 7 MONTH UNION ALL
    SELECT LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 8 MONTH UNION ALL
    SELECT LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 9 MONTH UNION ALL
    SELECT LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 10 MONTH UNION ALL
    SELECT LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 11 MONTH UNION ALL
    SELECT LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 12 MONTH
) AS dates
LEFT JOIN orders ON order_processed_date >= date AND order_processed_date < date + INTERVAL 1 MONTH
GROUP BY date


text:
Q: How can I solve this differential equation through Laplace transforms? Solve $y''-2y'+2y=0$ where $y(0)=0,~~y'(0)=1$. So I started solving this by doing the following
$$s^2Y(s)-sy(0)-y'(0)-2sY(s)-y(0)+2Y(s) = 0 \\
(s^2-2s+2)Y(s)-1=0 \implies Y(s) = \frac{1}{s^2-2s+2} = \frac{1}{(s-1)^2+1}$$
I am stuck on how to find the Laplace inversion given this transform. According to notes from class, the answer should be $y(t)=e^t\sin t$ but I don't see how to come to this. Any help would be greatly appreciated.

A: We have:
$$\mathcal{L}\{y''-2y'+2y=0\} = (s^2 y(s) - sy(0)-y'(0)) -2 (sy(s) - y(0)) +2 y(s) = 0$$
with: $y(0)=0,~~y'(0)=1$
Substitute for the IC's, solve for $y(s)$ and then find the inverse Laplace Transform.
We get:
$$y(s) = \dfrac{1}{s^2-2s+2}$$
Now, you just need to take $\mathcal{L^{-1}}\{y(s)\} = y(t)$.
We can write this as (complete the square):
$$y(s) = \dfrac{1}{s^2-2s+2} = \dfrac{b}{(s-a)^2 + b^2} = \dfrac{1}{(s-1)^2 + 1^2}$$
From the Table of Laplace Transforms, item $19.$,  we have:
$$\mathcal{L^{-1}} \left(\dfrac{1}{(s-1)^2 + 1^2}\right) = e^t \sin t$$


text:
Q: Calculate Account Receivables using LINQ How to calculate account receivable using LINQ.
I have tried this but stuck here.
I have done this in SQL but I want this in LINQ so I can use it in my MVC project.
var sale = saleslist.GroupBy(s => s.BuyerId).Select(s => s.Sum(u => u.Amount)).ToList();
var receipt = receiptslist.GroupBy(r => r.StakeHolderId).Select(t => t.Sum(u => u.Amount)).ToList();

List<AccountReceivablesVM> res = db.StakeHolders
    .Where(r=>r.StakeHolderTypeId == "0b85a69e-55f2-4142-a49d-98e22aa7ca10")
    .Select(rvm => new AccountReceivablesVM
    {
        CompanyName = rvm.CompanyName,
        Receivables = //don't know what to do here
    }).ToList();

Models:
public class StakeHolder
{
    public string StakeHolderId { get; set; }
    public string CompanyName { get; set; }
    public string Address { get; set; }
    public string Contact { get; set; }
    public string StakeHolderTypeId { get; set; }
}

public class Sale
{
    public string SaleId { get; set; }
    public string RefNo { get; set; }
    public DateTime Date { get; set; }
    public string BuyerId { get; set; }
    public string Description { get; set; }
    public Nullable<double> Amount { get; set; }
}

public class PaymentsAndReceipt
{
    public string PaymentAndReceiptId { get; set; }
    public Nullable<int> VoucherNo { get; set; }
    public DateTime Date { get; set; }
    public string StakeHolderId { get; set; }
    public string Description { get; set; }
    public Nullable<double> Amount { get; set; }
}

public class AccountReceivablesVM
{
    public string CompanyName { get; set; }
    public Nullable<double> Receivables { get; set; }
}

Expected Result:

A: You can join first with stakeholderId and then sum the amount and then group by with company name and stakeholder id, however I write the code in Linq. I have considered the stakeholderid as the primary key of your table just because you have not mentioned the schema of stakeholder so.
        var result = from s in db.StakeHolders
                    join pr in db.PaymentsAndReceipt on s.StakeHolderId equals pr.StakeHolderId
                    where StakeHolderTypeId == "0b85a69e-55f2-4142-a49d-98e22aa7ca10"
                    group s by new { s.StakeHolderId,s.CompanyName} into p
                    select new
                    {
                      StakeHolderId= p.Key.StakeHolderId,
                      CompanyName= p.Key.CompanyName,
                      Receivables = string.Format("{0:C}", p.Sum(y => y.Amount))
                   };


text:
Q: How to calculate median in Crate I am using Crate 0.54.7 and have the following table definition:
CREATE TABLE test (id int PRIMARY KEY, val int);

Now I want to get the median of val. The query I used in Postgresql so far did not work:
SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY val) FROM test;

Is there any way I can calculate the median in Crate?

A: This is not supported in Crate (as of 0.54.X).
But there are two feature requests on Github

*

*1 Percentile Aggregation?

*2 Quantiles Aggregation


text:
Q: Is my password storage technique strong enough This is a question about whether my security process is adequate for the kind of information i am storing.
I am building a website using ASP.NET 4.0 with a SQL backend and need to know how my security would hold up with regards to passwords and hashes etc.
I don't store any critical information on someone - No real names, addresses, credit card details or anything like that... just email and username.
For now, I am deliberately leaving out some specifics as I am not sure if telling you them will weaken my security but if not I can reveal slightly more.
Here is how I do it:

*

*The user registers with their email and a unique username up to 50 chars long

*They create a password (minimum 6 chars) using any characters on the keyboard (I HTMLEncode the input and am using parameterized stored procedures so I don't restrict the chars)

*I send them an email with a link to verify they are real.

*I use FormsAuthentication to set an auth cookie but I'm not using SSL at the moment... I understand the implications of sending auth details across plain http but I have asked my host to add the cert so it should be ready shortly.

It's the hashing bit I need to be sure of!
I create a random 100 character salt from the following char set (I just use the System.Random class, nothing cryptographic) - abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!£$%^*()_{}[]@~#<,>.?
This is then merged with the password and then hashed using SHA-512 (SHA512Managed class) tens of thousands of times (takes nearly 2 seconds on my i7 laptop to generate the final hash).
This final hash is then converted to a base64 string and compared with the already-hashed password in the database (the salt is stored in another column in the DB too)
A few questions (ignore the lack of SSL for the moment, I just haven't bought the certificate yet but it will be ready in a week or so):

*

*Does this strike you as secure enough? I understand there are degrees of security and that given enough time and resources anything is breakable but given that I don't store critical data, does it seem like enough?

*Would revealing the actual number of times I hash the password weaken my security?

*Does a 100 character salt make any difference over, say, a 20 character one?

*By revealing how I join a password and salt together, would that weaken my security?

A: So, let's try to answer your questions one by one:
Does this strike you as secure enough? I understand there are degrees of security and that given enough time and resources anything is breakable but given that I don't store critical data, does it seem like enough?
No. It is definitely not "secure enough".
Without seeing code, it's hard to say more. But the fact that you're doing a straight SHA512 instead of doing a HMAC indicates one problem. Not because you need to be using a HMAC, but because most algorithms that are designed for this purpose use HMAC under the hood (for several reasons).
And it seems likely you're doing hash = SHA512(hash) (just from your wording) which is proven to be bad.
So without seeing code, it's hard to say for sure, but it's not pointing in the right direction...
Would revealing the actual number of times I hash the password weaken my security?
No, it shouldn't. If it does, you have a problem somewhere else in the algorithm.
Does a 100 character salt make any difference over, say, a 20 character one?
Nope. All the salt does is make the hash unique (forcing the attacker to attack each password separately). All you need is a salt long enough to be statistically unique. Thanks to the Birthday Problem, 128 bits is more than enough for a 1/10^12 chance of collision. Which is plenty for us. So that means that 16 characters is the upper bound on salt effectiveness.
That doesn't mean it's bad to use a longer salt. It just means that making it longer than 16 characters doesn't significantly increase the security it provides...
By revealing how I join a password and salt together, would that weaken my security?
If it does, your algorithm is severely flawed. If it does, it amounts to Security Through Obscurity.
The Real Answer
The real answer here is to not re-invent the wheel. Algorithms like PBKDF2 and BCRYPT exist for exactly this purpose. So use them.
Further Information (Note that these talk about PHP, but the concepts are 100% applicable to ASP.NET and C#):

*

*YouTube Video - Password Storage and Hacking in PHP

*Blog Post - The Rainbow Table Is Dead

*Blog Post - Properly Salting Passwords

*PHP password_hash RFC

*Blog Post - Seven Ways To Screw Up BCrypt

A: *

*In theory, your hashing scheme sounds ok. In practice, it sounds like you have rolled your own crypto, which is bad. Use bcrypt, scrypt, or pbkdf2. All of these are designed by security professionals.

*Not really, but I don't think anyone needs to know that anyway.

*No. It just needs to be unique to every user. The purpose of salt is to prevent precalculation of hashes/rainbow table attacks.

*This doesn't apply once you make use of bcrypt (or scrypt or pbkdf2)

http://security.stackexchange.com has some topics on the subject, you should check them out.
Some extra notes - serious attackers will crack sha512 hashes way faster than your laptop. For example you could rent a server with a few Tesla GPU's from Amazon or similar, and start cracking at a few billion hashes/second rate. Scrypt makes some effort trying to prevent this by using memory intensive operations.
6 characters minimum for password is not enough, go with at least 8. A related image, I haven't verified the times but it gives a rough estimate and gives you the general idea (excluding dictionary attacks, which can target longer passwords):


text:
Q: Angular custom directive: a strange error occurs when set controller attribute to `function(scope){}` When I wrote a custom directive, a strange error blocks me.
angular.module('app.directives', [])
.directive('cyMenu', ['RecursionHelper', function(RecursionHelper) {
    function postLink(){};
    return {
        restrict: 'E',
        templateUrl: 'views/component/cy-menu.html',
        replace: true,
        transclude: false,
        require: '?^cyMenu',
        controller: function ($scope) { // when set this argument($scope) to scope, error occurs.
            this.getList = function() {
                return $scope.list;
            }
        },
        scope: {
            list: '=',
            isSubmenu: '@'
        },
        compile: function(tElement) {
            return RecursionHelper.compile(tElement, postLink);
        }
    }
}

As I pointed out(see comment), when I set controller attribute to controller: function (scope) {}, the error occurs:
Error: [$injector:unpr] Unknown provider: scopeProvider <- scope
http://errors.angularjs.org/1.3.6/$injector/unpr?p0=scopeProvider%20%3C-%20scope
...

I don't know why. Any help will be appreciated.

update
Here is angular's official demo, it looks similar to my directivehttps://code.angularjs.org/1.3.6/docs/guide/directive:
angular.module('docsTabsExample', [])
.directive('myTabs', function() {
  return {
    restrict: 'E',
    transclude: true,
    scope: {},
    controller: function($scope) {
      ...
    },
    templateUrl: 'my-tabs.html'
  };
})

A: A very good practice is to separate every component in a separate file, so I would start by putting your controller in a file like that :
//File recursionHelperController.js
(function() {
  'use strict';

  angular
    .module('app.controllers')
    .controller('RecursionHelperController', RecursionHelperController);

  RecursionHelperController.$inject = ['$scope'];

  function RecursionHelperController($scope) {
     //do your stuff
  }

})();

Note that I gave you the most correct format I know for a controller or any angular element in general, but you can do something simpler like:
angular.module('app.controllers')
.controller('RecursionHelperController', ['$scope', function($scope) {
         //do your stuff
      }])

You can then call this controller in your main file :
controller: 'RecursionHelperController'

Hope it helps
Update :
Sometimes the automatic injection has some troubles that's why I recommend doing it this way with an explicit injection. The angular doc only shows the simplest way for clarity and tutorial purposes
Update 2
If you don't want to separate the controller, try using the injection safe notation
controller : ['$scope', function($scope) {
     //do your stuff
  }])


text:
Q: Large size dlls with a 'd' suffix I am trying to make stand alone applications for windows platform. I searched for the dlls which my application depended on, placed them with the exe and things worked fine.
Recently, in one of my app, I saw that the dependency being asked are a little different :

*

*Qt5Guid.dll instead of Qt5Gui.dll

*Qt5Declaratived.dll instead of Qt5Declarative.dll

and some more similar kinds..
Common thing is, all these new dependencies are the same old dependencies with a d appended to it. When I used the new ones with a 'd', my application worked fine. Problem is all these dlls with 'd' are almost 100Mb more in size than their normal counterparts.
eg:
Qt5Guid.dll  ~ 119 Mb
Qt5Gui.dll   ~ 4 Mb
This is making my package to large in size to give as an application.
Q1. What is the difference between the normal dlls and the counterparts with a d suffix. ?
Q2. Can I do something to make my application depend on the normal one explicitly and thus have smaller size of my application ?

A: Qt DLLs with d suffix are just debug versions. They are needed if an application build in debug mode with CONFIG+=debug make parameter.
To make an app use the release DLLs, which are significantly smaller, just rebuild your application in release mode.


text:
Q: Trying to calculate a value from a text-box and dropdown list in Qualtrics I am trying to add the values from a text-box (which keeps changing) and a drop-down list (respondents click an answer). For some reason, I am not able to capture the value from the text-box. I am not sure where I am going wrong! Can someone please help, thank you.
Qualtrics.SurveyEngine.addOnload(function()
{
var InputA = $("QR~QID88");
var dropB = $("QR~QID85");
var InputTotalC = $("QR~"+this.questionId);
InputTotalC.readOnly= true;

Event.observe(dropB,'change',function(e){
var dropIdB= dropB.value;
dropB.select("option").each(function(s){
if(s.value==dropIdB)
{
dropIdB=parseInt(s.text);
}
});
var InputA1 = InputA.value;
if(dropIdB>=0) InputTotalC.value=(InputA1+dropIdB)-1;
else InputTotalC.value="0";
});
});


text:
Q: why image with onclick property get clicked on pressing enter first time I have a logon page for an application which asks for user id and password and then use following code for submitting it after validation.
<input Type="image" ID="btnMsgOk" src='images\Button\Normal\Ok.gif' onclick="release();return true;" onkeydown="escapeKey();" onmousemove="buttonMouseOver('btnMsgOk')" onmouseout="buttonMouseOut('btnMsgOk')" />

Once the page is loaded and 1st time I press enter key this ok get clicked but if page is not relaoded and enter key is pressed again it is not getting clicked , there is no onkeypress event in this page.
In the same way I have different jsp pages which use images and add  onclick event to it to call different function even for submitting the form.
In this pages even though functionality is defined for onkeypress event which defines the function key to press the image responsible for submitting the form, but when the jsp page is loaded and first time enter key is pressed it doesn't fires the function which is defined by onkeypress event but it fires the function defined by the 1st image on page which has onclick functionality and second time it behaves in the way it should i.e firing the function defined by onkeypress event and hence clicking the right button.

A: Disable it explicitly by below code::
   function stopRKey(evt) {
      var evt = (evt) ? evt : ((event) ? event : null);
      var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
      if ((evt.keyCode == 13) && (node.type=="text"))  {return false;}
    }

    document.onkeypress = stopRKey;


text:
Q: What is the proper way to do logging to a CSV file? I want to log some information of every single request sent to a busy http server in a formatted form. Using the logging module would create some thing I don't want to:
[I 131104 15:31:29 Sys:34]

I thought of the CSV format, but I don't know how to customize it. Python has the csv module, but I read in the manual
import csv
with open('some.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(someiterable)

Since it would open and close a file each time, I am afraid this way would slow down the whole server performance. What could I do?

A: As sloth suggests, you can easily edit the delimiter of the log to a comma, thus producing a CSV file.
Working example:
import logging

# create logger
lgr = logging.getLogger('logger name')
lgr.setLevel(logging.DEBUG) # log all escalated at and above DEBUG
# add a file handler
fh = logging.FileHandler('path_of_your_log.csv')
fh.setLevel(logging.DEBUG) # ensure all messages are logged to file

# create a formatter and set the formatter for the handler.
frmt = logging.Formatter('%(asctime)s,%(name)s,%(levelname)s,%(message)s')
fh.setFormatter(frmt)

# add the Handler to the logger
lgr.addHandler(fh)

# You can now start issuing logging statements in your code
lgr.debug('a debug message')
lgr.info('an info message')
lgr.warn('A Checkout this warning.')
lgr.error('An error writen here.')
lgr.critical('Something very critical happened.')

A: I would agree that you should use the logging module, but you can't really do it properly with just a format string like some of the other answers show, as they do not address the situation where you log a message that contains a comma.
If you need a solution that will properly escape any special characters in the message (or other fields, I suppose), you would have to write a custom formatter and set it.
logger = logging.getLogger()

formatter = MyCsvFormatter()

handler = logging.FileHandler(filename, "w")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(level)

You'll obviously have to implement the MyCsvFormatter class, which should inherit from logging.Formatter and override the format() method
class MyCsvFormatter(logging.Formatter):
    def __init__(self):
        fmt = "%(levelname)s,%(message)s" # Set a format that uses commas, like the other answers
        super(MyCsvFormatter, self).__init__(fmt=fmt)

    def format(self, record):
        msg = record.getMessage()
        # convert msg to a csv compatible string using your method of choice
        record.msg = msg
        return super(MyCsvFormatter, self).format(self, record)

Note: I've done something like this before, but haven't tested this particular code sample
As far as doing the actual escaping of the message, here's one possible approach:
Python - write data into csv format as string (not file)

A: Just use python's logging module.
You can adjust the output the way you want; take a look at Changing the format of displayed messages:

To change the format which is used to display messages, you need to specify the format you want to use:
import logging
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
logging.debug('This message should appear on the console')
logging.info('So should this')
logging.warning('And this, too')

and Formatters:

Formatter objects configure the final order, structure, and contents of the log message.

You'll find a list of the attribtus you can use here: LogRecord attributes.

If you want to produce a valid csv-file, use python's csv module, too.
Here's a simple example:
import logging
import csv
import io

class CsvFormatter(logging.Formatter):
    def __init__(self):
        super().__init__()
        self.output = io.StringIO()
        self.writer = csv.writer(self.output, quoting=csv.QUOTE_ALL)

    def format(self, record):
        self.writer.writerow([record.levelname, record.msg])
        data = self.output.getvalue()
        self.output.truncate(0)
        self.output.seek(0)
        return data.strip()

logging.basicConfig(level=logging.DEBUG)

logger = logging.getLogger(__name__)
logging.root.handlers[0].setFormatter(CsvFormatter())

logger.debug('This message should appear on the console')
logger.info('So should "this", and it\'s using quoting...')
logger.warning('And this, too')

Output:

"DEBUG","This message should appear on the console"
  "INFO","So should ""this"", and it's using quoting..."
  "WARNING","And this, too"

A: I don't think that is the best idea, but it is doable, and quite simple.
Manually buffer your log. Store log entries in some place, and write them to file from time to time.
If you know that your server will be constantly busy, flush your buffer when it reaches some size. If there may be big gaps in usage, I'd say that new thread (or better process, check yourself why threads suck and slow down apps) with endless (theoretically of course) loop of sleep/flush would be better call.
Also, remember to create some kind of hook that will flush buffer when server is interrupted or fails (maybe signals? or just try/except on main function - there are even more ways to do it), so you don't lose unflushed buffer data on unexpected exit.
I repeat - this is not the best idea, it's the first thing that came to my mind. You may want to consult logging implementations from Flask or some other webapp framework (AFAIR Flask has CSV logging too).


text:
Q: Looking for an Elko County Nevada Land Ownership Shapefile I am looking for a Nevada Land Ownership shapefile.
County and state GIS don't seem to have anything beyond pdf.
Are there any public or commercial avenues to acquire land ownership in Nevada?
I'm really just needing public vs. private info.

A: Usually the BLM has a good public ownership layer since they manage the most public lands. You can try the BLM Navigator site--specifically BLM NV Surface Management Agency (SMA) Polygons
.

Description: The SMA dataset was created to display the management
  status of the land through the BLM Administrative State of Nevada. In
  2010 it was updated to be coincident with GCDB lines from Premier
  data. The ownership for each smallest division was identified by the
  previous land status layer. In areas of confusion or pieces that were
  divided in areas smaller then GCDB, the MTP was referenced as the
  final authoritative source. This project was completed 8/10/10, and is
  updated as necessary. Updates have not occurred to bring the dataset
  into alignment with the most current CadNSDI PLSS data and there are
  known alignment errors.


text:
Q: Chrome shows 'data;.' in address bar while using selenium to login I'm using selenium to test login page like this:
from selenium import webdriver
import time

browser = webdriver.Chrome()

def execute():
    browser.get("https://test.com")
    browser.find_element_by_id("user_name").send_keys("user_name")
    browser.find_element_by_id("password").send_keys("password")
    time.sleep(1)
    browser.find_element_by_id("submit_button").click()

with Google Chrome version 79.0.3945.117, chromedriver version 79.0.3945.36, selenium version 3.141.0 and MacOS High Sierra version 10.13.6.
But when I run the program, chrome open a blank page with data:, in address bar.
What went wrong?
Thankyou!


text:
Q: Can I silence boost's configure script? When I'm installing boost (running .configure) it lists every file that is copied in the install process. Is there any way to silence this?

A: By silence, do you mean just prevent output to the screen? You could do .configure > /dev/null in Linux/OS X or .configure > nul in Windows.


text:
Q: Dismissing UIPopover I have a popover displayed from a barButton, I just want that when I tap a button in the popover the popover is dismissed.
I tried a this way and adding a public method in the viewController that creates the popover to dismiss it, but nothing happens.
Any idea?
Thank you in advance.

A: You can Using dismissPopoverAnimated Method of PopoverController you can dismiss popover.
try this,
 - (IBAction) buttonClick:(id)sender
{
    [popover dismissPopoverAnimated:YES];

}


text:
Q: What type of variable is this in php: {{%= description %}} I'm modifying a wordpress plugin (Page Builder by SiteOrigin 2.0.7) and there are some variables throughout one of the php files (tpl/js-templates.php) in a notation that I don't recognize. The variables look like this: {{%= foo %}} and they always appear in the midst of html.
Here is an example of some of the html:

    {{%= buttons %}}

    {{%= content %}}

What is this? Is this blade template notation?
How can I use this variable in a conditional? For instance, I'd like to test if {{%= url %}} is a jpg url.

A: This is a bit new to me, so I may be wrong here, but lets follow the code backwards through the plugin..
{{% appears in tpl\js-templates.php 36 times and js\siteorigin-panels.js (and the .min version) once. %}} appears only 34 times in the same php file, still once in the js file.
In the .js file they appear at line 14+, here:
String.prototype.panelsProcessTemplate = function(){
    var s = this;
    s = s.replace(/{{%/g, '<%');
    s = s.replace(/%}}/g, '%>');
    s = s.trim();
    return s;
};

So they're using {{% as a placeholder and using JS to replace it with <%. The same is happening with the closing %}} (now %>).
It also shows up as a sort of shorthand for

text/template is a browser-ignored template client-side code can use. So it's replacing {{% with <% and %}} with %> in this template, running it through the template() function, and setting it all to the template variable in this view.
What is template() doing? It's not defined in this file, but it is in the Underscore.js documentation under the template section. Apparently it's actually the whole _.template(), not just template(). Here's the overview:

Compiles JavaScript templates into functions that can be evaluated for rendering. Useful for rendering complicated bits of HTML from JSON data sources. Template functions can both interpolate values, using <%= … %>, as well as execute arbitrary JavaScript code, with <% … %>. [...]

So, we know right now that Underscore.js is using <% and %> as their data identifiers in templates, both for variables and arbitrary JavaScript as we saw above.
We know what {{% .. %}} is
{{%= description %}} in this case is more-or-less saying . It's outputting the description parameter into the template HTML.
If I were a betting man, I'd bet you can change the widget title and description through the WordPress/ Page Builder Admin.
As for checking what the variable is, you'll likely be best suited checking after everything is rendered on the page.
$( document ).ready(function() {
   if ($("#id .so-content img").prop("src").endsWith(".jpg")) {
     ...

endsWith being a custom String prototype defined here.

A: As it seems, these expressions are part of the Liquid programming language. Please see the attached link for a full description.


text:
Q: How to turn a constraint list in pyomo into a dataframe? I am developing a production model and a very long list of constraints (ca. 600). How can I export the list to an excel file for analysis?
so far i am using model.cons.pprint() to generate a visualisation of the constraints at runtime. However its very cumbersome to review 100s of lines in a terminal window.
This is the current solution that produces an output in the terminal window at runtime.
# define constraints
model.cons = pyomo.ConstraintList()
#
# ....
#
model.cons.pprint()
#

this produces
Size=577, Index=cons_index, Active=True,  Key : Lower  : Body                                                                                : Upper    : Active
and then 577 lines of constraints. which is fine to get started.
i have tried the following to generate a dataframe,
df_cons = pd.DataFrame.from_dict(model.cons.extract_values(), orient='index', columns=[str(model.cons)])
print(df_cons)
print("--------------")

However this did not work.
I am looking for a command to export the constraint list to a dataframe or write directly to an excel file.


text:
Q: VirtualBox guest additions crashes and fails to fully install on Ubuntu 20.04 guest My virtualbox 6.1.4 vm with Ubuntu 20.04 guest on Windows 10 Pro fails to install:
Verifying archive integrity... All good.
Uncompressing VirtualBox 6.1.4 Guest Additions for Linux........
VirtualBox Guest Additions installer
Removing installed version 6.1.4 of VirtualBox Guest Additions...
Copying additional installer modules ...
Installing additional modules ...
VirtualBox Guest Additions: Starting.
VirtualBox Guest Additions: Building the VirtualBox Guest Additions kernel
modules.  This may take a while.
VirtualBox Guest Additions: To build modules for other installed kernels, run
VirtualBox Guest Additions:   /sbin/rcvboxadd quicksetup <version>
VirtualBox Guest Additions: or
VirtualBox Guest Additions:   /sbin/rcvboxadd quicksetup all
VirtualBox Guest Additions: Building the modules for kernel 5.8.0-38-generic.

VirtualBox Guest Additions: Look at /var/log/vboxadd-setup.log to find out what
went wrong
VirtualBox Guest Additions: Running kernel modules will not be replaced until
the system is restarted

When I look at that log file, it shows this:
Building the main Guest Additions 6.1.4 module for kernel 5.8.0-38-generic.
Error building the module.  Build output follows.
make V=1 CONFIG_MODULE_SIG= CONFIG_MODULE_SIG_ALL= -C /lib/modules/5.8.0-38-gene
ric/build M=/tmp/vbox.0 SRCROOT=/tmp/vbox.0 -j4 modules
make[1]: warning: -j4 forced in submake: resetting jobserver mode.
test -e include/generated/autoconf.h -a -e include/config/auto.conf || (
    \
echo >&2;                           \
echo >&2 "  ERROR: Kernel configuration is invalid.";       \
echo >&2 "         include/generated/autoconf.h or include/config/auto.conf are
missing.";\
echo >&2 "         Run 'make oldconfig && make prepare' on kernel src to fix it.
";  \
echo >&2 ;
...

I checked for include/generated/autoconf.h or include/config/auto.conf, both exist from /usr/src/linux-headers-5.8.0-38-generic, so I think this top part of log runs fine.
After the above output there are a few gcc commands that complete and then one that fails, causing guest additions to abort:
...
gcc -Wp,-MMD,/tmp/vbox.0/.combined-agnostic.o.d  ... -c
 -o /tmp/vbox.0/combined-agnostic.o /tmp/vbox.0/combined-agnostic.c
In file included from /tmp/vbox.0/VBoxGuestR0LibHGCMInternal.c:44,
                 from /tmp/vbox.0/combined-agnostic.c:34:
/tmp/vbox.0/include/iprt/time.h: In function 'RTTimeSpecGetTimeval':
/tmp/vbox.0/include/iprt/time.h:379:13: error: dereferencing pointer to incomple
te type 'struct timeval'
  379 |     pTimeval->tv_sec = (time_t)i64;
      |             ^~
/tmp/vbox.0/include/iprt/time.h:379:25: error: 'time_t' undeclared (first use in
 this function); did you mean 'ktime_t'?
  379 |     pTimeval->tv_sec = (time_t)i64;
      |                         ^~~~~~
      |                         ktime_t
/tmp/vbox.0/include/iprt/time.h:379:25: note: each undeclared identifier is repo
rted only once for each function it appears in
/tmp/vbox.0/include/iprt/time.h:379:32: error: expected ';' before 'i64'
  379 |     pTimeval->tv_sec = (time_t)i64;
      |                                ^~~
      |                                ;
/tmp/vbox.0/include/iprt/time.h: In function 'RTTimeSpecSetTimeval':
/tmp/vbox.0/include/iprt/time.h:393:67: error: dereferencing pointer to incomple
te type 'const struct timeval'
  393 |     return RTTimeSpecAddMicro(RTTimeSpecSetSeconds(pTime, pTimeval->tv_s
ec), pTimeval->tv_usec);
      |                                                                   ^~
make[2]: *** [scripts/Makefile.build:290: /tmp/vbox.0/combined-agnostic.o] Error
 1
make[2]: *** Waiting for unfinished jobs....
make[1]: *** [Makefile:1780: /tmp/vbox.0] Error 2
make: *** [/tmp/vbox.0/Makefile-footer.gmk:114: vboxguest] Error 2

I'm guessing this is a gcc version issue or headers issue but there are no further upgrades available. I just found a comment on Problem installing virtualBox Guest Additions suggesting known issues so I will first try upgrading. I will post answer if this works, stay tuned.

A: So it works now, here is what I did:

*

*In guest vm running in virtualbox 6.1.4, ran sudo apt upgrade which showed upgrades for gcc and linux headers etc

*Re-ran the guest additions installer, same crash problem; I tried restarting the guest and re-installing, a couple of times to be sure; upon logging in, I would also get the message that guest addition crashed

*Upgraded virtualbox to 6.1.18

*Re-ran the guest additions install, it succeeded, but clipboard sharing still did not work. Output:
  Verifying archive integrity... All good.
  Uncompressing VirtualBox 6.1.18 Guest Additions for Linux........
  VirtualBox Guest Additions installer
  Removing installed version 6.1.18 of VirtualBox Guest Additions...
  update-initramfs: Generating /boot/initrd.img-5.8.0-40-generic
  Copying additional installer modules ...
  Installing additional modules ...
  VirtualBox Guest Additions: Starting.
  VirtualBox Guest Additions: Building the VirtualBox Guest Additions kernel
  modules.  This may take a while.
  VirtualBox Guest Additions: To build modules for other installed kernels, run
  VirtualBox Guest Additions:   /sbin/rcvboxadd quicksetup <version>
  VirtualBox Guest Additions: or
  VirtualBox Guest Additions:   /sbin/rcvboxadd quicksetup all
  VirtualBox Guest Additions: Building the modules for kernel 5.8.0-40-generic.
  update-initramfs: Generating /boot/initrd.img-5.8.0-40-generic
  VirtualBox Guest Additions: Running kernel modules will not be replaced until
  the system is restarted
  Press Return to close this window...

*Restarted vm: no crash on login, and sharing clipboard with host works
It's weird because i have several other vm that have Ubuntu 18 and 6.1.4 guest additions was just fine.


text:
Q: What do I actually need in a C++ project? I have been programming a lot in college and have a basic understanding on how to program. All the time the programming environment was configured and all necessary files were provided. Even the source files were pre-filled, where I had to only add essential lines of code. Thus, I learned the programming language and how to code, but I have no idea what is necessary besides the code to make a working application.
Now, when I want to make my own application, what is necessary to have except the functional programming code? What files are created automatically for me (such as in MS Visual Studio 2008 C++), what other files/libraries should be included by me? What are the essential project settings i should pay attention to? etc.
Most of the tutorials I found cover programming essentials and rarely mention the questions above. If someone could name the topics that cover these questions, I would greatly appreciate. The links to educational sources would be welcome.


text:
Q: (InvalidChangeBatch) when calling the ChangeResourceRecordSets operation - using boto3 to update resource record I am trying to update a number of CNAME records to A hosted on Route53 using boto3, here is my function:
def change_resource_record(domain, zone_id, hosted_zone_id, balancer_id):
    print(domain, zone_id, hosted_zone_id, balancer_id)
    client.change_resource_record_sets(
        HostedZoneId=zone_id,
        ChangeBatch={
            "Comment": "Automatic DNS update",
            "Changes": [
                {
                    "Action": "UPSERT",
                    "ResourceRecordSet": {
                        "Name": domain,
                        "Type": "A",
                        "AliasTarget": {
                            "HostedZoneId": hosted_zone_id,
                            "DNSName": balancer_id,
                            "EvaluateTargetHealth": False
                        }
                    }
                },
            ]
        }
    )

I get this error:
Traceback (most recent call last):
  File "load_balancer.py", line 138, in <module>
    get_balancer(domain)
  File "load_balancer.py", line 135, in get_balancer
    change_resource_record(domain, zone_id, hosted_zone_id, balancer_id)
  File "load_balancer.py", line 116, in change_resource_record
    "EvaluateTargetHealth": False
  File "C:\Python36\lib\site-packages\botocore\client.py", line 312, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "C:\Python36\lib\site-packages\botocore\client.py", line 601, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.errorfactory.InvalidChangeBatch: An error occurred (InvalidChangeBatch) when calling the ChangeResourceRecordSets operation: RRSet of type A with DNS name suffix.domain.tld. is not permitted because a conflicting RRSet of type  CNAME with the same DNS name already exists in zone domain.tld.

What is the correct way to update the record, should I delete the entry and then re-create it?
Any advice is much appreciated.

A: I had a missing closing period in the domain, so changing to this solved my issue:
            "ResourceRecordSet": {
                "Name": domain + '.',
                "Type": "A",
                "AliasTarget": {
                    "HostedZoneId": hosted_zone_id,
                    "DNSName": balancer_id,
                    "EvaluateTargetHealth": False
                }
            }


text:
Q: Can I improve linear model coefficient estimates using group information without working it into model? I am fitting a linear model in order to predict future observations. The training data consists of about 1000 observations. Each observation comes from one of 10 individuals, which means I have about 100 observations per individual. The future data to which the model will be applied will come from different individuals than those in the training set. The individuals are expected to vary systematically (they could have different slopes, intercepts, etc).
I have an understanding of how one would usually account for this individual-level variation in a linear model. Dummy variables, interaction terms, partial pooling, etc. However, these options only work for prediction if I have the same individuals in the prediction data as I do in the training data. This is not the case in my situation; the individuals at prediction time are not the same individuals at training time, so the model cannot contain any terms which represent the individual.
My question: if my sole concern is in getting the best coefficient estimates possible, is there anything more I can do beyond fitting the linear model as usual with no accounting for the individuals?
I came across some info about clustered standard errors, but the entire purpose of that seems to be in correcting for underestimation of error-term variance. It doesn't seem like introducing clustered standard errors will at all impact the coefficient estimates themselves (what I really care about), though please correct me if I'm wrong.
Some relevant points:

*

*Thankfully, there is strong reason to believe that the individuals in the training set are a representative sample of individuals that will be seen in the wild.

*I have no information that could account for individual-level variation. In the training data, I only have indicators for individuals. There is no way to model the individuals' slopes/intercepts as depending on some underlying property of the individuals.

Visual explanation:
library(ggplot2)

set.seed(123)
n_individuals <- 5
obs_per_individual <- 100

df_params <- data.frame(individual = factor(1:n_individuals),
                        slope = rnorm(n = n_individuals, mean = 1, sd = 0.2),
                        intercept = rnorm(n = n_individuals, mean = 0, sd = 0.2))

df_list <- list()
for (i in 1:n_individuals) {
  df_iter <- data.frame(individual = rep(df_params$individual[i], obs_per_individual),
                    x = runif(n = obs_per_individual))
  df_iter$y <- df_params$intercept[i] + df_iter$x * df_params$slope[i] + rnorm(n = obs_per_individual, mean = 0, sd = 0.1)
  df_list[[i]] <- df_iter
}
df <- bind_rows(df_list)

ggplot(df, aes(x = x, y = y)) +
  geom_point(aes(color = individual), size = 0.5) +
  geom_smooth(aes(color = individual), method = "lm", fullrange = TRUE, se = FALSE, size = 0.5) +
  geom_smooth(mapping = aes(x = x, y = y), method = "lm", fullrange = TRUE, se = FALSE, linetype = "dashed") +
  scale_color_discrete(guide = NULL)

The dashed line is the overall regression line. Colors represent individuals. Is there any way to improve upon the regression in a way that does not rely on knowing the individuals in advance at prediction time?

A: When estimating a mixed effects model we have to distinguish between marginal (sometimes called "unconditional") and conditional estimates. Conditioning refers to whether these estimates are subject-specific or not. In a way, all models other than conditional GLMMs produce some variation of a marginal estimators. Please note that while I mention "subjects" here, this extends to an arbitrary level on nesting.
The practical implications of this distinction is that when we are making estimates about new "unseen" individuals, e.g. subjects $s_{n+1}$ and $s_{n+2}$, we can only predict their marginal estimates. That is because we assume that any difference between them and our training sample will be due to random variation which is by definition "0" in expectation. (For example in a single-level mixed effects model with $y_{i,j} = X_{ij}\beta + Z_{ij}u_i + \epsilon_{ij}$, our working assumption for the random effect $u_i$ is that $u_i \sim N(0,\sigma^2 D)$.) As such having conditional estimates for $s_{n+1}$ and $s_{n+2}$ is inapplicable; if we assume there are any systemic differences between these new subjects and our training sample, those differences will be realised in the fixed effects ("explanatory variables") rather than the random effects ("nuisance parameters") of our model.
Two relatively mature reference on the matter are: A Comparison of Cluster-Specific and Population-Averaged Approaches for Analyzing Correlated Binary Data (1991) by Neuhaus et al. and Marginalized multilevel models and likelihood inference (2000) by Heagerty and Zeger; CV.SE has a related thread on Difference between marginal and conditional treatment effect? Relating to regression vs. propensity score methods that will be handy to check too.  West et al.'s "Linear Mixed Models: A Practical Guide Using Statistical Software" (see Sect. 2.3.2 on the "The Marginal Model Implied by an LMM" particularly) is also a good and easy-to-follow resource on the matter.


text:
Q: AX 2009 / 2012 CS database collation I've found several articles, posts and threads that case sensitive database collation isn't supported. Neither by 2009 nor by 2012. In Installation-progress, you'll be faced with this, latest. But I wasn't able to find a concrete reason for that behaviour.
So - what's the reason, CS collation isn't allowed?

A: String comparisons are case insensitive in X++. Using a case sensitive database on a case insensitive programming environment would be strange indeed.
Example: transactions may be created with currencies "usd" or "USD". Different currencies?


text:
Q: Issue with case_when statement using & in dplyr? I am attempting to create an additional column in my dataset that bucketizes percentiles. Ideally I would to create logic as follows:
CASE
  WHEN  percentile >=  75 AND  percentile < 90  THEN "75%-89% Percentile"
  WHEN percentile >=  50 AND  percentile < 75  THEN "50%-75% Percentile"

END

What I have attempted dplyr is the following:
  mutate(Bucket = case_when(as.double(percentile) >= 90 ~ "90%-100% Percentile",
                            as.double(percentile) >=  75 & as.double(percentile) < 90  ~ "75%-89% Percentile",
                            as.double(percentile) <  75 & as.double(percentile) >= 50  ~ "50%-75% Percentile",
                            as.double(percentile) <  50 & as.double(percentile) >= 25  ~ "25%-50% Percentile",
                            as.double(percentile) <  25 & as.double(percentile) >= 0  ~ "0%-25% Percentile"))

However it is not bucketizing correctly, see a sample of the results in the screenshot. The bucket flag for these percentiles should be "75%-89% Percentile" :

A: The column percentile is factor.  We need to convert to character class first and then to numeric
library(dplyr)
 df1 %>%
     mutate(percentile = as.numeric(as.character(percentile))) %>%
     ...

What happens is that when we directly coerce to numeric/integer, it gets coerced to integer storage values instead of the actual values
v1 <- factor(c(81.9, 82.7, 81.9, 82.5))
as.numeric(v1)
#[1] 1 3 1 2

is different than the following
as.numeric(as.character(v1))
#[1] 81.9 82.7 81.9 82.5

Or probably faster with levels
as.numeric(levels(v1)[v1])
#[1] 81.9 82.7 81.9 82.5


text:
Q: Django Template Data I have the following models:
class Contactnumber(TimeStampedModel):
    phone_number = models.CharField(max_length=100, unique=True)
    contact = models.ForeignKey('contacts.Contact')

class Contact(TimeStampedModel):
        contact = models.CharField(max_length=100, db_index=True,
                               verbose_name='Contact Name')
        practice = models.ManyToManyField('practice.Practice',
                                      related_name="contacts",)

class Practice(TimeStampedModel):
       practice = models.CharField(max_length=150, db_index=True,
                                verbose_name='Practice Name')

I have a template including data tables in which I want to show the following:
Practice, Contact, Contact Phone
The following gives me the contact for the practice:
{% for contact in practice.contacts.all %}
    {{ contact }}
    {% endfor %}

My question is how do  include the contact phone number as I seem a bit lost.
Any help would be appreciated. Apologies if this is a simple question!

A: ATM your contacts can have multiple phone numbers, so one way would be to do it like this:
{% for contact in practice.contacts.all %}
    {% for number in contact.contactnumber_set.all %}
        {{ number.phone_number }}
    {% endfor %}
{% endfor %}

The logic behing this is that when you haven't set a related_name to a relation field (one2one, FK, M2M), then you can access the related model by the model's name and adding "_set" to the end. So you iterate over all contacts and over all numbers that a contact has and the output will be all the numbers for those guys. Feel free to format it any way you like (adding commas, <br>'s and so on).


text:
Q: Delphi and NoSQL Have anyone ever used Delphi with NoSQL databases like Mongo, CouchDB or others? Which one would you recommend?

A: There is a new full featured driver for MongoDB "mongo-delphi-driver" which can be found (with examples) here:  https://github.com/gerald-lindsly/mongo-delphi-driver.

A: For Mongo, theres TMongoWire and pebongo (early stages). For couchDB, I believe one would interact mainly through HTTP/JSON
For Cassandra, I believe the best bet would be to somehow incorporate a supported language inside your Delphi app and use that to interact with Cassandra, or else implement a web service in a supported language and make it accessible to your Delphi application.
Hope it helps.

A: Delphi has few native NoSQL database solutions right-out-of-the-box:

*

*BDE & Paradox & dBase through the TDatabase & TTable API;

*TClientDataSet.

Not that I suggest them, but you have not listed your requirements.