text:
Q: animated popup view similar to one in Ipad music folder I would like to know what is the name of the functionality that is used in the Ipad's Music folder, where when an album folder is clicked, details regarding that album pops up in an animated view.
I tried using presentModelViewController but its functionality is different.
It would be great if someone could help me out.

A: On the iPad you have several different options with regards to animating a modal view controller, you can find them here: UIModalTransitionStyle.
However, if you are referring to the "zoom and flip" sort of effect on the album I'm pretty sure this is private behaviour so you would need to develop this yourself.... you might be able to accomplish this with Core Graphics/Quartz.

A: I just managed to get sth. like this to work using CoreAnimation / QuartzCore Framework...
be sure to
#import <QuartzCore/QuartzCore.h>

when you want to animate, use CATransform3Dand the poorly documented CATransform3D.m34 property. this will do the first half of the animation (assuming 200x200<->450x450 with 180° rotation):
[UIView beginAnimations:nil context:NULL];

[UIView setAnimationDuration:0.5];
[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
[UIView setAnimationDelegate:self];
CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
rotationAndPerspectiveTransform.m34 = 1.0 / -1000; // this turns on perspective!
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 90.0f * M_PI / 180.0f, 0.0f, 1.0f, 0.0f);
someView.layer.transform = rotationAndPerspectiveTransform;
someView.bounds = CGRectMake(0, 0, 325, 325);

[UIView commitAnimations];

for the second half of the animation, you have to add/remove your view to the hierarchy. this example shows hiding/showing of a view that already exists as a subview of someView, it also makes use of a BOOL isUp instance variable (the first half of the aniation is independent of the isUp-flag!)
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    if (flag) {
        if (isUp) {
            someSubView.hidden = YES; // hide subview
            [UIView beginAnimations:nil context:NULL];

            [UIView setAnimationDuration:0.5];
            [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
            CATransform3D rotationAndPerspectiveTransform = CATransform3DRotate(someView.layer.transform, -90.0f * M_PI / 180.0f, 0.0f, 1.0f, 0.0f);
            someView.layer.transform = rotationAndPerspectiveTransform;
            someView.bounds = CGRectMake(0, 0, 200, 200);

            [UIView commitAnimations];
            isUp = NO;
        } else {
            someSubView.hidden = NO; // Show subview
            [UIView beginAnimations:nil context:NULL];

            [UIView setAnimationDuration:0.5];
            [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
            CATransform3D rotationAndPerspectiveTransform = CATransform3DRotate(someView.layer.transform, 90.0f * M_PI / 180.0f, 0.0f, 1.0f, 0.0f);
            someView.layer.transform = rotationAndPerspectiveTransform;
            someView.bounds = CGRectMake(0, 0, 450, 450);

            [UIView commitAnimations];
            isUp = YES;
        }
    }
}

one last thing: everything in your view will appear mirrored, it might not be the ideal solution, but mirroring back by applying a CGAffineTransform to the subview does the trick:
- (void)viewDidLoad
{
    [super viewDidLoad];
    someSubView.transform = CGAffineTransformMakeScale(-1, 1);
    isUp = NO;
}

i'm alredy a month late with this solution but i hope it helped someone :)
i first tried using the animateWithDuration:animations:completion: block-based API but that turned out to lag heavily (no smooth first/second-half animaiton even without touching subviews).


text:
Q: MailParser, stop after headers have been parsed I am using MailParser to parse incoming mail. It's done in two steps:

*

*analyze (figuring out what to do with the email) and

*handing it in several different ways depending on analysis result.

For analyze step I do not need to have any of the bodies or attachments parsed, just headers.
MailParser has this handy event:
mailparser.on("headers", function(headers) {
    console.log(headers.received);
})

Is there any way to break execution here? There's no need for MailParser to spend any CPU cycles after this point in my use case.
Thanks

A: I'm looking at their source code right now and they did not implement a way to do so, have a look at their _process function.
Because it is asynchronous, when you receive the headers event, it might already be further down the processing flow of mailparser.
What you could do though is fork their code and add a hook that pauses the flow when the headers are parsed, and continues only if your hook allows it to, which should not be too hard.
If you manage to do it in a clean way and add some tests for it, you could also open a pullrequest to them as I'm sure it could be useful to some other people as well!
You could also manually parse the headers before passing the envelope to mailparser, as the headers are separated from the body by a \r\n\r\n it is easy to find and parse those.

redpajama_set_name: RedPajamaStackExchange


text:
Q: $f$ convex $\iff f(y)\geq f'(x)(y-x)+f(x).$ I want to prove that $f$ is convex $\iff f(y)\geq f'(x)(y-x)+f(x)$.
The implication is fine, but I have difficulties with the converse implication. I tried to prove that $f'$ is increasing, but still, it doesn't work : Let $y>x$, then $$\frac{f(y)-f(x)}{y-x}\geq f'(x),$$
but taking $x\to y$ we get $f'(y)\geq \lim_{x\to y}f'(x).$ So if $f$ is $\mathcal C^1$ we don't get better than $f'(y)\geq f'(y)$... any idea ?

A: Graphically, this means that the tangent at any point of a convex function lies below the graph.
Convexity implies $ f(y)\geq f'(x)(y-x)+f(x)$

Now, take $0 < \theta < 1$, we know that for $x,y \in \operatorname{dom}(f)$, we also have that $x + \theta(y-x) \in  \operatorname{dom}(f)$. Using the definition of convexity, we can say
  $$f(x + \theta(y-x)) \leq (1-\theta)f(x) + \theta f(y)$$
  which implies
  $$f(y) \geq f(x) + \frac{f(x + \theta(y-x)) -f(x)}{\theta}$$
  Taking $\theta \rightarrow 0$, we get the desired result. Now, to show the other way around,

$ f(y)\geq f'(x)(y-x)+f(x)$ implies convexity

Choose any $x \neq y$, and $0 < \theta < 1$, let $z = \theta x + (1-\theta) y$. Applying the equation twice we have
  $$ f(x)\geq f'(z)(x-z)+f(z) \tag{1}$$
  and
  $$ f(y)\geq f'(z)(y-z)+f(z) \tag{2}$$
  Now, multiplying $(1)$ by $\theta$ and $(2)$ by $1 - \theta$, we get
  $\theta f(x) + (1-\theta)f(y) \geq f(z)$
  which means we have convexity.

A: Choose any $x\ne y$, and $0\le\theta\le1$, and let $z=\theta x+(1-\theta)y$. Applying the inequality  twice yields
$$
 f(x)\ge f(z)+f'(z)(x-z)
 \quad\text{and}\quad
 f(y)\ge f(z)+f'(z)(y-z).
$$
Multiplying the first inequality by $\theta$, the second by $1-\theta$, and adding them yields
$$
 f(z)\le\theta f(x)+(1-\theta)f(y),
$$
which proves that $f$ is convex.


text:
Q: plot a circle with pyplot surprisingly I didn't find a straight-forward description on how to draw a circle with matplotlib.pyplot (please no pylab) taking as input center (x,y) and radius r. I tried some variants of this:
import matplotlib.pyplot as plt
circle=plt.Circle((0,0),2)
# here must be something like circle.plot() or not?
plt.show()

... but still didn't get it working.

A: If you want to plot a set of circles, you might want to see this post or this gist(a bit newer). The post offered a function named circles.
The function circles works like scatter, but the sizes of plotted circles are in data unit.
Here's an example:
from pylab import *
figure(figsize=(8,8))
ax=subplot(aspect='equal')

#plot one circle (the biggest one on bottom-right)
circles(1, 0, 0.5, 'r', alpha=0.2, lw=5, edgecolor='b', transform=ax.transAxes)

#plot a set of circles (circles in diagonal)
a=arange(11)
out = circles(a, a, a*0.2, c=a, alpha=0.5, edgecolor='none')
colorbar(out)

xlim(0,10)
ylim(0,10)

A: You need to add it to an axes. A Circle is a subclass of an Patch, and an axes has an add_patch method. (You can also use add_artist but it's not recommended.)
Here's an example of doing this:
import matplotlib.pyplot as plt

circle1 = plt.Circle((0, 0), 0.2, color='r')
circle2 = plt.Circle((0.5, 0.5), 0.2, color='blue')
circle3 = plt.Circle((1, 1), 0.2, color='g', clip_on=False)

fig, ax = plt.subplots() # note we must use plt.subplots, not plt.subplot
# (or if you have an existing figure)
# fig = plt.gcf()
# ax = fig.gca()

ax.add_patch(circle1)
ax.add_patch(circle2)
ax.add_patch(circle3)

fig.savefig('plotcircles.png')

This results in the following figure:

The first circle is at the origin, but by default clip_on is True, so the circle is clipped when ever it extends beyond the axes. The third (green) circle shows what happens when you don't clip the Artist. It extends beyond the axes (but not beyond the figure, ie the figure size is not automatically adjusted to plot all of your artists).
The units for x, y and radius correspond to data units by default. In this case, I didn't plot anything on my axes (fig.gca() returns the current axes), and since the limits have never been set, they defaults to an x and y range from 0 to 1.
Here's a continuation of the example, showing how units matter:
circle1 = plt.Circle((0, 0), 2, color='r')
# now make a circle with no fill, which is good for hi-lighting key results
circle2 = plt.Circle((5, 5), 0.5, color='b', fill=False)
circle3 = plt.Circle((10, 10), 2, color='g', clip_on=False)

ax = plt.gca()
ax.cla() # clear things for fresh plot

# change default range so that new circles will work
ax.set_xlim((0, 10))
ax.set_ylim((0, 10))
# some data
ax.plot(range(11), 'o', color='black')
# key data point that we are encircling
ax.plot((5), (5), 'o', color='y')

ax.add_patch(circle1)
ax.add_patch(circle2)
ax.add_patch(circle3)
fig.savefig('plotcircles2.png')

which results in:

You can see how I set the fill of the 2nd circle to False, which is useful for encircling key results (like my yellow data point).

A: #!/usr/bin/python
import matplotlib.pyplot as plt
import numpy as np

def xy(r,phi):
  return r*np.cos(phi), r*np.sin(phi)

fig = plt.figure()
ax = fig.add_subplot(111,aspect='equal')

phis=np.arange(0,6.28,0.01)
r =1.
ax.plot( *xy(r,phis), c='r',ls='-' )
plt.show()

Or, if you prefer, look at the paths, http://matplotlib.sourceforge.net/users/path_tutorial.html

A: If you aim to have the "circle" maintain a visual aspect ratio of 1 no matter what the data coordinates are, you could use the scatter() method. http://matplotlib.org/1.3.1/api/pyplot_api.html#matplotlib.pyplot.scatter
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
r = [100, 80, 60, 40, 20] # in points, not data units
fig, ax = plt.subplots(1, 1)
ax.scatter(x, y, s=r)
fig.show()

A: Extending the accepted answer for a common usecase. In particular:

*

*View the circles at a natural aspect ratio.

*Automatically extend the axes limits to include the newly plotted circles.
Self-contained example:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.add_patch(plt.Circle((0, 0), 0.2, color='r', alpha=0.5))
ax.add_patch(plt.Circle((1, 1), 0.5, color='#00ffff', alpha=0.5))
ax.add_artist(plt.Circle((1, 0), 0.5, color='#000033', alpha=0.5))

#Use adjustable='box-forced' to make the plot area square-shaped as well.
ax.set_aspect('equal', adjustable='datalim')
ax.plot()   #Causes an autoscale update.
plt.show()

Note the difference between ax.add_patch(..) and ax.add_artist(..): of the two, only the former makes autoscaling machinery take the circle into account (reference: discussion), so after running the above code we get:

See also: set_aspect(..) documentation.

A: I see plots with the use of (.circle) but based on what you might want to do you can also try this out:
import matplotlib.pyplot as plt
import numpy as np

x = list(range(1,6))
y = list(range(10, 20, 2))

print(x, y)

for i, data in enumerate(zip(x,y)):
    j, k = data
    plt.scatter(j,k, marker = "o", s = ((i+1)**4)*50, alpha = 0.3)

centers = np.array([[5,18], [3,14], [7,6]])
m, n = make_blobs(n_samples=20, centers=[[5,18], [3,14], [7,6]], n_features=2,
cluster_std = 0.4)
colors = ['g', 'b', 'r', 'm']

plt.figure(num=None, figsize=(7,6), facecolor='w', edgecolor='k')
plt.scatter(m[:,0], m[:,1])

for i in range(len(centers)):

    plt.scatter(centers[i,0], centers[i,1], color = colors[i], marker = 'o', s = 13000, alpha = 0.2)
    plt.scatter(centers[i,0], centers[i,1], color = 'k', marker = 'x', s = 50)

plt.savefig('plot.png')

A: import matplotlib.pyplot as plt

circle1 = plt.Circle((0, 0), 0.2, color='r')
plt.gca().add_patch(circle1)

A quick condensed version of the accepted answer, to quickly plug a circle into an existing plot. Refer to the accepted answer and other answers to understand the details.
By the way:

*

*gca() means Get Current Axis

A: Similarly to scatter plot you can also use normal plot with circle line style. Using markersize parameter you can adjust radius of a circle:
import matplotlib.pyplot as plt

plt.plot(200, 2, 'o', markersize=7)

A: Hello I have written a code for drawing a circle.
It will help for drawing all kind of circles.
The image shows the circle with radius 1 and center at 0,0
The center and radius can be edited of any choice.
## Draw a circle with center and radius defined
## Also enable the coordinate axes
import matplotlib.pyplot as plt
import numpy as np
# Define limits of coordinate system
x1 = -1.5
x2 = 1.5
y1 = -1.5
y2 = 1.5

circle1 = plt.Circle((0,0),1, color = 'k', fill = False, clip_on = False)
fig, ax = plt.subplots()
ax.add_artist(circle1)
plt.axis("equal")
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
plt.xlim(left=x1)
plt.xlim(right=x2)
plt.ylim(bottom=y1)
plt.ylim(top=y2)
plt.axhline(linewidth=2, color='k')
plt.axvline(linewidth=2, color='k')

##plt.grid(True)
plt.grid(color='k', linestyle='-.', linewidth=0.5)
plt.show()

Good luck


text:
Q: C++ Functions with no destructor I am writing a bare-metal C++ application that will enter an infinite loop and then never exit.
I have a number of objects that will be constructed at the top of main() and will never leave scope.  Memory (both code and RAM) is at a premium, as I only have a few k-bytes to work with.
Will the optimizer generally strip out the unused destructors for me?  If not, is there a way to tell the compiler not to generate any default destructors?
Also, is there an analogous way to get rid of some of the other default functions that classes come with (copy constructor etc).

A: With C++11, the default destructor and some other member functions can be deleted.  For a class A this can be done with.
 ~A() = delete;

That said, deleting a destructor does introduce some limitations on how an instance can be created.
For older (pre C++11) compilers, simply don't declare a destructor.     While the compiler will typically create a destructor, it will often be something that is inline and does nothing - so the compiler might elect to eliminate the code entirely.
You'll also need to read your compiler documentation (or examine the code it emits) to understand what it actually does.  When it comes to eliminating unused code - including deleted member functions in C++11 - you are relying on quality of implementation of your compiler.   You might also find that different optimisation settings affect what it does (e.g. whether an empty inline compiler-generated destructor is actually optimised out of existence).

A: If you are using C++11, then the default destructor can be deleted. Check the code below:
class A
{
    public:
        ~A() = delete;
};

A: In some cases when you can't just delete the destructors, then you can move the things from the top of the main function to the global scope, make them static and use the -fno-use-cxa-atexit which will not run at the exit the destructors on statics. Remove the parameter from the compiler options to let the destructor to surface appear:
https://godbolt.org/z/4M484ThEM


text:
Q: Error converting bytecode to dex: Exception parsing classes while Enabling Proguard I am using a library module imported as .AAR in my project and everything works fine untill i enable proguard. After enabling Proguard the library  gives the following Exception on building the project.
I tried everything from Cleaning,Building, Rebuilding the project.
Also tried modifying gradle version from 2.3.0 to 3.3.0 but all in vain.
I have to kept Obfuscation on(which i am not able to do till now).
Tried adding all these to my proguard.txt file:
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-verbose
#-dontobfuscate
# Optimization is turned off by default. Dex does not like code run
# through the ProGuard optimize and preverify steps (and performs some
# of these optimizations on its own).
-optimizations !code/simplification/arithmetic,!code/simplification/cast,!field/*,!class/merging/*
-optimizationpasses 5
#-dontoptimize
-dontpreverify

Exception:

{"kind":"error","text":"Error converting bytecode to dex:\nCause:
  java.lang.RuntimeException: Exception parsing
  classes","sources":[{}],"original":"UNEXPECTED TOP-LEVEL
  EXCEPTION:\njava.lang.RuntimeException: Exception parsing
  classes\n\tat
  com.android.dx.command.dexer.Main.processClass(Main.java:752)\n\tat
  com.android.dx.command.dexer.Main.processFileBytes(Main.java:718)\n\tat
  com.android.dx.command.dexer.Main.access$1200(Main.java:85)\n\tat
  com.android.dx.command.dexer.Main$FileBytesConsumer.processFileBytes(Main.java:1645)\n\tat
  com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:170)\n\tat
  com.android.dx.cf.direct.ClassPathOpener.processDirectory(ClassPathOpener.java:229)\n\tat
  com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:158)\n\tat
  com.android.dx.cf.direct.ClassPathOpener.processDirectory(ClassPathOpener.java:229)\n\tat
  com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:158)\n\tat
  com.android.dx.cf.direct.ClassPathOpener.processDirectory(ClassPathOpener.java:229)\n\tat
  com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:158)\n\tat
  com.android.dx.cf.direct.ClassPathOpener.processDirectory(ClassPathOpener.java:229)\n\tat
  com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:158)\n\tat
  com.android.dx.cf.direct.ClassPathOpener.processDirectory(ClassPathOpener.java:229)\n\tat
  com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:158)\n\tat
  com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:144)\n\tat
  com.android.dx.command.dexer.Main.processOne(Main.java:672)\n\tat
  com.android.dx.command.dexer.Main.processAllFiles(Main.java:574)\n\tat
  com.android.dx.command.dexer.Main.runMultiDex(Main.java:366)\n\tat
  com.android.dx.command.dexer.Main.run(Main.java:275)\n\tat
  com.android.dx.command.dexer.Main.main(Main.java:245)\n\tat
  com.android.dx.command.Main.main(Main.java:106)\nCaused by:
  com.android.dx.cf.iface.ParseException: class name
  (hk/com/domainname/libname/r) does not match path
  (hk/com/domainname/libname/R.class)\n\tat
  com.android.dx.cf.direct.DirectClassFile.parse0(DirectClassFile.java:520)\n\tat
  com.android.dx.cf.direct.DirectClassFile.parse(DirectClassFile.java:406)\n\tat
  com.android.dx.cf.direct.DirectClassFile.parseToInterfacesIfNecessary(DirectClassFile.java:388)\n\tat
  com.android.dx.cf.direct.DirectClassFile.getMagic(DirectClassFile.java:251)\n\tat
  com.android.dx.command.dexer.Main.parseClass(Main.java:764)\n\tat
  com.android.dx.command.dexer.Main.access$1500(Main.java:85)\n\tat
  com.android.dx.command.dexer.Main$ClassParserTask.call(Main.java:1684)\n\tat
  com.android.dx.command.dexer.Main.processClass(Main.java:749)\n\t...
  21 more\n","tool":"Dex"}


text:
Q: How to use different PostgreSQL instace for testing from production I need my docker containers to connect to different PostgreSQL server, depending on the environment (test & production). What I desire is testing my application locally with local database instance, and push the fixes after. From what I read, PostgreSQL's default connection parameters can be determined by environment variables, so I think writing two different environment variables files for test/production and pass the desired one in with --env-file option of docker run command would do the trick.
Is this a suitable way to test & deploy an web application? If not, what would be a better solution?

A: Yes, in general this is the approach you should take when using Docker. Store your DB connection parameters (URL, Username, Password) in environment variables. There is no real need to use an environment file unless you have a ton of environment variables, you could also pass an arbitrary number of "-e" parameters to docker as well. This is closer to how services like amazon's ECS will expect you to pass parameters.
If you're going to write those to a file, make sure that the file is encrypted/encoded somehow - storing database passwords in a file in plaintext is not a great security practice.


text:
Q: displaying icons instead of thumbnails In windows 10, Windows Live Photo Gallery displays icons and not thumbnails. I have tried EVERYTHING with no results. (Well, not quite everything. dod not do the command prompt thing.) I finally resorted to uninstalling it, but now I cannot find any download to reinstall it.

A: Start button > Control Panel > classic view > Folder Options > View tab >UN-check the first box " Always show icons never thumbnails " > OK
Microsoft website prompts Windows Photo Gallery was a part of Windows Essentials 2012 suite reached end of support on January 10, 2017. It is no longer available for download.
But I find that you could try to download it from the link below.
https://answers.microsoft.com/en-us/windowslive/forum/gallery-program/where-to-download-windows-essentials-2012/7665b354-4f2b-445d-811e-9d8c98e8f872


text:
Q: XSLT shortcut for conditional statements I have a ton of this in a large stylesheet and it's making the stylesheet become really cumbersome:
<xsl:when test="Field_Goal_Stats/Field_Goal_Total/FGTtl_Attempted">
               "attempted": <xsl:value-of select="number(Field_Goal_Stats/Field_Goal_Total/FGTtl_Attempted)" />,</xsl:when><xsl:otherwise>
               "attempted": 0,</xsl:otherwise></xsl:choose>

Basically what I'm trying to do is straight forward. I'm trying to grab the number() from a respective XPath. If that fails, normally with NaN, because the field doesn't exist or the field doesn't contain a value that's appropriate for number(), I set it to zero.
Is there anyway to either do this in 1 line or somehow create a re-usable component that I can apply against a ton of other XPath nodes I'm running this code against? Seems wrong to keep doing the whole choose/otherwise pattern in so many parts of my code.

A: You could use a xsl:call-template like this:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>

    <xsl:template match="/">
        <xsl:call-template name="myTemplate">
            <xsl:with-param name="myTestField" select="Field_Goal_Stats/Field_Goal_Total/FGTtl_Attempted" />
        </xsl:call-template>
        <xsl:call-template name="myTemplate">
            <xsl:with-param name="myTestField" select="Field_Goal_Stats/Field_Goal_Total/FGTtl_AttemptedSecondField" />
        </xsl:call-template>
    </xsl:template>

    <xsl:template name="myTemplate">
        <xsl:param name="myTestField" />

        <xsl:choose>
            <xsl:when test="$myTestField">
                "attempted": <xsl:value-of select="number($myTestField)" />,
            </xsl:when>
            <xsl:otherwise>
                "attempted": 0,
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet>

A: In XSLT 2.0 you can do:
<xsl:value-of select="(Field_Goal_Stats/Field_Goal_Total/FGTtl_Attempted,0)[1]"/>

When the value exists, you get it ... when the value doesn't exist, the first value of the resulting sequence is 0.
This is not available in XSLT 1.0.


text:
Q: MYSQL variable IN clause In filtering out some spam, I have two MYSQL statements in one file,
SET @valid_users := '"admin", "jrock", "kmicka", "First Last"';  //etc

Followed by a SELECT like this
SELECT /*stuff*/ /*WHERE*/ /*filters*/ AND User.user_name NOT IN (@valid_users)

When I do this, it acts as if @valid_users is an empty string. (Returns all results).  But if I change the clause to NOT IN ('admin', 'jrock', etc) then it works as it should.
Why would a variable in the NOT IN filter not work?

A: You'll want to take a look at MySQL's find_in_set() function:
SELECT
    *
FROM
    your_table
WHERE
    NOT FIND_IN_SET(User.user_name, @valid_users);

For this to work, the comma-separated list shouldn't contain quotes (unless your usernames actually contain quotes) and should not be padded with spaces:
SET @valid_users := 'admin,jrock,kmicka,First Last';

SqlFiddle Example
To directly answer your question regarding "why would a variable in the NOT IN filter work", it's because @valid_users is being treated as a string and when you pass it to IN(), it's being treated as a single string (i.e. not a set/list). With FIND_IN_SET(), it treats the string in @valid_users as a comma-separated set/list and uses it accordingly.


text:
Q: Java Stream API: Optional if not null proceed I would like to have opportunity to make null check inside the stream:
firstItem = array.stream().min(myComparator).get();
if(firstItem!=null){
     name = firstItem.getData().get("Name")
}

Is it possible to get name right from the Stream?

A: Note that Optional can't contain null values, so your code will either execute the conditional, or fail with an exception at get().
You could change the get() to orElse(null); but you'd still need the separate conditional.
Instead, use Optional.map, then orElse:
String name =
    array.stream()
        .min(myComparator)
        .map(m -> m.getData().get("name"))
        .orElse(someDefaultValue);

Of course, if you don't want to assign a default value, you can omit the final orElse, and make the variable type Optional<String>.

A: Try this:
String name = array.stream().min(myComparator) //
.map(item -> item.getData().get("Name")) //
.orElse("No Name");

A: Unfortunetly there is no way to avoid either some kind of check or a default value (as was already posted in previous answers). Having said that, there is a nice way of doing checks with optionals. Let me give you an example.
I've created simple class for tests.
 class ExampleData
    {
        private String name;
        private int value;

        public ExampleData(String name, int value) {
            this.name = name;
            this.value = value;
        }

        public String getName() {
            return name;
        }

        public int getValue() {
            return value;
        }

        @Override
        public String toString() {
            return "ExampleData{" +
                    "name='" + name + '\'' +
                    ", value=" + value +
                    '}';
        }
    }

Now lets write a simple test method.
 public void testApp()
    {
        ArrayList<ExampleData> array = new ArrayList<>(Arrays.asList(
                new ExampleData("TestName", 1),new ExampleData("TestName1", 2)));
        Optional<ExampleData> min = array
                .stream()
                .min(Comparator.comparingInt(ExampleData::getValue));

               min.ifPresent(System.out::println);

    }

Notice that i didn't use get() right away. Instead i used ifPresent method when i wanted to extract value. I don't know if you ever used C# language but this approach remind me of ? operator from c#.
In c# you would simply do something like this
String name = possibllyNullValue?.getName();

so here in Java you can do something similar with ifPresent()
Of course ifPresent returns void so it can be inconvenient in some cases.


text:
Q: How to Resize the window of my GUI? I normally resize my window using setSize() method but this time round it is not working? I want to resize the window to fit all my components in. I have taken out the majority of my code as it is irrelevant for my question but have left in what is needed. I have found questions with this similar problem but the solutions seem too complicated and I can't replicate them in my code. Here is my class:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

@SuppressWarnings("serial")
public class Display extends JFrame {

    public Display() {
        super("Mandelbrot Set Display");

        JPanel jp = new JPanel();
        //setSize(1000, 1000); this doesnt resize window
        setBounds(0, 0, 800, 600);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        add(jp);

    }

    public static void main(String[] args) {
        new Display().setVisible(true);
    }
}

Thanks

A: Did you try call setSize after setBounds;
 setBounds(0, 0, 800, 600);
 setSize(1000, 1000); //this will resize window

public void setBounds(int x,
               int y,
               int width,
               int height)

If you call setBounds after setSize, width and height is setted by setBounds
import javax.swing.JFrame;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class Display extends JFrame {

    public Display() {
        super("Mandelbrot Set Display");

        JPanel jp = new JPanel();
        setBounds(0, 0, 800, 600); //800 and 600 not effect because of next line setSize method
        setSize(1000, 1000);// this doesnt resize window
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        add(jp);

    }

    public static void main(String[] args) {
        new Display().setVisible(true);
    }
}

A: resize after adding components and containers to the current JFrame.

A: Try calling this.setSize(x, y) :
this.setSize(WIDTH, HEIGHT);

You need to put this before the method call because your class is extended to JFrame and you need to attribute the method setSize at your JFrame using this.


text:
Q: If $F$ is a field show that $F[x]$ is not a field. I know that $ax=1$ has a solution in $F$ so that every element must be a unit but then I'm not sure how to proceed.

A: It's obvious that $F[x]/(x) $ is isomorphic to $F$, and hence $(x)$ is a non trivial proper ideal of $F[x]$, and hence $F[x]$ can't be a field.
(Note that there are other trivial ways of doing this problem, as mentioned in the comments, and an answer above, but I thought of doing this problem in a bit different way, just for fun.)

A: Hint $\rm\rm\,\  x \; f(x) = 1 \,$ in $\rm\ F[x]\, \Rightarrow\, 0 = 1 \, $ in $\rm F \, $  by evaluating at $\rm\ x = 0.\ $
If you know the universal (mapping) property of the polynomial ring then you may find it instructive to interpret the above from that viewpoint (see here).

A: Can you find a polynomial in $p \in F[x]$ such that $p(x)\cdot x = 1$?  Why not?


text:
Q: Awaiting an async function when using Mongodb in node.js I am trying to retrieve all documents from a MongoDB cluster. I've been searching online and using the async/await keywords and have wrote the following code
//Database connection
const MongoClient = require('mongodb');
const uri = "mongodb+srv://user:password@cluster0-10soy.mongodb.net/test?retryWrites=true&w=majority";

async function GetQuestions() {
     MongoClient.connect(uri, async function (err, client) {
        const db = client.db("WhatSportWereYouMadeFor");
        return await db.collection("Questions").find().toArray();

    });
}

async function main(){
    let questions = await GetQuestions();
    console.log(questions);
}

main();

From my understanding of the async/await pattern theconsole.log(questions) line should only be hit after the return inside GetQuestions is hit, however that is not the case.

A: You should return a Promise with the result of Mongoose:
const MongoClient = require('mongodb');
const uri = "mongodb+srv://user:password@cluster0-10soy.mongodb.net/test?retryWrites=true&w=majority";

async function GetQuestions() {
     return new Promise((resolve, reject) => {
         MongoClient.connect(uri, function (err, client) {
             const db = client.db("WhatSportWereYouMadeFor");
             resolve(db.collection("Questions").find().toArray());
         });
     });
}

async function main(){
    let questions = await GetQuestions();
    console.log(questions);
}

main();


text:
Q: Survivor Function vs. Hazard Function I'm attempting to understand what the survivor and hazard functions describe under a non-traditional context. I have data comprising distances between successive points on a line ($1D$ vector):

Traditionally in my field, such data is fitted with a gamma-distribution in an attempt to describe the distribution of the points. For example, such data may yield a best-fit (MLE) gamma of $\alpha = 3.5$, $\beta = 450$. In plotting this distribution as a survivor function, I obtain:

And as a hazard function:

Under this context, what is each plot describing? It was my understanding that the hazard function could be understood as describing the probability of finding another point when a point already exists at $x(0)$ i.e. the further away from a pre-existing point you go, the higher the chance is that you will encounter another point. However, I am not entirely sure if this is correct.
With regards to the survivor function, I'm struggling to translate the typical descriptions of it (regarding time, populations etc.) into a more applicable understanding.
Any help would be greatly appreciated.

A: The theory about survival analysis usually regards time to event data, but I would say that the concepts can be transferred here without loss of generality.
You usually have (referring to the wiki article: wiki )
$S(t) = P(T>t)$ = survival function, which is basically the probability that the event has not happened yet at time t, where the event could be the death of a patient or the malfunction of some machinery and T is the random variable describing it.
$h(t) = lim_{dt \to 0} \frac{P(t \leq T<t+dt)}{dt*S(t)} = - \frac{S'(t)}{S(t)}$ is the hazard function and from wiki Suppose that an item has survived for a time t and we desire the probability that it will not survive for an additional time dt: this is the hazard function/rate.
You usually assume that $T_i$ time of death of patient i, is independent from $T_j$ time of death of patient j, for any $j \neq i$.
So i would Say that you could define a set of independent R.V. $X_i$ = distance where I occur in point i, measured from i-1 with $i=1,..,n$, where $n$ = number of points (not considering the first one).Being independent means that the distance between point $i$ and $j$ does not depend on the distances between any other 2 points.
Given this assumptions I'd say:
$D(x)=P(X>x)$ is your 'survival function'.
$h(x) = -\frac{D'(x)}{D(x)}$ is your hazard rate/function.


text:
Q: find matching value in a column based on other vector I have a data frame and vector like this:
df1 <- data.frame(orig = c(1,1,1,2,2,2,2,3,3),
                  proxy = c(1,43,65,2,44,45,46,3,55),
                  dist = c(0, 100,101, 10, 1000, 5000, 5001,0,3))

v <- c(1,45:100)

I now want the following:
For each unique value in df1$orig (here it's a numeric for simplicity, but it could be character too), if the same orig value is not available in v, find the best proxy that has the lowest dist.
In this example the first value in df1$orig is 1 and this value is available in v as well, so we take it.
The second unique value in df$orig is 2 and this is not available in v. The best proxy with the lowest dist is 44 in this case, but it is not in v either. The next best is 45 and this value is in v so we take it.
The third unique value in df1$orig is 3 and there is no 3 in v. The best proxy here is 55.
the solution is c(1,45,55)
Note that the first value for each orig in proxy is the orig value.
dist is sorted here but not necessarily the case always.

A: This can be done in a couple of steps with {dplyr}: keep the proxies that are in v, sort by dist and pick the first for each orig:
library(dplyr)

df1 %>%
  filter(proxy %in% v) %>%
  arrange(dist) %>%
  group_by(orig) %>%
  slice(1)
#> # A tibble: 3 x 3
#> # Groups:   orig [3]
#>    orig proxy  dist
#>   <dbl> <dbl> <dbl>
#> 1     1     1     0
#> 2     2    45  5000
#> 3     3    55     3

Created on 2019-09-11 by the reprex package (v0.3.0)

A: In case you are beside a dplyr solution also interested in a base solution.
Fist reduce to those which have a match between proxy and v, then order by orig and dist and then take those which are not duplicated.
tt <- df1[df1$proxy %in% v,]
tt <- tt[order(tt$orig, tt$dist),]
tt[!duplicated(tt$orig),]
#  orig proxy dist
#1    1     1    0
#6    2    45 5000
#9    3    55    3

Or in case you losse some orig when there is not match between proxy and v you can use:
tt <- df1[df1$proxy %in% v,]
tt <- tt[order(tt$orig, tt$dist),]
tt <- tt[!duplicated(tt$orig),c("orig", "proxy")]
tt$proxy[match(unique(df1$orig), tt$orig)]
#[1]  1 45 55


text:
Q: Java Class Path error in SAS I am trying to call a java class object from a data step in SAS. The Java class file has been placed in the class path./dir/folder_location
The class path variable for SAS has been changed to the folder where the class files are stored. This has been verified from the SAS enterprise Guide where I am printing the class path to the logs
SYSGET("CLASSPATH") returns /dir/folder_location
When I run the following path to declare a java object in the class:
   data _null_;
   declare javaobj j ('Classname');
   run;

This gives me an error that
ERROR: Could not find class 'ClassName' at line x column y. Please ensure that the CLASSPATH is correct.
ERROR: DATA STEP Component Object failure. Aborted during the EXECUTION phase.
Als when i get the java info by using the command
PROC javainfo CLASSPATHS;
run;

This returns a different path. Is this different than the above class path?
Does anyone have thoughts on as to why this is happening and what the solution is?
Thanks in advance.

A: Is your Java class in a JAR file, by chance?  If so, the documentation seems to say the classpath needs to include the .jar file.
In SAS, you must set the CLASSPATH environment variable so that the Java object can find your Java classes. The Java object represents an instance of a Java class that is found in the current Java classpath. Any class that you use must appear in the classpath. If the class is in a .jar file, then the .jar filename must appear in the classpath.
http://support.sas.com/documentation/cdl/en/lrcon/67227/HTML/default/viewer.htm#n0swy2q7eouj2fn11g1o28q57v4u.htm#p1eop5jjb9digin1adfp22tmssl0

A: SAS documentation is as crap as usual in this subject (either).
In client/server application the spawner omits the user's enviroment variables on the server.
Fortunately I found a very simple solution.
Try this:
options set=CLASSPATH "your classpaths here";

A: Maybe you can set classpath in simple mode in sasv9 config file.
It is usually on this installation path:
c:\SAS94\x86\SASFoundation\9.4\sasv9.cfg

Or not x86 version on:
c:\SAS94\SASFoundation\9.4\sasv9.cfg

You can register your JAR file in this row end on the config.
Example:
-Dsas.app.class.path=/sas/sas94/SASVersionedJarRepository/eclipse/plugins/tkjava.jar:/yourpath/your.jar

I remember the earlier version are same (9.3,9.2,9.1)


text:
Q: Osprey RAML Validation Error Handling I am trying to custom handle response sent to caller due to RAML specification failure. At the moment my code does the following.
const cfg = require("./cfg");
const log = require('./logging');
const RAML = require('osprey');
const startMessage = "My Service started on port " + cfg.SERVER_PORT + " at " + cfg.API_MOUNT_POINT;

// start an express server
const start = x => {
  // server dependencies
  const fs = require('fs'),
  express = require('express'),
  app = express(),
  router = express.Router(),
  bodyParser = require('body-parser'),
  api = require('./api');

  RAML.loadFile(cfg.API_SPEC).then(_raml => {

    app.use(bodyParser.json({ extended: true }));
    // hide the useless "powered by express" header
    app.disable('x-powered-by');
    // RAML validation
    app.use(cfg.API_MOUNT_POINT, _raml);
    app.use(cfg.API_MOUNT_POINT, api);
  })
  .then(v => {
    app.listen(cfg.SERVER_PORT, function() {
        log.info(startMessage);
    });
  })
  .catch(e => log.error(e));
}

This works well but the response sent to caller when validation fails is shown below.
{
  "errors": [
    {
      "type": "json",
      "dataPath": "redeemtype",
      "keyword": "required",
      "schema": true,
      "message": "Missing required property: redeemtype"
    }
  ],
  "stack": "BadRequestError: Request failed to validate against RAML definition\n    at createValidationError (/Volumes/Devel/dollardine/node_modules/osprey-method-handler/osprey-method-handler.js:735:14)\n    at ospreyJsonBody (/Volumes/Devel/dollardine/node_modules/osprey-method-handler/osprey-method-handler.js:448:21)\n    at handle (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:56:16)\n    at dispatch (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:39:20)\n    at next (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:37:24)\n    at jsonParser (/Volumes/Devel/dollardine/node_modules/body-parser/lib/types/json.js:94:7)\n    at handle (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:56:16)\n    at dispatch (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:39:20)\n    at middleware (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:41:16)\n    at /Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:10:16\n    at ospreyContentType (/Volumes/Devel/dollardine/node_modules/osprey-method-handler/osprey-method-handler.js:325:17)\n    at handle (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:56:16)\n    at dispatch (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:39:20)\n    at next (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:37:24)\n    at ospreyMethodHeader (/Volumes/Devel/dollardine/node_modules/osprey-method-handler/osprey-method-handler.js:262:12)\n    at handle (/Volumes/Devel/dollardine/node_modules/compose-middleware/lib/index.js:56:16)"
}

This is great, but I do not want to send all this info to caller. I want just log it locally and just sent {"code": 400, "message": "Invalid input"}
How can I make osprey to give me ability to handle the error response?

A: I found answer to my own question. In case anyone in future gets stuck here.
const start = x => {
  // server dependencies
  const fs = require('fs'),
  express = require('express'),
  app = express(),
  router = express.Router(),
  bodyParser = require('body-parser'),
    api = require('./api');

  const ramlConfig = {
    "server": {
      "notFoundHandler": false
    },
    "disableErrorInterception": true
  }

  osprey.loadFile(cfg.API_SPEC, ramlConfig).then(_raml => {

    app.use(bodyParser.json({ extended: true }));
    // hide the useless "powered by express" header
    app.disable('x-powered-by');
    // RAML validation
    app.use(cfg.API_MOUNT_POINT, _raml);
    app.use(customNotFoundHandler);
    app.use(ramlErrorChecker);

    app.use(cfg.API_MOUNT_POINT, api);
    //app.use(ramlErrorChecker);
  })
  .then(v => {
    app.listen(cfg.SERVER_PORT, function() {
        log.info(startMessage);
    });
  })
  .catch(e => log.error(e));
}

const ramlErrorChecker = (err, req, res, next) => {
  if (err) {
    log.error("RAML validation failed. Reason: " + err);
    res.status(400);
    return res.json(buildResponseJSON(400));
  }
  return next();
}

const customNotFoundHandler = (req, res, next) => {
  // Check for existence of the method handler.
  if (req.resourcePath) {
    return next()
  }
  res.status(404);
  return res.json({"message": "The path is not found"});
}

The important part is ramlConfig which helps in putting some customisation. By setting "disableErrorInterception" to true, we are taking over the error handling which is much better for standardisation and most importantly hiding the fact the RAML is being used. Setting "notFoundHandler" to false means, the undeclared routes are reject gracefully instead of random html.


text:
Q: average correlation of z dim of an x,y rolling window in numpy I would like to write some code that helps me assess how good some fits are. I have a 3D matrix. The z dimension is a fit to some data at point i, j of the matrix. I would like to assess if this fit is good by comparing the fit at point i, j to the fits of its nearest neighbours (in the x,y dimension). If the fits of the neighbours are similar to the fit at that point then I would like to keep the fit. I hope that makes sense.
What that boils down to is: is there a good way to have a rolling window across the x,y dimension that calculates the Pearson's r in the z dim of the window central point to all the other points in the window and takes the mean (or even the number of points with r greater than some constant).
I can only think how to do this in a very long handed inefficient way currently. For some background information, I am fitting these data with a fourier series. Ultimately I want to use this technique to assess the minimum number of waves to use in the fourier fits at each point.
Thanks in advance
Niall

A: This is my solution but its not very efficient. (by the way, was another dimension of data I didn't bother telling you about in the question. Has anyone got any suggestions of more efficient ways to do this?
Thanks again
import numpy as np
from scipy.stats import pearsonr
from bottleneck import nanmean

def calc_corr_of_neighbours(data, win_shape):
    rs = np.empty(data.shape[1:])
    thisrs = np.empty(win_shape)
    win_data = np.empty(win_shape)
    dA = int(win_shape[0]/2)
    dB = int(win_shape[1]/2)
    maxA = data.shape[2]
    maxB = data.shape[3]

    for i in np.ndindex(rs.shape):
        stA = max(i[1]-dA, 0)
        endA = min(i[1]+dA, maxA)
        stB = max(i[2]-dB, 0)
        endB = min(i[2]+dB, maxB)

        win_data = data[:, i[0], stA:endA, stB:endB]

        thisrs.fill(np.NaN)
        for j in np.ndindex(win_data.shape[1:]):
            thisrs[j] = pearsonr(data[:, i[0], i[1], i[2]], win_data[:, j[0], j[1]])[0]

        rs[i] = nanmean(thisrs)

    return rs


text:
Q: Почему тег form в к относительному адресу добавляет "?" Есть форма в node.js, атрибут action="/registration". Файл registration.html существует и находится в той-же директории, что и index.html . Почему при клике на кнопку в form к адресу добавляется "?", и получается
http://localhost:3000/registration?
Что не так? И что означает знак "?"?

A: Обычно знак "?" в URL означает что после него пойдут get-параметры.
Например,  http://localhost:3000/registration?name='John'&surname='Smith'
В вашем случае, скорее всего, форма отправляется методом GET, вот и добавляется "?"

A: Используйте для подобных форм и запросов метод POST
Для этого добавьте атрибут method с соответствующим значением
Пример для формы:
<form method="POST">
....
</form>


text:
Q: I want to create a button on my webpage that activates the action of a tab on the same page using jquery if possible I currently have a tab on my page (created with Jquery UI) that when clicked expands some content that is collapsed on page load.  I want to be able to activate that tab's action by pressing a separate button on the site.  For example, here is the jquery script that makes the tab work it uses Jquery UI core, and the scrollTo plugin:

And the tab looks like this:

Testimonials

THE CONTENT IS HERE

So I want to put a button elsewhere on the page that expands this content and scrolls to the content, essentially this button, when clicked, will do the exact thing that the "Testimonials"
 tab does.  It would expand #testimonial, and scrolls to it.

A: Couldn't you use the .trigger() function on the element?
For example, if you had an element with the ID of 'button', the following code should do what you want:
$('#button').click(function(){
    $('.scrolltoanchor').trigger('click');
});

jsFiddle example.


text:
Q: Jquery Ajax .load loops i have a problem. The script below works not well. The problem is when i am clicking on a link in the lister page i get the detail, but when i am clicking once more he refresh 2 times en when i am clicking 2 times he refreshing 4 times and so on.
Can somebody help me what i do wrong?
Kr BAs
indexpage

Javascript general.js
$(document).ready(function(){
//returns LISTER
$('ul#ajaxNav li a').click(function() {
    var page = $(this).attr('href');
    $('#content').fadeOut().load('classes/cAjaxLister.php'+ page).fadeIn();
    return false;
});

//returns Detail
$('td ul#ajaxLister li a').click(function() {
    var page = $(this).attr('href');
    $('#contentLister').fadeOut().load('classes/cAjaxLister.php'+ page).fadeIn();

    return false;
    });

});

lister and detailpage
    echo '

view

edit

delete

    	';
    echo '
'.PHP_EOL;

A: I apologize as I may not be overly knowledgeable with javascript, but the issue seems to come from clicking on the A tag. You need to use an event parameter in your click function and then prevent the link from redirecting:
    $(document).ready(function(){
    //returns LISTER
    $('ul#ajaxNav li a').click(function(event) {
        event.preventDefault();
        var page = $(this).attr('href');
        $('#content').fadeOut().load('classes/cAjaxLister.php'+ page).fadeIn();
        return false;
    });

    //returns Detail
    $('td ul#ajaxLister li a').click(function(event) {
        event.preventDefault();
        var page = $(this).attr('href');
        $('#contentLister').fadeOut().load('classes/cAjaxLister.php'+ page).fadeIn();

        return false;
        });

    });

http://api.jquery.com/event.preventDefault/


text:
Q: Ubuntu Core for non eMMC Intel NUCs Is there any method to install Ubuntu Core onto an Intel NUC without eMMC ?
I have a bunch of older NUCs that don't have the eMMC storage; I'd like to install core on the hard disk, is that documented or an option?
Thanks
J.

A: I actually need to confirm that writing the ubuntu core image to disk (a brand new one, there was no tolerance for an older one I initially tried) worked, same instructions, advised to wipe the disk using disk tools prior to the dd.
Thanks again to GabrielaGarcia, I do appreciate the answer but would like to remind you I asked an open question and really didn't deserve to be to rudely treated. I don't need to validate my *nix experience but would ask that your less rude and hostile in future comments or replies. My own initial comment was equally (if not more so) rude and with the benefit of hindsight appreciate neither was helpful or valid.
Have a nice day :)


text:
Q: Generating JPEG tiles using gdal2tiles.py? I am using gdal2tiles.py to generate tiles and packing it into MBTiles using mb-util.
gdal2tiles by default generates PNG tiles. When I convert PNG tiles to JPEG large black area around tiles are left (due to lack of transparency in JPEG):
http://www.imagemagick.org/discourse-server/viewtopic.php?f=1&t=24048
Is there a way to directly generate JPEG tiles in gdal2tiles.py ?
I am using GDAL 1.9.2 on Ubuntu 12.04.

A: for resolve the problem of black areas is necessary to proceed this way:
1) create a virtual mosaic of the images with the param -vrtnodata 255:
gdalbuildvrt test.vrt -vrtnodata 255 *.tif
this add a white background to the mosaic
see this explanation: http://lists.osgeo.org/pipermail/gdal-dev/2010-January/023032.html
2) download the correct prj file from
http://spatialreference.org/
3) run gdal2tiles
python3.4 /usr/local/bin/gdal2tiles.py -p raster -s 3003.prj -v test.vrt out
NOTE:
with the official gdal2tiles is not possible to generate JPEG, only PNG.
has explained here in the last open source beta version of maptiler there was an upgraded version of gdal2tiles that permit to generate JPEG tiles.
https://trac.osgeo.org/gdal/ticket/5624
the option is –tile-format jpeg
the complete command is:
python gdal2tilesNew.py  --tile-format jpeg -p raster -s 3003.prj prova_white.vrt output_folder_white
THIS SEEMS TO BE A FORK OF THE LATEST VERSION OF GDAL2TILES
https://github.com/mj10777/mapmbtiles


text:
Q: Integral on manifold with orientation given by vector I have task described below. I'm not sure if I started correctly and how to finish (include orientation to calculations). Could you check it and give me some explanations?

Let $S = \lbrace (x, y, z) \in \mathbb{R}^3: x^2 + y^2 +z^2 = 1, x+y+z=0, x\geq0 \rbrace$,
  find $p \in S$ such that vector $v = (1, -1, 0)$ is tangent
  at the point $p$.
Let $\omega = x~dy - y~dz$. Calculate $\int_S \omega$,
  where orientation is given by $v$ at the $p$.

$v$ have to be orthogonal to $\{x^2+y^2+z^2\}$ and $\{x+y+z=0\}$. It's not hard to show that $p = (\frac{1}{\sqrt{6}}, \frac{1}{\sqrt{6}}, \frac{-2}{\sqrt{6}}) \in S$ is our point.
Then I tried to find parametrization. $z = - (x+y) \Rightarrow 2(x^2 + y^2 + xy) = 1$, now looking at $y$ as parameter:
$$
x^2 + yx + (y^2-\frac{1}{2}) = 0\\
\Delta = y^2-4(y^2-\frac{1}{2})=2-3y^2 \geq 0 \Leftrightarrow\\
\sqrt{\frac{2}{3}} \geq |y|\\
x = \frac{-y + \sqrt{\Delta}}{2} ~~~~ \because x \geq 0\\
y \leq \sqrt{\frac{1}{2}} ~~~~ \because x \geq 0\\
y \in \left[ -\sqrt{\frac{2}{3}}; \frac{1}{\sqrt{2}} \right] =A'\\
A = \text{int} A'
$$
So I made parametrization (we removed only two extreme points - measure 0)
$$
\psi(t) = \left( \frac{-y + \sqrt{2-3y^2}}{2}, y, - \frac{y + \sqrt{2-3y^2}}{2}\right)
$$
And now forgetting about orientation, we can calculate
$$
\int_S \omega = \int_A \frac{-y + \sqrt{2-3y^2}}{2} \cdot 1 - y \cdot \left(-\frac{1 - \frac{3y}{\sqrt{2-3y^2}}}{2}\right)~dy=\\
\frac{1}{2}\int_A (\sqrt{2-3y^2} - y) + y - \frac{3y^2}{\sqrt{2-3y^2}}~dy =\\
\frac{1}{2}\int_A \frac{2-3y^2}{\sqrt{2-3y^2}} - \frac{3y^2}{\sqrt{2-3y^2}} = \frac{1}{2} \int_A \frac{2-6y^2}{\sqrt{2-3y^2}}\\
= \frac{1}{4}
$$
And how should I include information about orientation now, when given is vector $v$ at point $p$? I understand what orientation is (as one of two class of abstraction). When two parametrization has same orientation. Why I can check only at one point. Etc. I know some imagination methods like "if you are walking..." (I saw MIT lectures and I have to say that my imagination is very poor).
So, how can I check it algorithmically? Without using imagination, only with calculations.
I will be very grateful for general answer for any manifold ($m$-dimentional in $\mathbb{R}^n$) and example on $S$ from given task.


text:
Q: Rethrow original exception when catch clause has another try-catch which throws nothing - equivalent in Reactive pipeline I have a method which would be like this in traditional, imperative try-catch coding style:
void confirmCart(Checkout Order) {
    try {
        cartService.confirm(order.getCartId(), order.getCartHash());
    } catch (Exception ex1) {
        log.error("Confirm error: ", ex1);
        try {
            paymentService.cancel(order.getPaymentTransaction().getGatewayReference());
            throw ServiceException.wrap(ex1, CheckoutErrorCode.FAILED_CONFIRMING_CART);
        } catch (Exception ex2) {
            throw ServiceException.wrap(ex2, CheckoutErrorCode.FAILED_CANCELLING_PAYMENT);
        }
    }
}

The requirement is:

*

*when cartService.confirm() works, returns nothing

*when it fails, enter catch part, and try paymentService.cancel()

*if 2 fails, throw ex2

*if 2 succeeds, throw ex1(because confirm() has failed, anyway)

*depending on the exception thrown here, controller will do different things

Now, in Reactive style, it is like:
    Mono<Void> confirmCart(CheckoutOrder order) {
        return cartService.confirm(order.getCartId(), order.getCartHash())
                .onErrorMap(throwable -> {
                    log.error("Failed confirming cart! cartId: '{}', cartHash: '{}'", order.getCartId(), order.getCartHash(), throwable);
                    return ServiceException.wrap(throwable, CheckoutErrorCode.FAILED_CONFIRMING_CART);
                })
                .onErrorResume(throwable -> {
                    log.trace("Cancelling payment with order id {}", order.getId().toString());
                    // when confirmation fails, 1. cancel payment and 2. throw original exception to notify controller -> exception handler
                    return paymentService.cancel(order.getPaymentTransaction().getGatewayReference())
                            .map(paymentCancellationResponse -> {
                                log.trace("payment cancellation response: {}, order id: {}", paymentCancellationResponse, order.getId().toString());
                                return paymentCancellationResponse;
                            }).then()
                            .onErrorMap(e -> {
                                log.error("payment payment cancellation failed. ", e);
                                return ServiceException.wrap(e, CheckoutErrorCode.FAILED_CANCELLING_PAYMENT);
                            });
                });
    }

But, I have spent a lot of time playing with Reactive operators and cannot find any way to rethrow the original exception. The code above compiles, but will not throw the first exception when confirmCart() fails. I guess because onErrorMap() and onErrorResume() cannot coexist; the latter one will be honored, maybe?
I have tried with onErrorMap because besides, it should be synchronous: confirmCart() should wait for paymentService.cancel() if it fails.
I was playing with then(), thenReturn() and so on, but I can make it compile, but it does not return/rethrow the first confirmation exception.
return cartService.confirm(order.getCartId(), order.getCartHash())
        .onErrorResume(throwable -> {
            log.error("Failed confirming cart! cartId: '{}', cartHash: '{}'", order.getCartId(), order.getCartHash(), throwable);
            log.trace("Cancelling payment with order id {}", order.getId().toString());
            // when confirmation fails, 1. cancel payment and 2. redirect user to checkout page
            return paymentService.cancel(order.getPaymentTransaction().getGatewayReference())
                    .map(paymentCancellationResponse -> {
                        log.trace("payment cancellation response: {}, order id: {}", paymentCancellationResponse, order.getId().toString());
                        return paymentCancellationResponse;
                    }).thenReturn(
                        ServiceException.wrap(throwable, CheckoutErrorCode.FAILED_CONFIRMING_CART)
                    )
                    .onErrorMap(e -> {
                        log.error("payment payment cancellation failed. ", e);
                        return ServiceException.wrap(e, CheckoutErrorCode.FAILED_CANCELLING_PAYMENT);
                    }).then();
        });

In the test I have no exception thrown when cartService.confirm() fails.


text:
Q: Jstree get all child node I am using Jstree plugin and i want to get the all child node of the selected node without expanding it.
I googled little bit and came know that it can be done using below code.

checked = $("#tree").jstree("get_checked",null,true) ;

But its not working for me, I need to expand/open node first in order to get its children.
Here is sample code that i am using

$("#treeview-CarrierGroup").jstree("get_checked", null, true).each(function (item) {
            alert($(this).attr("id"));
       });

Please let me know if its possible to get child node of selected parent node without expanding/opening it.
Thank

A: It looks like you are using the wrong method for a start. .get_checked ( context, get_all ) is part of the checkbox plugin. You want ._get_children ( node ). Docs for core of jstree1
Also, if you are using lazy loading and a node is not loaded, you will not be able to get its children in this fashion because they simply do not exist yet. That is possibly why you are seeing a difference between before and after you have expanded the node. There are various solutions to this:
You could manually load the node before getting its children.
Or if you are simply after the list of children and don't really need to visualize it in the jstree, you could use another ajax call to get this information independantly of the jstree.

A: $('#tree').find('.jstree-node')


text:
Q: Ambiguous Columns and Count My query requires me to find the busiest location by number of people (Schema Attached)
select DISTINCT location.name as 'Location', f_name|| ' ' || l_name as 'Citizen'
from CheckIn
join location on checkin.LocID = Location.LocID
join  person on person.PersonID = CheckIn.PersonID

With the above query. I can find the people who visited the locations but I cannot find the most number of people who visited a location as they all show individually. I know I need to add a count or group by.
If I try to put the count as per below
select DISTINCT location.name as 'Location', f_name|| ' ' || l_name as 'Citizen', count (personid)
from CheckIn
join location on checkin.LocID = Location.LocID
join  person on person.PersonID = CheckIn.PersonID

It will show me ambiguous column. I know it is saying that because I have used it as a join but then how do I count the persons If I cannot reuse it?
How do I fix this code to show me the busiest location by number of people?

A: This query:
SELECT LID, COUNT(*)
FROM CheckIn
GROUP BY LID

returns the number of people visited each LID.
You can also use window function RANK() to rank each location by the number of people:
SELECT LID, RANK() OVER (ORDER BY COUNT(*) DESC) rnk
FROM CheckIn
GROUP BY LID

Finally you use this query with the operator IN to return the details of the locations ranked first:
SELECT * FROM Location
WHERE LocationID IN (
  SELECT LID
  FROM (
    SELECT LID, RANK() OVER (ORDER BY COUNT(*) DESC) rnk
    FROM CheckIn
    GROUP BY LID
  )
  WHERE rnk = 1
)

A: You can try below:
select
  name, COUNT(P.PersonID) as People_Count
from Location AS L
inner join checkin as C on C.LocID = L.LocID
inner join  person as P on P.PersonID = C.PersonID
group by name
order by COUNT(P.PersonID) desc


text:
Q: How to find the selected value from the dropdown using Jquery

    <input data-notr="1" name="TestFIName" id="TestFIName" class="awe-val" type="hidden" value="7126">
    <select class="awe-display awe-field form-control" style="background-color: rgb(255, 255, 255);">
        <option value="">--Select test--</option>
        <option value="7172">1000RPM 380PBA all patterns</option>
        <option value="7173">1000RPM low load tight all patterns</option>
        <option value="7141">10pct 2KM noise without krrefend learned mp data</option>
        <option value="7174">1500RPM 230PBA all patterns loose</option>
        <option value="7175">2000RPM 230 PBA all patterns</option>
        <option value="7176">2000RPM low load tight all patterns</option>
        <option value="7179">2500RPM 230 PBA all patterns and continuous random</option>
        <option value="7177">2500RPM pattern misfire no load line</option>
        <option value="7131">2MF_2SF-7003_1_CELL4_20160506_006</option>
        <option value="7128">2MF_2SF-7003_10cStart_CELL4_20160506_003</option>
        <option value="7129">2MF_2SF-7003_4hrSoak1_CELL4_20160506_004</option>
        <option selected="selected" value="7126">2MF_2SF-7003_FIMISFIRE_CELL4_20160506_002</option>
        <option value="7125">2MF_2SF-7003_IGMISFIRE_CELL4_20160506_001</option>
        <option value="7130">2MF_2SF-7003_InGear4hrSoak1_CELL4_20160506_005</option>
        <option value="7142">2YM 10pct offset noise file Feb 2016</option>
        <option value="7168">2YM MF toughness2 219AT SW and fire air rev2 052716</option>
        <option value="7152">3500 higher loads issue</option>
        <option value="7153">4000 rpm low load and 230 MF data</option>
        <option value="7154">4500 rpm 380 pba detection</option>
        <option value="7155">4500 rpm low load</option>
        <option value="7178">drive 600rpm all misfire types OK</option>
        <option value="7157">drive with 10pct noise in cyl3</option>
        <option value="7158">drive with cylinder5 offset noise</option>
        <option value="7160">neutral with 10pct noise in cyl3</option>
    </select>

How to find the selected option here using Jquery.

A:

  <input data-notr="1" name="TestFIName" id="TestFIName" class="awe-val" type="hidden" value="7126">
  <select class="awe-display awe-field form-control" style="background-color: rgb(255, 255, 255);">
    <option value="">--Select test--</option>
    <option value="7172">1000RPM 380PBA all patterns</option>
    <option selected="selected" value="7126">2MF_2SF-7003_FIMISFIRE_CELL4_20160506_002</option>
    <option value="7125">2MF_2SF-7003_IGMISFIRE_CELL4_20160506_001</option>
    <option value="7130">2MF_2SF-7003_InGear4hrSoak1_CELL4_20160506_005</option>
    <option value="7142">2YM 10pct offset noise file Feb 2016</option>
    <option value="7168">2YM MF toughness2 219AT SW and fire air rev2 052716</option>
    <option value="7152">3500 higher loads issue</option>
    <option value="7158">drive with cylinder5 offset noise</option>
    <option value="7160">neutral with 10pct noise in cyl3</option>
  </select>

jQuery
alert($(".awe-ajaxdropdown-field select").val());


text:
Q: Why is simulation effective bandwidth of LM741CN op-amp wider than calculations says it should be? For my electronics course, I have been tasked with creating a circuit that will take a \$10\text{mV AC}\$ input and amplify by a factor 490 using the LM741CN op-amp with an effective bandwidth (attenuation less than 3dB) from \$1\text{ Hz}\$ to at least \$20\text{ kHz}\$. Knowing that its \$f_t = 1.5\text{ MHz}\$, I know I must split the gain into two stages to increase the bandwidth or else
$$f_{-3\text{dB}}=\frac{f_t}{A_{CL-O}}=\frac{1.5\text{ MHz}}{490}=3.06\text{ kHz.}$$
This lead me to having two stages each with the square-root of the original 490 gain (\$7\sqrt{10} \approx 22.13\$). To do this, I used two inverting op-amps configurations so that the gain would simply be \$-\frac{R_2}{R_1}\$ and set \$R_2 = 22.13 \text{ k}\Omega\$ and \$R_1 = 1 \text{ k}\Omega\$. I do this twice and I get the required gain. This also has the added benefit of increasing \$f_{-3\text{dB}}\$ to \$67.8\text{ kHz}\$.
However, I also have to account for the slew rate of the op-amp, which for the LM741CN is \$0.5\text{ V}/\mu s\$. This brings the maximum frequency to:
$$f_m = \frac{\text{SR}}{2\pi\hat{v}_o} = \frac{0.5\text{ V}/\mu s}{2\pi\times 10 \text{ mV} \times 490} = 16.1\text{ kHz}$$
This posed a problem to me so I went on to NI Multisim to simulate the bode plot for the planned circuit. Here is the circuit:

And here is the bode plot for the output vs input:

The most notable piece of information is the fact that the effective bandwidth (as I've described above, the frequency range where attenuation is less than 3dB) reaches past \$20\text{ kHz}\$, all the way above \$24\text{ kHz}\$. The regular gain (gain at 1 Hz) is 53.797 dB so at 50.797 dB, I take that to be ineffective. Yet at \$16.1\text{ kHz}\$, there is only 1.438 dB of attenuation.
My question is why is this happening? Why is the effective bandwidth larger than what my calculations tell me they should be. I can't find out what I did wrong with my calculations, and I am not sure if there are any other equations to consider.
EDIT: Some more info I was informed should be part of the post:
My actual task is described here:

It doesn't say anything specifically regarding 3dB being the point at which frequencies are ineffective, but it does talk about total harmonic distortion, which I assumed would be similar to the 3dB limit since my class still hasn't actually taught anything about calculating it, and I am not sure if it is possible to calculate in a theoretical POV. It also mentions the LM318N, but I got that to work fine in my calculations.

A:
My question is why is this happening?

You are probably using an AC simulation to generate the Bode plot.
The AC simulation method assumes circuit linearity, therefore it neglects the slew rate effect.
As to why you don't get the full 67.8 kHz you calculated under linear assumptions, probably there is either some loading effect due to the relatively low (for a 741) 1 kohm load on the first stage, as well as some compounding effect where the net gain of the two stages drops by more than 3 dB before either of the individual stages drops by 3 dB. The LM741 model in Multisim might also have different values for \$f_t\$ and \$A_{CL-O}\$ than you used in your calculations.

A: Photon has explained why AC analysis does not give the correct answer when nonlinear effects such as slew-rate limiting (or crossover distortion) are significant.
The slew rate limitation is baked into the LM741 by the design choice of the compensation, however if you make a bridging amplifier you can achieve the design goal for typical (not worst case) slew rate as below:

simulate this circuit – Schematic created using CircuitLab
If you needed a ground-referenced output you could also build a discrete output amplifier for the output 741 and close the loop around it. It would resemble the output stage of an audio amplifier.
Of course it would be much easier to  use another amplifier such as a TL081 or LM318.


text:
Q: Best voltage regulator for high current application? I have high-current devices (10 A) of variable resistance and I am researching their current-voltage behavior over time. I want to operate several devices in series using only a single power supply which delivers a constant DC current of 10 A. However, the voltage drop across each device may never exceed 2.5V as this would cause overheating.
So, here are the requirements for my circuit:

*

*Ideally, 10 A runs through each device (whatever the voltage drop).

*If the resistance of a device increases such that the voltage drop would exceed 2.5 V, it should be held at 2.5 V instead (still drawing current - but now less than 10 A).

*I should be able to disconnect each device from the series circuit without affecting the others.

Below is a simple depiction of the desired circuit which I hope is helpful. I'm looking for circuit elements that are maybe something like a very-high-power Zener diode. Thank you!

A:
I have a device that's directly connected to a power supply. The power supply is set to a 10A current limit and a 2.5V voltage limit. So, if the voltage drop across my device at 10A exceeds 2.5V, the device will be held at 2.5V instead and the current is reduced accordingly.

No. If the effective resistance is lower than V/I = 2.5 / 10 = 0.25 Ω then the PSU will limit the current to 10 A and the voltage will fall below 2.5 V.

Can I put my devices in series and replicate similar voltage controls for each device by using circuit elements?

This would generally be a bad idea as series-connected circuits would normally share the same current. You could do it using a "shunt regulator" around each of your loads but that would be difficult with only 2.5 V for the regulator circuit to go on.
Note that your Zener diodes are drawn backwards.
Let all current flow go through Device A if V1 < 2.5V
If V1 would exceed 2.5V at 10A, hold it constant at 2.5V instead (whatever the current that flows through)
Be able to disconnect Device A from the circuit without affecting Device B.
To power both devices you would need at least 5 V.
This sounds as though you are trying to run two different model LEDs in series. You'd get much better answers if you edit your question to explain the real problem you're trying to solve.

A: Here is something that seems to work as you require. The voltage across the variable load R2 (which tries to simulate your loads), is limited to 2.2 volts, which is the combined forward voltage of the two diodes D1 and D2, and the base-emitter junction of power transistor Q1. R1 limits current in the diodes to about 267 uA. Changing it to 10 ohms raises the maximum voltage to about 2.35 volts.


text:
Q: How to Create skeleton script in bash that takes the input from file.JSON(files represent devices) i need to create script in bash that takes the json file as input from a folder. Lets say json file looks like this:
{\"mac_address\": null, \"serial_number\": \"A-HCI1\", \"device_type\": \"STORAGE\", \"device_model\": \"NIMBLE DHCI STORAGE\", \"part_number\": \"6790\", \"extra_attributes\": [
{\"attribute_type\": \"ENTITLEMENT_ID\", \"attribute_value\": \"YIZUYYNEYSFO9ghhhgAU\"}

and then  CCS quotes the json in the event data field of the Kafka event - A valid kafka event will look like
{
    "specversion": "4.0",
    "id": "(i will be using uuid genereator for that",
    "source": "CCS",
    "type": "DEVICE_PROVISION_EVENT",
    "time": "local time",
    "data": "{\"mac_address\": null, \"serial_number\": \"ADL23231\", \"device_type\": \"DHCI_STORAGE\", \"device_model\": \"NIMBLE DHCI STORAGE\", \"part_number\": \"6320\", \"extra_attributes\": [{\"attribute_type\": \"ENTITLEMENT_ID\", \"attribute_value\": \"YIZUYYNEYSFO9ZV0LVAU\"}],\"tag_entities\": [], \"platform_customer_id\": \"a07db108sadasd33325ee95\", \"application_customer_id\": \"31187723dfd32a93178\", \"folder_name\": null}"
}

A: If you flatten the JSON into a single line, you can just input into the kafka console consumer
kafka-console-producer.sh --topic foo --bootstrap-server localhost:9092 < data.json

But from your previous questions, you should ideally stick with Python or Go based producer scripts rather than shell scripts for flexibility.


text:
Q: React server side rendering page source is not updating I'm working with server side rendering for my React Js App.showing page content and routes are working fine.but when i hit 'page source',it's not showing all content inside html.also when i navigate to another page and hit 'page source',it's not updated old html.
Any idea about this issue?
server.js
import 'babel-polyfill';
import express from 'express';
import { matchRoutes } from 'react-router-config';
import Routes from './client/Routes';
import renderer from './helpers/renderer';
import createStore from './helpers/createStore';
const app = express();

app.use(express.static('public'));
app.get('*', (req, res) => {
  const store = createStore(req);
  const promises = matchRoutes(Routes, req.path)
    .map(({ route }) => {
      return route.loadData ? route.loadData(store) : null;
    })
    .map(promise => {
      if (promise) {
        return new Promise((resolve, reject) => {
          promise.then(resolve).catch(resolve);
        });
      }
    });

  Promise.all(promises).then(() => {
    const context = {};
    const content = renderer(req, store, context);
    res.send(content);
  });
});

app.listen(3000, () => {
  console.log('Listening on prot 3000');
});

renderer.js
import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { renderRoutes } from 'react-router-config';
import serialize from 'serialize-javascript';
import { Helmet } from 'react-helmet';
import Routes from '../client/Routes';

export default (req, store, context) => {
  const content = renderToString(
    <Provider store={store}>
      <StaticRouter location={req.path} context={context}>

{renderRoutes(Routes)}

      </StaticRouter>
    </Provider>
  );

  const helmet = Helmet.renderStatic();

  return `<!doctype html>

        ${helmet.title.toString()}
        ${helmet.meta.toString()}

${content.toString()}

  `;
};

App.js
import React from 'react';
import { renderRoutes } from 'react-router-config';
import { fetchHomeSliders } from './actions/home';
const App = ({ route }) => {
  return (

      {renderRoutes(route.routes)}

  );
};

export default {
  component: App,
  loadData: ({ dispatch }) => dispatch(fetchHomeSliders())
};

Routes.js
import React from 'react';
import App from './App';
import HomePage from './components/home';
import About from './components/about';

export default [
  {
    ...App,
    routes: [
      {
        ...HomePage,
        path: '/',
        exact: true
      }
      ,
      {
        ...About,
        path: '/about-us'
      }

    ]
  }
];

fetchHomeSliders API
 export const fetchHomeSliders = () => async (dispatch, getState, api) => {
      const request = await api.get(`https://example.com/api/contents/ABOUT`);
      dispatch ({type: FETCH_HOME_SLIDERS, payload: request});
      console.log("request request",request)
      };

A: The reason why it might be happening is that on doing view page source only the server rendered page is shown in SSR website.
So anything you do on the client like add an html element or listener will be seen only it the inspect element.The inspect
element is kind of dynamic meaning that it updates itself to server as well as client side changes.So whenever you are doing anything like
show/hide a div/button, it will be shown in the inspect element. Whereas when you try to View page souce what happens is it hits the server and
whatever  HTML content the server returned it will show.
As an example you can check https://preactjs.com/. If you do View page souce in it the html content is very less and won't contain
majority of elements compared to inspect element.So here only a part of the html is sent by Server and majority of things happen on
client side.
For your case I think you need to hydrate elements rendered by server.It will ensure that the content is the same on
the server and the client and won't override it.
Something like
import React from 'react'
import {hydrate} from 'react-dom'
import {Provider} from 'react-redux'
import configureStore from './redux/configureStore'
import App from './components/app'
const state = window.__STATE__;
delete window.__STATE__;
const store = configureStore(state)

//Here we are hydrating.
hydrate(
    <Provider store={store} >
        <App />
    </Provider>,
    document.querySelector('#app')
)

Also you can check in network request if server is returning content.toString()
Hope that helps.


text:
Q: How to replace contents of div instead of append when php script is running through XMLHttprequest? Is there a way to make the div be replaced with the php echo value instead of being appended to the div as it does now with the following code?
PHP File (generator.php) :

header('Content-type: text/html; charset=utf-8');

function output($val)
{

echo $val.str_repeat(" ",5000);
sleep(2);

}

output('Begin... (counting to 10)');

for( $i = 0 ; $i < 10 ; $i++ )
{
    output($i+1);
}

output('End...');

?>

Calling HTML file:

<form id="aform">
<input name="Generate" onClick="start()" type="button" value="Generate Fresh File" />
</form>


text:
Q: How to send messages from Biztalk to MANY web services Imagine we have a Notification service build on BizTalk. Once the service receives a notification it should then send this notification to other systems. If we have had 2-3 systems we could just add a few web service references and send the message thru corresponding port. But I wonder what if there are hundred of subscribed web services to which we should send a message? What's the best way to resend a message to 100 web services?

A: As Filburt said! You would have one logical send port out of your orchestration and you would bind your orchestration to a send port group in the Admin console; so you could add or remove send ports at will. Any mapping could be performed outbound if any services need the message transformed too.

A: In agreement with Filburt + teepeeboy, and to add, if you offered push data services you would probably want control over each and every port, in order to control SLA's, Retries, possibly linked to billing, etc. You would likely need to increase the number of threads on the relevant WCF adapter and / or increase the number of Send Hosts and / or Clustered Servers for scalability.
You might also consider using an asynchronous adapter like MSMQ or MQSeries, as the chances that one of more of your 100 subscribers is down becomes higher. w.r.t. "ACK" replies, by restricting access on the queue and making the queue transactional, you could 'prove' that your subscriber had transactionally removed the message off the queue.


text:
Q: Deleting a std::function in the middle of invocation Is it undefined behavior to be destroying/deleting a std::function while in the middle of invocation?
class Event {
  public:
    Event(std::function<void()> f) : func(std::move(f)) {}
    ~Event() {}
    std::function<void()> func;
};

int main()
{
    std::vector<Event> events;
    auto func = [&]() {
      events.pop_back();
      std::cout << "event" << std::endl;
      // do more work
    };

    events.emplace_back(std::move(func));
    events[0].func();

    return 0;
}

A: This is undefined by [res.on.objects]p2:

If an object of a standard library type is accessed, and the beginning
  of the object's lifetime does not happen before the access, or the
  access does not happen before the end of the object's lifetime, the
  behavior is undefined unless otherwise specified.

The "access" in this case consists of the call to the function call operator of the std::function. The std::function object's lifetime ended at the pop_back() call, in the middle of the access. Therefore, the access does not happen before the end of the object's lifetime, and the behavior is undefined.

A: Your code (the bit you're asking about, i.e. the destructing of the object inside a member function) is roughly equivalent to
struct A
{
  void f() { delete this; }
}

int main()
{
  A* a = new A;
  a.f();
}

This does actually work. Refcounted resources could do something similar when the refcount reaches zero in their unref function.
Note you might want to rethink tying the event list and events themselves together like this. An event shouldn't know about its environment (the event queue).


text:
Q: \citeauthor with LNCS template raises undefined control sequence error I am writing a conference paper in which I am to use the LNCS template. The problem is I cannot use \citeauthor to refer to the authors of a certain paper, and it is tedious and pointless to manually write and maintain the (sometimes foreign) names of researchers especially in the Related Work section when an automatic mechanism already exists..
On top of that, in the template (file splncs04.bst) it is explicitly stated that:

Note that this file will not work for author-year style citations.

Is there a way to get a similar functionality to \citeauthor without risking a rejection of the paper?

A: I think your can use this splncs04nat.bst from here!
The resulting splncs04nat.bst emulates the splncs04.bst from Springer; however, splncs04nat.bst is natbib compatible.
Finally, \citet{xxx} will get xxx et al. [number].


text:
Q: Converting a Lyx document to MS Word I've made several attempts of converting a Lyx document to MS Word , or RTF, and failed. I'm working with a moderately complex document, involving external includes ( Java code, Child documents ), formulas and images.
I've tried

*

*exporting to Latex and then using tex4ht but the OpenOffice file is not created ( no context.xml inside the odt );

*exporting to HTML and importing in OpenOffice Writer;

*exporting to PDF and importing using Nitro PDF;

I'm now manually converting the Nitro PDF output, but it fares rather badly on formulas and code listings.
What other options are there?

A: Probably a little late to the party, but since it took me a long while to complete the task even as of today, I felt like it's worth leaving a trace.
Here's the procedure that got me home. It's a little cumbersome, yet it allowed me not to replace all special characters in my Italian document, which was were latex2rtf was failing.

*

*From Lyx, export your file in Latex(Luatex, didn't try the other options)

*Run htlatex [filename.tex] (a)

*Open the resulting file with Firefox, it should show all of your formattings rather well

*Select All-->Copy-->Paste into LibreOffice

I had to manually reinsert the images (b), but it felt like a gift when compared with all other methods I tried.
Sorry I didn't test further refinements, but had to complete everything to comply with a tight deadline and hadn't had time to test afterwards. Will edit if able to.
(a) I suspect I got the package by installing the gigantic latex2rtf application, but it should be an easy find.
(b) On that matter I suspect the Lyx export of images into Latex would have worked if the images didn't contain spaces in their filenames, but can't confirm yet. Might check and edit this little bit.
Edit: checked (b), and I could not make it work. The spaces trick applies to latex2rtf.

A: Have you tried LyX-> LaTeX -> RTF-> Word?
Here are some additional suggestions, some paid options: http://wiki.lyx.org/FAQ/Compatibility#toc2

A: Install pandoc and add it to the path in LyX's preference configuration.
Then reconfigure LyX and restart LyX.
After restarting LyX, you will see a new export option like "export to office XML (Word)".
For my experience, most math symbols can be easily converted into MS Word formula. Some are not if there is one symbol not recognized.
Good luck, the feature is available at least with LyX 2.3.4.

A: Convert to LaTeX then use tex2word. The conversion isn't perfect, but not bad, leaving a little tidying up to do at the end. Other latex -> word converters are listed at http://www.tug.org/utilities/texconv/textopc.html

A: Export to PDF from LyX. Adobe Acrobat Pro X has the option to save PDF as a MS Word document. If this version of Adobe is available to you, I highly recommend this method.

A: So I just tried this
Exported from lyx to html(doc)
then open the exported file in Libreoffice writer, voila it works almost perfectly
I understand this answer is 8 years late in coming, but was just questing for it my self and hope it helps others who may need to know / want to know

A: Simplest way - sort of two-clicks - working with recent Word versions:

*

*Render your LyX document as PDF (e.g. Ctrl-R)

*Open the PDF in Word - yes this is readily possible in modern Word versions (Word 2016)