text:
Q: Python Animation of projectile giving straight line The goal is to animate/simulate a sprinkler. The basic idea is to create multiple droplets at an instance, each exiting the sprinkler at a different angle.
However, instead of having a point that moves along, I'm getting a straight, static line. I've tried the same code with only one or 2 drops/points, but I still get the same straight line. At first I thought it was because I included drag into the animation (in previous trials I got strange/unexpected results when I included the drag, so I was hoping it was the same problem)
Below is the code I wrote.
EDIT: dragx and dragy are no longer set to the same values. The initial velocities are calculated outside the update function.
Drag forces are recalculated at each index increase, since the drag depends on the velocity.
The imports are also now included.
I have also now tried to use a scatter plot instead of a line, which gave me a single dot at the origin. I reverted back to the line since then
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as animation
from math import sin, cos
import matplotlib.axes as axess

#pressure in system
def pressure(pump):
    return 10.197*pump*10**5/998.2

#Initial velocity based on the pressure of the system
def vinit(init_head):
    return (2*9.81*init_head)**0.5
# Number of droplets per iteration
n = 2
v0 = vinit(pressure(5.8))
cd = 0.5                                             #drag coefficient of a sphere;
rho = 1.225                                          #density of air;                 kg/m^3

fps = 20
runtime = 1*20
numframes = fps*runtime
time = np.linspace(0,runtime,numframes)

#Initialize droplets

droplets = np.zeros(numframes, dtype = [('position', float, 2),
                                ('velocity', float, 2),
                                ('force', float, 2),
                                ('angle',float, 1),
                                ('radius', float, 1)])

droplets['radius'] = np.random.normal(0.0045, 0.001, numframes)
A = 4*np.pi*droplets['radius']**2
mass = ((4*np.pi*droplets['radius']**3)/3)*1000     #mass of waterdroplet
drag = np.zeros(numframes,dtype = [('dragx', float, 1),('dragy', float, 1)])

rads = np.radians(np.random.normal(37,1,numframes))
droplets['angle'] = rads
droplets['force'][:,1] = -9.8*mass

#Initialize velocity
for i in range(0, numframes):
    droplets['velocity'][i,0] = v0*cos(droplets['angle'][i])
    droplets['velocity'][i,1] = v0*sin(droplets['angle'][i])

#Initialize the drag
drag['dragx'] = -0.5*rho*cd*A*droplets['velocity'][:,0]
drag['dragy'] = -0.5*rho*cd*A*droplets['velocity'][:,1]

droplets['position'][:,0] = 0

#Initialize the figure
fig,ax = plt.subplots()
axess.Axes.set_frame_on(ax,True)
ax.autoscale(True)
ax.set_xlim(0)
ax.set_ylim(0)

line = ax.plot(droplets['position'][0, 0], droplets['position'][0, 1],'b.')[0]
line = ax.plot(droplets['position'][:, 0], droplets['position'][:, 1],'b.')[0]
xdata = [droplets['position'][0, 0]]
ydata = [droplets['position'][0, 1]]
ln = plt.plot([],[],'b')[0]

def initfunc():
    droplets['position'][0,:] = 0
    ln.set_data(droplets['position'][0, 0], droplets['position'][0, 1])
    return ln

def update(framenum):
    index = framenum
    cd = 0.5                                          #drag coefficient of a sphere;
    rho = 1.225                                       #density of air;                 kg/m^3
    A = 4*np.pi*droplets['radius']**2                 #surface area of droplet;        m^2
    mass = ((4*np.pi*droplets['radius']**3)/3)*1000   #mass of waterdroplet

    #Update the drag force on the droplet
    drag['dragx'] = -0.5*rho*cd*A*droplets['velocity'][:,0]
    drag['dragy'] = -0.5*rho*cd*A*droplets['velocity'][:,1]

    droplets['force'][index,0] += drag['dragx'][index]
    droplets['force'][index,1] += drag['dragy'][index]
    #droplets['position'][0] = [0,0]
    droplets['velocity'][index,0] = droplets['velocity'][index,0] + (droplets['force'][index,0]/mass[index])*index
    droplets['velocity'][index,1] = droplets['velocity'][index,1] + (droplets['force'][index,1]/mass[index])*index
    droplets['position'][index,0] = droplets['position'][index,0] + (droplets['velocity'][index,0])*index
    droplets['position'][index,1] = droplets['position'][index,1] + (droplets['velocity'][index,1])*index

    xdata.append(droplets['position'][index,0])
    ydata.append(droplets['position'][index,1])
    ln.set_data(xdata,ydata)

    line.set_data(droplets['position'][:,0], droplets['position'][:,1])

    return ln

sprink = animation.FuncAnimation(fig, update,init_func = initfunc,interval= 200,  frames = numframes)
plt.show()

sprink.save('Sprinkler.mp4', fps = fps)

A: In addition to the mistakes pointed out by @JohanC, you are using the surface area (4 * pi * r^2) instead of the cross-sectional area (pi * r^2) of the water droplets (approximated as spheres). Furthermore, you appear to be trying to using equations of motion which assume a vacuum, those equations break down when air resistance or other nonconstant forces are added.
I would recommend you read this answer for a more complete explanation of calculating ballistic projectile motion with air resistance, but here is a simplified version.
Calculating the position of a particle moving through a medium is essentially solving a first order ODE, there are many ways to solve such an equation numerically. The simplest (albeit least robust) way is to break the problem into small segments and approximate the change from the current point to the next point. For this problem such a method works quite well, assuming you use a small enough time step.
In your case we could do something like this
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import animation
import numpy as np
from math import sin, cos

g = 9.81
rho = 1.225
v0 = 50.0    # This can be initialized as desired, I chose 50 m/s for demonstration
C = 0.5

nframes = 100
ndrops = 10
tend = 8.0
time = np.linspace(0.1, tend, nframes)   # Runtime of 4s chosen arbitrarily
dt = time[1] - time[0]                    # change in time between steps
maxs = [0.0, 0.0]
r = [0.001, 0.0045]                       # This stores the range of radii to be used

# I have implemented a class to store the drops for brevity
class drop:

    def __init__(self, pos, vel, r):
        self.pos = pos
        self.vel = vel
        self.r = r

class sprinkler:
# I implemented this as a class to simplify updating the scatter plot
    def __init__(self):
        self.fig, self.ax = plt.subplots()
        self.drops = [None]*ndrops
        self.maxt = 0.0
        ## This step is simply to figure out how far the water drops can travel
        ## in order to set the bounds of the plot accordingly
        angles = np.linspace(0, np.pi/2, 90)    # We only need to sample from 0 to pi/2
        for angle in angles:
            m = [drop([0.0, 0.1], [v0*cos(angle), v0*sin(angle)], 0.001),
                 drop([0.0, 0.1], [v0*cos(angle), v0*sin(angle)], 0.0045)]
            for d in m:
                t = 0.0
                coef = - 0.5*C*np.pi*d.r**2*rho
                mass = 4/3*np.pi*d.r**3*1000
                while d.pos[1] > 0:
                    a = np.power(d.vel, 2) * coef * np.sign(d.vel)/mass
                    a[1] -= g
                    d.pos += (d.vel + a * dt) * dt
                    d.vel += a * dt
                    t += dt
                    if d.pos[1] > maxs[1]:
                        maxs[1] = d.pos[1]
                    if d.pos[0] > maxs[0]:
                        maxs[0] = d.pos[0]
                    if d.pos[1] < 0.0:
                        if t > self.maxt:
                            self.maxt = t
                        break
        for ii in range(ndrops):    # Make some randomly distributed water drops
            self.drops[ii] = drop([0.0, 0.0], [cos(np.random.random()*np.pi)*v0,
                             sin(np.random.random()*np.pi)*v0],
                             np.random.random()*(r[1]-r[0]) + r[0])

        anim = animation.FuncAnimation(self.fig, self.update, init_func=self.setup,
                                       interval=200, frames=nframes)
        anim.save('Sprinkler.gif', fps = 20, writer='imagemagick')

    def setup(self):
        self.scat = self.ax.scatter([d.pos[0] for d in self.drops],
                               [d.pos[1] for d in self.drops], marker='.', color='k')
        self.ax.set_xlim([-maxs[0]*1.15, maxs[0]*1.15])
        self.ax.set_ylim([0, maxs[1]*1.15])

        return self.scat,

    def update(self,frame):  # Use set_offsets to move the water drops
        self.step()          # Advance to the next 'step'
        self.scat.set_offsets(np.stack([[d.pos[0] for d in self.drops],
                                       [d.pos[1] for d in self.drops]], 1))

        return self.scat,

    def step(self):
        for ii in range(ndrops):
            coef = - 0.5*C*np.pi*self.drops[ii].r**2*rho    # Aggregated coefficient
            mass = 4/3*np.pi*self.drops[ii].r**3*1000
            a = np.power(self.drops[ii].vel, 2)*coef * np.sign(self.drops[ii].vel)/mass
            a[1] -= g
            # Approximate how much the position and velocity would change if we assume
            # a(t) does not change between t and t+dt
            self.drops[ii].pos += np.array(self.drops[ii].vel) * dt + 0.5 * a * dt**2
            self.drops[ii].vel += a * dt
            if self.drops[ii].pos[1] < 0.0:     # Check if the drop has hit the ground
                self.drops[ii].pos[1] = 0.0
                self.drops[ii].vel = [0.0, 0.0]

sprinkler()

This may not produce exactly what you are after but it correctly models the motion of the water droplets.

Implementing the drops as a class and storing them in a list as I have makes it easy to create more droplets to simulate many 'iterations' of the above by simply modifying the update function (create method added for simplicity):
    def update(self,frame):  # Use set_offsets to move the water drops
        # Create between 0 and ndrops new drops, but only until tend-maxt
        if time[frame] < tend - self.maxt*1.1:
            self.create(np.random.randint(0, ndrops))
        self.step()          # Advance to the next 'step'
        self.scat.set_offsets(np.stack([[d.pos[0] for d in self.drops],
                                        [d.pos[1] for d in self.drops]], 1))

        return self.scat,

    def create(self, i):
        for ii in range(i):
            self.drops.append(drop([0.0, 0.0], [cos(np.random.random()*np.pi)*v0,
                             sin(np.random.random()*np.pi)*v0],
                             np.random.random()*(r[1]-r[0]) + r[0]))

 Edit - The entire code to produce the second animation
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import animation
import numpy as np
from math import sin, cos

g = 9.81
rho = 1.225
v0 = 50.0    # This can be initialized as desired, I chose 50 m/s for demonstration
C = 0.5

nframes = 100
ndrops = 10
tend = 8.0
time = np.linspace(0.1, tend, nframes)   # Runtime of 4s chosen arbitrarily
dt = time[1] - time[0]                    # change in time between steps
maxs = [0.0, 0.0]
r = [0.001, 0.0045]                       # This stores the range of radii to be used

# I have implemented a class to store the drops for brevity
class drop:

    def __init__(self, pos, vel, r):
        self.pos = pos
        self.vel = vel
        self.r = r

class sprinkler:
# I implemented this as a class to simplify updating the scatter plot
    def __init__(self):
        self.fig, self.ax = plt.subplots()
        self.drops = [None]*ndrops
        self.maxt = 0.0
        ## This step is simply to figure out how far the water drops can travel
        ## in order to set the bounds of the plot accordingly
        angles = np.linspace(0, np.pi/2, 90)    # We only need to sample from 0 to pi/2
        for angle in angles:
            m = [drop([0.0, 0.1], [v0*cos(angle), v0*sin(angle)], 0.001),
                 drop([0.0, 0.1], [v0*cos(angle), v0*sin(angle)], 0.0045)]
            for d in m:
                t = 0.0
                coef = - 0.5*C*np.pi*d.r**2*rho
                mass = 4/3*np.pi*d.r**3*1000
                while d.pos[1] > 0:
                    a = np.power(d.vel, 2) * coef * np.sign(d.vel)/mass
                    a[1] -= g
                    d.pos += (d.vel + a * dt) * dt
                    d.vel += a * dt
                    t += dt
                    if d.pos[1] > maxs[1]:
                        maxs[1] = d.pos[1]
                    if d.pos[0] > maxs[0]:
                        maxs[0] = d.pos[0]
                    if d.pos[1] < 0.0:
                        if t > self.maxt:
                            self.maxt = t
                        break
        for ii in range(ndrops):    # Make some randomly distributed water drops
            self.drops[ii] = drop([0.0, 0.0], [cos(np.random.random()*np.pi)*v0,
                             sin(np.random.random()*np.pi)*v0],
                             np.random.random()*(r[1]-r[0]) + r[0])

        anim = animation.FuncAnimation(self.fig, self.update, init_func=self.setup,
                                       interval=200, frames=nframes)
        anim.save('Sprinkler.gif', fps = 20, writer='imagemagick')

    def setup(self):
        self.scat = self.ax.scatter([d.pos[0] for d in self.drops],
                                    [d.pos[1] for d in self.drops], marker='.', color='k')
        self.ax.set_xlim([-maxs[0]*1.15, maxs[0]*1.15])
        self.ax.set_ylim([0, maxs[1]*1.15])

        return self.scat,

    def update(self,frame):  # Use set_offsets to move the water drops
        # Create between 0 and ndrops new drops, but only until tend-maxt
        if time[frame] < tend - self.maxt*1.1:
            self.create(np.random.randint(0, ndrops))
        self.step()          # Advance to the next 'step'
        self.scat.set_offsets(np.stack([[d.pos[0] for d in self.drops],
                                        [d.pos[1] for d in self.drops]], 1))

        return self.scat,

    def create(self, i):
        for ii in range(i):
            self.drops.append(drop([0.0, 0.0], [cos(np.random.random()*np.pi)*v0,
                             sin(np.random.random()*np.pi)*v0],
                             np.random.random()*(r[1]-r[0]) + r[0]))
    def step(self):
        for ii in range(len(self.drops)):
            coef = - 0.5*C*np.pi*self.drops[ii].r**2*rho    # Aggregated coefficient
            mass = 4/3*np.pi*self.drops[ii].r**3*1000
            a = np.power(self.drops[ii].vel, 2) * coef * np.sign(self.drops[ii].vel)/mass
            a[1] -= g
            # Approximate how much the position and velocity would change if we assume
            # a(t) does not change between t and t+dt
            self.drops[ii].pos += np.array(self.drops[ii].vel) * dt + 0.5 * a * dt**2
            self.drops[ii].vel += a * dt
            if self.drops[ii].pos[1] < 0.0:     # Check if the drop has hit the ground
                self.drops[ii].pos[1] = 0.0
                self.drops[ii].vel = [0.0, 0.0]

sprinkler()


text:
Q: assetsLibrary a simple bug? I am really lost .
why i get NSLog twice for each UIImage ?
 //------ get the images from the camera roll ----------
    assets=[[NSMutableArray alloc]init];
    NSMutableArray *cameraRollPictures=[[NSMutableArray alloc]init];
    ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
    [assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop)
    {

        NSInteger numberOfAssets = [group numberOfAssets];
        NSLog(@"NUM OF IMAGES:%d",numberOfAssets);
        if (numberOfAssets > 0)
        {

            for (int i = 0; i <= numberOfAssets-1; i++)
            {

                [group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:i] options:0 usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop)
                 {
                    UIImage *thumbnail = [UIImage imageWithCGImage:[result thumbnail]];
                    [assets addObject:thumbnail];
                     NSLog(@"theObject!!!! -- (%d) %@",i,thumbnail);

            //******* for each i its here twice !!   ********

                }];
            }
        }

A: For some reason, enumerateAssetsAtIndexes (and enumerateAssetsUsingBlock) do an additional invocation of the block  with result == nil and index == NSNotFound at the end of the enumeration. This becomes obvious if you change the NSLog() to
NSLog(@"i=%d, index=%ld, result=%@", i, (unsigned long)index, result);

Then you will get the output
NUM OF IMAGES:2
i=0, index=0, result=ALAsset - Type:Photo, URLs:assets-library://asset/asset.PNG?id=...
i=0, index=2147483647, result=(null)
i=1, index=1, result=ALAsset - Type:Photo, URLs:assets-library://asset/asset.PNG?id=...
i=1, index=2147483647, result=(null)

Therefore you have to check the value of result and ignore a nil value:
for (int i = 0; i <= numberOfAssets-1; i++) {
     [group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:i] options:0 usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop)
      {
          if (result != nil) {
              UIImage *thumbnail = [UIImage imageWithCGImage:[result thumbnail]];
              [assets addObject:thumbnail];
          }
      }];
}

Note that you can simplify the enumeration to
[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
     if (result != nil) {
         UIImage *thumbnail = [UIImage imageWithCGImage:[result thumbnail]];
         [assets addObject:thumbnail];
     }
}];

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting an error converting from varchar to numeric I made a historical table along with a trigger function built in the reference table. Is based on possible name changes for an user and as well recording down the date.
My trigger built:

Target table:

The trigger function pulls the names off the table.

But I'm getting error converting data type. All my data that I'm updating are of VARCHAR type. Where am I missing?

A: Change the INSERT..VALUES statement to INSERT..SELECT and set aliases for all the columns. Make sure the aliases match the every column in the target table (defaulting all NOT NULL columns), and they are in the same order as they are declared.
Note that the SELECT statement uses the patientLastNameChange table, because the MAX() without a GROUP BY ensures only one row is returned.
I recommend to use COALESCE to set the MAX() result to 0 if it returns NULL. Then simply add 1 to increment the lastNameChangeID. I think this is more readable.
CREATE TRIGGER patientLastNameChangeTrigger
ON patient
AFTER UPDATE
AS
BEGIN
    DECLARE @oldLastName VARCHAR(255) = (SELECT pt_lastName FROM DELETED);
    DECLARE @newLastName VARCHAR(255) = (SELECT pt_lastName FROM INSERTED);

    IF @oldLastName <> @newLastName
        INSERT INTO dbo.patientLastNameChange (lastnameChangeID, patientID, oldLastName, newLastName, datechanged)
        SELECT
        COALESCE(MAX(plnc.lastnameChangeID),0)+1 AS lastnameChangeID,
        (SELECT patientID FROM INSERTED) AS patientID,
        @oldLastName AS oldLastName,
        @newLastName AS newLastName,
        GETDATE() AS datechanged
        FROM patientLastNameChange plnc;
END;


text:
Q: Randomise next word with no duplicate in Hangman game using JavaScript I have made a Hangman game using JavaScript. It works just fine, but I've found that every time I click on 'New Word' to start a new game, it's completely random (which is good), but it doesn't take into account whether or not the new word has already occurred/been played. So you get a lot of duplicates from previous words.
I have made about 50 words/answers that can appear. I just want it so that every time I click on 'New Word', it generates a new word (from my choices) at random, and doesn't ever duplicate the same word again, unless all other options/words have been played already.
For some reason this text box isn't putting all my code into a block, so to make things easier to read, this is a link to my code in Github. I've attached all files but I'm pretty sure you only need to look at my JavaScript code:
HTML:
https://raw.githubusercontent.com/kaw31/hangman/master/hangman.html
CSS: (I've commented out a bit of code from a previous version so just ignore that);
https://raw.githubusercontent.com/kaw31/hangman/master/css/style.css
JavaScript:
https://raw.githubusercontent.com/kaw31/hangman/master/js/script.js
Any help is much appreciated.

A: There are a couple of logic errors in your code:

*

*The list of your categories is set every time you run play function - and for every game it's the same (that's why it's possible to retrieve a word that was retrieved in previous games), while it should be set once for given browser refresh. Therefore you should move categories to the top (var categories = [list of your categories]) so that it's persistent.

*You're not removing the chosen word after it has been retrieved from the list of your words - that's why it'll still be available to be retrieved again even with above fix. To do so, you first should get the index of category and word and simply remove it:

var category_index = Math.floor(Math.random() * categories.length);
var word_index = Math.floor(Math.random() * categories[category_index].length;

categories[category_index] = categories[category_index].splice(word_index, 1);

Of course at that point, you'll also have to remove hints and cater for the situation when list of words is empty (both - for each category, and empty at all)
Personally, I'd change how your words are stored, instead of using multiple arrays, use object as such:
var categories = [{
    title: "Sport Teams",
    words: [{
        word: "ARSENAL",
        hint: "Thierry Henry",
        }, ...
    ]}, ...
]

so, when retrieving a word, you're retrieving all information regarding it - at that point the list of words becomes more manageable and manipulation becomes a bit easier.


text:
Q: Equations including ``tikzpicture`` With the following codes
\documentclass[12pt,a4paper]{report}
\usepackage{amsfonts,amsmath,amssymb,graphicx,amsthm,xcolor,tikz}
\usetikzlibrary{calc,matrix}

        \begin{document}
\begin{tikzpicture}[
strip/.style = {
    draw=#1,%color
    line width=1em, opacity=0.2,
    shorten <=-2mm,shorten >=-2mm,
                            },
                    ]
\matrix (mtrx)  [matrix of math nodes,
                 column sep=1em,
                 nodes={text height=1ex,text width=2ex}]
{
|[red]|+
    & |[red]|+
          & \color{red}+\color{blue}-
                & |[blue]|-
                      & |[blue]|-   \\[3.3mm,between origins]
a_1 & b_1 & c_1 & a_1 & a_2         \\
a_2 & b_2 & c_2 & a_2 & b_2         \\
a_3 & b_3 & c_3 & a_3 & b_3         \\
};
\draw[thick] (mtrx-2-1.north) -| (mtrx-4-1.south west)
                              -- (mtrx-4-1.south);
\draw[thick] (mtrx-2-3.north) -| (mtrx-4-3.south east)
                              -- (mtrx-4-3.south);
\path[draw,strip=blue]
    (mtrx-4-1.center) edge (mtrx-2-3.center)
    (mtrx-4-2.center) edge (mtrx-2-4.center)
    (mtrx-4-3.center)  --  (mtrx-2-5.center);
\path[draw,strip=red]
    (mtrx-2-1.center) edge (mtrx-4-3.center)
    (mtrx-2-2.center) edge (mtrx-4-4.center)
    (mtrx-2-3.center)  --  (mtrx-4-5.center);
\end{tikzpicture}
    \end{document}

I get

Howerver I want to replace [] by || and chage the place of the minus -. Also I want to add them in equations as the picture shows

I tried with \begin{align*} .. & = \\ &= \end{align*} but it does not work.

A: The brackets are drawn manually, so you just need to modify (simplify) how they are drawn. E.g. \draw[thick]  (mtrx-4-1.south west) -- (mtrx-2-1.north west); -- a single line from the bottom left corner of one cell, to the top left of another cell.
To move the minus signs, literally just move the minus signs in the code to a new row at the end of the matrix.
Note also the addition of the baseline key, as specified in use of tikzpicture matrix in align or gather environment, do get the proper vertical alignment.
Finally, the align* environment clashes with a TikZ matrix because for both, the & character has special meaning. To fix that, you can tell TikZ to use something else as the column separator with ampersand replacement. The common thing to use is \&, but you could use other macros as well. See that in the example below I added ampersand replacement=\& to the \matrix options, and I used \& inside the matrix, for example a_1 \& b_1 \& c_1 \& a_1 \& a_2 \\

\documentclass[12pt,a4paper]{report}
\usepackage{amsfonts,amsmath,amssymb,amsthm,tikz}
\usetikzlibrary{calc,matrix}

\begin{document}
\begin{align*}
D &=
\begin{tikzpicture}[
baseline=-\the\dimexpr\fontdimen22\textfont2\relax,
strip/.style = {
    draw=#1,%color
    line width=1em, opacity=0.2,
    shorten <=-2mm,shorten >=-2mm,
                            },
                    ]
\matrix (mtrx)  [matrix of math nodes,
                 column sep=1em,
                 nodes={text height=1ex,text width=2ex},
                 ampersand replacement=\&]
{
|[red]|+  \& |[red]|+  \& |[red]| +
 \\[3.3mm,between origins]
a_1 \& b_1 \& c_1 \& a_1 \& a_2         \\
a_2 \& b_2 \& c_2 \& a_2 \& b_2         \\
a_3 \& b_3 \& c_3 \& a_3 \& b_3         \\
|[blue]|- \& |[blue]|- \& |[blue]|- \\
};
\draw[thick]  (mtrx-4-1.south west) -- (mtrx-2-1.north west);
\draw[thick] (mtrx-4-3.south east)  -- (mtrx-2-3.north east);
\path[draw,strip=blue]
    (mtrx-4-1.center) edge (mtrx-2-3.center)
    (mtrx-4-2.center) edge (mtrx-2-4.center)
    (mtrx-4-3.center)  --  (mtrx-2-5.center);
\path[draw,strip=red]
    (mtrx-2-1.center) edge (mtrx-4-3.center)
    (mtrx-2-2.center) edge (mtrx-4-4.center)
    (mtrx-2-3.center)  --  (mtrx-4-5.center);
\end{tikzpicture} \\
 &= a+b+c\dots
\end{align*}
\end{document}


text:
Q: DataFrame .head() doesn't work when calling it from a function When calling this function in Jupyter's Notebook, it prints nothing:
def printess(request):
        table_AltModels[request].head(10)

where in this code table_AltModels[request] is a valid dataframe.
I would like my function to show the dataframe in a table like here:
table
Thanks

A: Either use a return or a print
return table_AltModels[request].head(10)

or
print table_AltModels[request].head(10)

or
from IPython.display import display
display(table_AltModels[request].head(10))


text:
Q: Bitcoin PHP JSONRPC permission denied After reading https://en.bitcoin.it/wiki/API_reference_(JSON-RPC)#PHP and also other tutorials, i haven't gotten it to work. All the JSON RPC libraries i use return the same error:

4.81.94:8332/): failed to open stream: Permission denied in /var/www/html/v2/jsonRPCClient.php on line 132

I also tried easybitcoin.php found on Github that one shows nothing but a blank page.
HOWEVER, when i run the command in SSH, it works perfectly.

bitcoin-cli getinfo

works in SSH and also

php bt.php

also works but when i run this in browser like http://ipaddress/bt.php all i get is a blank page(Using easybitcoin.php) or Permission Denied(Using JsonRPC)
Any ideas?

A: Are you using your username and password define int the bitcoin.conf file that should resolve your problem


text:
Q: Model.Finder Deperecated Play! 2.4 I am building an application using the latest version of Play!. When defining a Finder( as in Model.Finder) my IDE gives me a warning Finder is deprecated. I can't find any information in the documentation about Model.Finder being deprecated of any alternative to using it. Has anyone experienced a similar issue and know of an alternative?

A: Use Model.Finder<T> like:
public static Finder<Long, Foo> find = new Finder<>(Foo.class);

instead of
public static Finder<Long, Foo> find = new Finder<>(Long.class, Foo.class);

A: According to github Model.Finder is not deprecated, but one of its constructors:
/**
 * @deprecated
 */
public Finder(Class<I> idType, Class<T> type) {
  super(null, type);
}

Make sure you use correct constructor, pointed out by @biesior:
public static Finder<Long, Foo> find = new Finder<>(Foo.class);

A: Try This
 public static Finder<Long, Foo> find = new Finder<>(Foo.class);


text:
Q: Memory leak in tomcat 6.0.29 with grails 1.3.7 I am using Tomcat 6.0.29 to deploy my production war of Grails 1.3.7 on windows and linux machine.I haven't get any issue during application development,But when i deploy war and start/stop application through tomcat manager, i got below stacktrace in tomcat catalina log file.
May 17, 2011 7:43:21 PM org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc
SEVERE: The web application [/AppName] registered the JBDC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
May 17, 2011 7:43:21 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/AppName] appears to have started a thread named [MySQL Statement Cancellation Timer] but has failed to stop it. This is very likely to create a memory leak.
May 17, 2011 7:43:21 PM org.apache.catalina.loader.WebappClassLoader clearThreadLocalMap
SEVERE: The web application [/AppName] created a ThreadLocal with key of type [null] (value [org.codehaus.groovy.grails.orm.hibernate.support.HibernatePersistenceContextInterceptor$1@87b2c8]) and a value of type [java.lang.Boolean] (value [false]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak.
May 17, 2011 7:43:21 PM org.apache.catalina.loader.WebappClassLoader clearThreadLocalMap
SEVERE: The web application [/AppName] created a ThreadLocal with key of type [null] (value [org.codehaus.groovy.grails.orm.hibernate.support.HibernatePersistenceContextInterceptor$2@ea95e0]) and a value of type [java.lang.Integer] (value [0]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak.
May 17, 2011 7:43:21 PM org.apache.catalina.loader.WebappClassLoader clearThreadLocalMap
SEVERE: The web application [/AppName] created a ThreadLocal with key of type [null] (value [org.codehaus.groovy.grails.orm.hibernate.support.HibernatePersistenceContextInterceptor$1@87b2c8]) and a value of type [java.lang.Boolean] (value [false]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak.
May 17, 2011 7:43:21 PM org.apache.catalina.loader.WebappClassLoader clearThreadLocalMap
SEVERE: The web application [/AppName] created a ThreadLocal with key of type [null] (value [org.codehaus.groovy.grails.orm.hibernate.support.HibernatePersistenceContextInterceptor$2@ea95e0]) and a value of type [java.lang.Integer] (value [0]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak.
May 17, 2011 7:43:21 PM org.apache.catalina.loader.WebappClassLoader clearThreadLocalMap
SEVERE: The web application [/AppName] created a ThreadLocal with key of type [null] (value [org.codehaus.groovy.grails.commons.spring.ReloadAwareAutowireCapableBeanFactory$2@1283b68]) and a value of type [java.lang.Boolean] (value [false]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak.
May 17, 2011 7:43:56 PM org.apache.catalina.loader.WebappClassLoader loadClass
INFO: Illegal access: this web application instance has been stopped already.  Could not load com.mysql.jdbc.SQLError.  The eventual following stack trace is caused by an error thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access, and has no functional impact.

Thank you in advance for your answers!

A: This is apparently a recognized problem:
ReloadAwareAutowireCapableBeanFactory - Memory leak
and will be corrected in next version:
tomcat threadlocal memory leak
In the last link, they said that will be fixed in 1.4 but that release was merged with 2.0:
Grails 1.4 is now Grails 2.0 . 2.0 M1 will be released at the end of July .


text:
Q: How should I optimize my RecyclerAdapter (Android) to maximize efficiency of information retrieval in my app's data feed? I was wondering if there were a set of standards or best practices for displaying information in lists for mobile applications (specifically Android applications that utilize RecyclerViews and custom RecyclerAdapters). I would be especially interested in hearing about this from Android developers who currently work or have worked at professional development agencies. I thought I would post this here as it seems a little to general for SO.
For example, is there a list of quality standards that one goes through before deciding  that yes, the way I retrieve and display information in my app's main data feed is satisfactory enough for a production build?
In particular, it would beneficial if your answer addressed the following with examples:

*

*Is data cached in the local datastore for offline viewing?

*Are server queries sufficiently separated from business logic?

*Do we extend our layout with a custom LinearLayout Manager so that images are loaded before they are seen by the user?

*Have we implemented an OnScrollListener of some kind to load additional information once the user has scrolled through say 20 adapter items so that we aren't immediately bogging down performance by loading everything all at once?

*Etc, etc.

The question is fairly open-ended but at the same time, I suspect there is a lot of convergence in terms of what a good feed looks like. It would be nice to know which methods, libraries, etc. you use for each of the above considerations, and when you have decided that your feed is sufficiently fast and stable for use in production.
As an example, I've included a fragment and associated adapter to show you just how probably bad the feed is in one of my open-source apps. Given that I have not worked at an Android agency, I'm really not sure how to compare what I've produced with what is typically seen in professional production-grade applications:
FeedFragment: https://github.com/santafebound/yeetclub-android/blob/master/app/src/main/java/com/yeetclub/android/fragment/FeedFragment.java
FeedAdapter: https://github.com/santafebound/yeetclub-android/blob/master/app/src/main/java/com/yeetclub/android/adapter/FeedAdapter.java
You don't have to look at these, but a general list of things to be aware of and to optimize for RecyclerViews and their adapters would probably be of great benefit to Android developers in general. Thanks in advance for your input. Cheers!


text:
Q: Shared objects between windows Javascript I have an application which open several windows (with javascript) in the same domain.
I would like to share some javascript objects between these windows (an object which contains some configurations for example).
Is it possible to do this in javascript and how to do this ?
Thanks.

A: There are 2 possibilities: local storage and session storage
The session storage stores value for duration of the session, the value gets deleted when browser is closed and re-opened.
// Store value
sessionStorage.setItem('key', 'value');
//or
sessionStorage['key'] = value;
// Retrieve value
alert(sessionStorage.getItem('key'));

The local storage stores value beyond the duration of the session, the value can be retrievedeven after closing and re-opening the browser.
// Store value
localStorage.setItem('key', 'value');
//or
localStorage['key'] = value;

// Retrieve value
alert(localStorage.getItem('key'));

A: Use localStorage along with JSON to store your objects as strings:
Setting:
window.localStorage.setItem('yourKey', JSON.stringify(yourObject));

Getting:
var yourObject = JSON.parse(window.localStorage.getItem('yourKey'));

the localStorage data will be shared across all of your pages as long as they exist in the same domain.

A: If you used window.open() to create the second window, window.opener in the second window might give you access to the first window. See MDN.


text:
Q: How to create a data frame using two unequal length of lists I have two lists like below:-
column1= [30, 40, 50, 60,90,20,30,20,30]
column2= ['bat', 'ball','tent']

I want to create a dataframe using two lists such that the values of column2 have to equally repated to create a data frame. I tried to implement it but I am getting an output like below:-
import pandas as pd
import numpy as np

column1= [30, 40, 50, 60,90,20,30,20,30]
column2= ['bat', 'ball','tent']
table1 = np.tile(column1, len(column2))
table2 = np.repeat(column2, len(column1))
df = pd.DataFrame({"table1": table1, "table2": table2})
print(df)

output received:-
 table1 table2
0   30  bat
1   40  bat
2   50  bat
3   60  bat
4   90  bat
5   20  bat
6   30  bat
7   20  bat
8   30  bat
9   30  ball
10  40  ball
11  50  ball
12  60  ball
13  90  ball
14  20  ball
15  30  ball
16  20  ball
17  30  ball
18  30  tent
19  40  tent
20  50  tent
21  60  tent
22  90  tent
23  20  tent
24  30  tent
25  20  tent
26  30  tent

Excepted output:-
table1  table2
0   30  bat
1   40  bat
2   50  bat
3   60  ball
4   90  ball
5   20  ball
6   30  tent
7   20  tent
8   30  tent

Is there a better way to get the excepted output?

A: Use np.repeat like this:
df = pd.DataFrame({'table1': column1,
                   'table2': np.repeat(column2, len(column1) // len(column2))})
print(df)

# Output:
   table1 table2
0      30    bat
1      40    bat
2      50    bat
3      60   ball
4      90   ball
5      20   ball
6      30   tent
7      20   tent
8      30   tent

A: The code you are using will help you to achieve this result. there is no need to work on column1, you can try this it will return you the desired output
import pandas as pd
import numpy as np

column1= [30, 40, 50, 60,90,20,30,20,30]
column2= ['bat', 'ball','tent']
# table1 = np.tile(column1, len(column2))
table2 = np.repeat(column2, len(column1)/len(column2))
df = pd.DataFrame({"table1": column1, "table2": table2})
print(df)

but in this approach column1 must be a multiple of column2


text:
Q: ArcGIS Silverlight API 2.4 support for Microsoft Silverlight 5.0? Please let me know whether ArcGIS Silverlight API 2.4 version officially supports or CERTIFIES Microsoft Silverlight 5.0.?

A: I do not know about ArcGIS API for Silverlight 2.4, but on the assumption that you may by now be using a later release, I note that the ArcGIS API for Silverlight 3.1 installation certainly seems to support Silverlight 5.


text:
Q: How to detect if a process is running for the current logged-in user? Environment - C#, .net 4.0, VS 2010
Hello, I have written a simple shell replacement for Windows. The shell is launched automatically when users log in. The normal Windows "explorer.exe" is launched when users exit my shell.
Now, when users exit (and to properly support this) I need to be able to check if "explorer.exe" is running for the current logged-in user. This prevents the code from unnecessarily launching it again, which results in a "Windows Explorer" application window.
I have seen countless examples of how to check and see if a process is running...but none to see if it is running for the current logged-in user.
The code below will check to see if "explorer.exe" is already running and will start it if it isn't. But there are situations when this code will test positive when it doesn't need to!
For example, when using fast-user switching...Another user is logged in to the machine and, as a result, "explorer.exe" shows in the process list. But, while "explorer.exe" is running, it is NOT running for the current logged-in user! So when my shell exits, the code tests positive, and "explorer.exe" is not launched. The user is left with a black screen and no shell!
So, how can I mod the code below to test if "explorer.exe" is running for the current logged-in user?
Process[] Processes = Process.GetProcessesByName("explorer");
if (Processes.Length == 0)
{
   string ExplorerShell = string.Format("{0}\\{1}", Environment.GetEnvironmentVariable("WINDIR"), "explorer.exe");
   System.Diagnostics.Process prcExplorerShell = new System.Diagnostics.Process();
   prcExplorerShell.StartInfo.FileName = ExplorerShell;
   prcExplorerShell.StartInfo.UseShellExecute = true;
   prcExplorerShell.Start();
}

A: You could get SessionID from your process and then query Processes and get Explorer instance that have the same SessionID, let's say that your program is named "NewShell" :
  Process myProc = Process.GetProcesses().FirstOrDefault(pp => pp.ProcessName.StartsWith("NewShell"));
  Process myExplorer = Process.GetProcesses().FirstOrDefault(pp => pp.ProcessName == "explorer" && pp.SessionId == myProc.SessionId);

  if (myExplorer == null)
    StartExplorer()

btw. if you use ProcessName.StartsWith("NewShell") instead of ProcessName == "NewShell" then it will work under VS debugger also (it adds vshost to the exe)


text:
Q: How can I overload a function with multiple bracket-slots so f[a][b] and f[a] can coexist? Maybe this is not even possible:
I want to create a function f that can have two input brackets like:
f[a_][b_:1]:= a*b

and alternatively just one input bracket:
f[a_]:= a

But with overloading the definitions the second definition interferes with the first definition, because the pattern f[a_] is replaced in a expression like:
In:
f[2][3]

Out:
2[3]

with the result of f[2] (in this case)
Of course, I could use just one bracket slot like f[a_,b_:1], instead of f[a_][b_:1], but thats not the point.
So i am asking for an optional bracket slot. Is that possible?
(BTW, I dont know the correct name of the []-Pattern, and called it bracket slot)

A: In the Standard Evaluation Sequence the heads of expressions are evaluated first:

*

*If the expression is a raw object (e.g., Integer, String, etc.), leave it unchanged.

*Evaluate the head h of the expression.

*Evaluate each element of the expression in turn ...
Therefore since f[1] is the head of f[1][2] it will evaluate if it has a definition that matches.  This is unavoidable in standard evaluation.  To get around this requires Stack trickery that Leonid illustrated here.  It works on the principle that f is the head of f[1] itself and is therefore evaluated first of all.
Here is a meta-function to automate his method:
SetAttributes[deepDefine, HoldAll]

deepDefine[s_Symbol, LHS_, RHS_] :=
  s :=
   With[{stack = Stack[_]},
    With[{fcallArgs = Cases[stack, HoldForm[LHS] :> RHS]},
     (First@fcallArgs &) & /; fcallArgs =!= {}
    ]
   ]

We now apply it like this:
ClearAll[f]

deepDefine[f, f[a_][b_: 1], a*b]

f[a_] := a

Test:
f[x]
f[x][y]
f[z][]

x

x y

z


text:
Q: How to set volume in Phaser 3? I have a problem with the video game that I am trying to create.
The problem that I have is that, the song that I have made this one very strong and looking at the documentation I have seen that can form the volume, have applied this way of forming it without any result. Not if I have explained correctly...
My code in typescript:
export class SampleScene extends Phaser.Scene {
private song: Phaser.Sound.BaseSound;
 public preload() {
   // TODO: Add your code
   this.load.audio('theme', 'assets/audio/sayrun.mp3');
 }
 public create() {
     // TODO Add your code.
   this.song = this.sound.add('theme');
   this.song.play('volume', {volume: 0.5});
 }
}

A: It sounds like you have a bunch of audio clips, but one of them is louder than the other. When you play the loud one you're trying to turn down the volume to compensate.
But your current code is trying to play a volume asset at half volume.
Since you always want this particular audio asset to play at half volume, I would recommend changing your code so that the volume is set when you define the asset, and then just play() it.
public create() {
    this.song = this.sound.add('theme', {volume: 0.5});
    this.song.play();
}


text:
Q: Changing app name broke ability to run tests in xcode After I changed the product name for my app, I could still run the app in the simulator, but when I try to run tests, I get this error:
ld: file not found: /Users/stefankendall/Library/Developer/Xcode/DerivedData/ProjectName-fcxmoirjyqcvalgdndrznrmnvtdw/Build/Products/Debug-iphonesimulator/OldAppName.app/ProjectRootDirectory
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Why is the test action still trying to read from the old app name, even though I've changed the Product Name build property and xcode no longer builds to that location?

A: you need to change the "bundle loader" property of your unit test target.
Check the other properties of both the test and the app for the "OldAppName" by typing it in the search field on the "Build Settings" page for both targets.
Here is a screen shot to illustrate:

A: How you changed your appname? from the Project navigation pane? or from the build settings packaging -> product name of the target ?However i also want to tell that second way is ideal way to do it.

A: I think your problem is that you have to change the name of the folder in which your project is stored to your new name.

A: Change the product name to previous one. Build the project. Now update the product name to newer one. This works for me.


text:
Q: jujud won't start because of different ip address Is there anyone who can tell me how to modify both public and private IP of juju bootstrap node stored in mongodb?
I have an all in one openstack server. This week, I launched a vm named juju-core and installed software package juju-core on it. By using the command  juju bootstrap , I successfully got a juju bootstrap node, which is also a vm on openstack, running very well. And now I have a
problem and don't know how to solve it. I created a snapshot of the juju bootstrap vm and named it juju-bootstrap-snapshot. After that, I launch a new instance, which is named juju bootstrap-1, from that snapshot.
In order to connect to juju bootstrap-1 I have to login to juju-core vm and modify IP address of state-servers in
/home/$user/.juju/environments/openstack.jenv.
When I run the command juju status on the juju-core vm, there is always no response.
So I login to juju bootstrap-1 to try finding out what happened; and I found there's no process listening on port 17070.
> netstat -ntulp

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:6514            0.0.0.0:*               LISTEN      838/rsyslogd
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      970/sshd
tcp        0      0 0.0.0.0:37017           0.0.0.0:*               LISTEN      932/mongod
tcp        0      0 0.0.0.0:38017           0.0.0.0:*               LISTEN      932/mongod
tcp6       0      0 :::6514                 :::*                    LISTEN      838/rsyslogd
tcp6       0      0 :::22                   :::*                    LISTEN      970/sshd
udp        0      0 0.0.0.0:68              0.0.0.0:*                           587/dhclient
udp        0      0 0.0.0.0:15712           0.0.0.0:*                           587/dhclient
udp6       0      0 :::52056                :::*                                587/dhclient

But the jujud is running
>ps aux | grep juju
root       932  0.6  2.1 3516932 44336 ?       Ssl  Jan15   7:08 /usr/lib/juju/bin/mongod --auth --dbpath=/var/lib/juju/db --sslOnNormalPorts --sslPEMKeyFile /var/lib/juju/server.pem --sslPEMKeyPassword xxxxxxx --bind_ip 0.0.0.0 --port 37017 --noprealloc --syslog --smallfiles --journal --keyFile /var/lib/juju/shared-secret --replSet juju --oplogSize 817<p>
root       935  0.2  0.6 426096 14032 ?        Ssl  Jan15   2:37 /var/lib/juju/tools/machine-0/jujud machine --data-dir /var/lib/juju --machine-id 0 --debug

I also modified apiaddresses in /var/lib/juju/agents/machine-0/agent.conf on vm juju bootstrap-1; just to make sure that juju end-point will be listening on port 17070. But there is still no process listening on port 17070.
By using another tool, juju-dbinspect, I found that both public IP and private IP of the original juju bootstrap node are stored in mongodb. So I try to modify related tables in mysql of openstack neutron and nova just to make sure that the new juju bootstrap node can obtain the IP of the original juju bootstrap node. After I get this done, the juju end-point started successfully and there is a service listing on port 17070 of the new juju bootstrap node. Everything works again.
When doing jobs in openstack; creating a snapshot of a vm, launching a vm from a snapshot is very common usage. I don't know why juju bootstrap node vm won't work in such situation. Please let me know if I missed anything. According to what I have done, the new vm juju bootstrap-1 should work very well if I can modify both public IP and private IP of the original juju bootstrap node stored in mongodb on it. But I don't know how to do it. Anyone who can tell me how to do it will be very appriciated.
Thank you, Jeff


text:
Q: JavaScript: Convert URL string to a Unique identifier I would like to convert a URL string into a shorter unique identifier. I would like to use this GUID as a CSS class. It is also important that if I pass the same URL/string to the GUID generator function, the function should return the exactly same unique identifier.
What is the best way to do this?

A: As I right understand, you need uniq string as identifier. Why don't you use REST representation? One URL represent only one uniq state.


text:
Q: Jump to function definition in Emacs by mouse-click Using Emacs + Common Lisp (SBCL) + Slime, is there a quick way to jump to the definition of a function (defun ...) without typing (find-function) the name of the function?
I am looking for an similar solution as often provided in Eclipse:
Strg + (left-mouse-click on function call).

A: You can use the keyboard. Usually m-. or esc-. in Emacs. The cursor must be on the symbol.

A: In Emacs:
With point on the function whose definition you want to visit, hit C-x 5 F (find-function-other-frame).
You can also bind find-function, find-function-other-window, or find-function-other-frame to a mouse button action.
You mention Strg + (left-mouse-click on function call), for instance.  Dunno what Strg is here, but you can easily bind [mouse-1] or [down-mouse-1] to a command that checks the symbol at the click position, and if it is a defined function calls find-function for it, and if it is not has the usual [mouse-1] or [down-mouse-1] behavior.
Personally, I wouldn't want such behavior, but it is easy to achieve in Emacs.  For example:
(defun my-find-func-mouse (event)
  (interactive "e")
  (let ((fn  (save-excursion
               (goto-char (posn-point (event-end event)))
               (function-called-at-point))))
    (unless (fboundp fn) (error "No function here"))
    (find-function-do-it fn nil 'switch-to-buffer-other-window)))

(global-set-key [C-down-mouse-1] nil)
(global-set-key [C-mouse-1] #'my-find-func-mouse)

A: The usual way is to create a TAGS file using etags:
$ find . -type f -iname "*.lisp*" | etags -

Then, do M-x visit-tags-table and navigate to the TAGS file. After the tags are loaded, you can simply do M-. with point on function and it will open in the current buffer.
Also, you can use M-* to go back to where you were before.
If you're using projectile, you can simply keep your TAGS file in the project root and you won't need to run M-x visit-tags-table. Projectile will load the tags table automatically when you first press M-.


text:
Q: Why are these segments parallel? I constructed something with GeoGebra, and I ran into trouble.
How can I prove this. (Actually I just hope this will be true)

You can also check this construction https://www.geogebra.org/classic/kvcdt7bd
with navigation button below.
$$$$
I am not good at using English, so sorry in case of confusion.


text:
Q: Ubuntu Boots Into Desktop Background When I boot Ubuntu it loads and shows only the desktop background. I have a black cross cursor and can right click to show the expected context menu for the desktop.
I can use Ctrl+Alt+F1  to get a terminalF1toF6 (tty1 to tty6) from which I have tried a lot of things suggested to others with similar issues on here.
I tried the basic sudo apt-get update and sudo apt-get upgrade which didn't help. I tried restarting lightdm. Updated nvidia drivers. Nothing made a difference.
One post said the issue was to do with the ccsm unity plugin being disabled. I managed to get that program to run and the plugin was disabled but enabling it has made no difference.
One suggested that unity needed reinstalling so I ran sudo apt-get install --reinstall unity. It reinstalled but didn't fix the problem.
Another said to install GNOME then switch back to unity which didn't work (though I could load gnome without any problems). I also ran a few commands which were supposed to set the defaults and reset settings though I can't remember what they were exactly. As you may have guessed those had no effect too.
Anyone have any ideas? I would just reinstall Ubuntu from usb but I have no way to get it onto a USB to do so.
Edit: The linked duplicate answer is one I had already tried and found didn't solve my issue.

A: For the Desktop Issue use these commands,
sudo apt-get update
sudo apt-get remove ubuntu-desktop unity -y
sudo apt-get purge ubuntu-desktop unity -y
sudo apt-get install --no-install-recommends ubuntu-desktop -y
sudo apt-get upgrade -y
sudo apt-get dist-upgrade -y
sudo apt-get autoclean -y
sudo reboot

As for your USB, go on someone else's computer, Install UNetBootIN and Burn the ISO

A: I ran into the same problem using MATE 1.8 under Ubuntu 14.04 and after hours i ended up installing Cinnamon (which i'm more than happy now with, btw.), to get a working desktop to find out what's going wrong.
The solution was to disable all the autostart programs from MATE inside my user profile.
I've moved all .desktop files out of ~/.config/autostart/ and then been able to login to MATE again.
I'm 99% sure your problem will be fixed by disabling your autostart items.


text:
Q: El-table-column prop with several values in an array I want to display on table column (I'm using Element-UI), a prop that has several values in a specific array. In my case, it's the array in settings that has 2 max values, a main label and a secondary label. I want to fetch and display the specific value of label as an array (value1, value2). I can fetch it if I use the property: prop="settings.0.label" or prop="settings.1.label", but I need to display both. Here's an image of the array structure. Array
Here's also the code of the table-column:
<el-table-column prop="settings" label="Status" sortable
    :sort-orders="['ascending', 'descending']" />
<el-table-column>

A: You can use a custom template to define your own content within a cell.

var Main = {
    data() {
      return {
        tableData: [{
          name: 'Tom',
          settings: [{
            value: 'first'
          }, {
            value: 'second'
          }]
        }, {
          name: 'John',
          settings: [{
            value: 'first'
          }, {
            value: 'second'
          }]
        }]
      }
    }
  }
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
@import url("//unpkg.com/element-ui@2.15.1/lib/theme-chalk/index.css");

  <template>
    <el-table ref="filterTable" :data="tableData" style="width: 100%">
      <el-table-column prop="name" label="Name" width="180"></el-table-column>
      <el-table-column label="Status">
        <template slot-scope="scope">
          {{ scope.row.settings[0].value }} - {{ scope.row.settings[1].value }}
        </template>
      </el-table-column>
    </el-table>
  </template>

Or you could define your own formatter:

var Main = {
    methods: {
      formatter(row, column) {
        return `${row.settings[0].value} - ${row.settings[1].value}`
      }
    },
    data() {
      return {
        tableData: [{
          name: 'Tom',
          settings: [{
            value: 'first'
          }, {
            value: 'second'
          }]
        }, {
          name: 'John',
          settings: [{
            value: 'first'
          }, {
            value: 'second'
          }]
        }]
      }
    }
  }
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
@import url("//unpkg.com/element-ui@2.15.1/lib/theme-chalk/index.css");

  <template>
    <el-table ref="filterTable" :data="tableData" style="width: 100%">
      <el-table-column prop="name" label="Name" width="180"></el-table-column>
      <el-table-column prop="settings" label="Status" :formatter="formatter"></el-table-column>
    </el-table>
  </template>


text:
Q: MySQL Query Retrieve Tags in TWO Categories (AND not OR) [WordPress Raw SQL] Struggling with this for a while
   SELECT DISTINCT terms2.term_id as tag_id, terms2.name as tag_name, terms2.slug as tag_slug, t2.description as tag_desc
    FROM
        wp_posts as p1
        LEFT JOIN wp_term_relationships as r1 ON p1.ID = r1.object_ID
        LEFT JOIN wp_term_taxonomy as t1 ON r1.term_taxonomy_id = t1.term_taxonomy_id
        LEFT JOIN wp_terms as terms1 ON t1.term_id = terms1.term_id,

        wp_posts as p2
        LEFT JOIN wp_term_relationships as r2 ON p2.ID = r2.object_ID
        LEFT JOIN wp_term_taxonomy as t2 ON r2.term_taxonomy_id = t2.term_taxonomy_id
        LEFT JOIN wp_terms as terms2 ON t2.term_id = terms2.term_id
    WHERE
    t1.taxonomy = 'product_cat' AND p1.post_status = 'publish' AND terms1.term_id IN (224,229) AND
    t2.taxonomy = 'product_tag' AND p2.post_status = 'publish'
        AND p1.ID = p2.ID
    ORDER by tag_name

Line I am dealing with is this one:
t1.taxonomy = 'product_cat' AND p1.post_status = 'publish' AND terms1.term_id IN (224,229) AND
This works, but the IN clause acts as an OR--- so it is bringing back tags that are in either the term_id 224 or 229
I am trying to make it so that it only returns tags that are in BOTH 224 and 229
I've tried
t1.taxonomy = 'product_cat' AND p1.post_status = 'publish' AND terms1.term_id = '224' AND
 t1.taxonomy = 'product_cat' AND p1.post_status = 'publish' AND terms1.term_id = '229' AND
but it just returns an empty result...
The only solution I have right now is to do two queries terms1.term_id = '224' for 224 and terms1.term_id = '229' for 229 and then use other logic to return the two matching.
Is there a way to combine this into one query?
Edit: See results of the IN query below (modified so that terms1.term_id is visible)

As you can see Gray is only in 229 (and thus not part of the result set I am trying to return back)

A: @BrianBruman I'm assuming that terms1.term_id is a comma separated list of values. If this is the case, you can use FIND_IN_SET() to make sure both 224 and 229 are in the comma delimited list.
Here is what your query needs to look like in order to get tags with both 224 and 229:
  SELECT DISTINCT terms2.term_id as tag_id,
      terms2.name as tag_name,
      terms2.slug as tag_slug,
      t2.description as tag_desc
  FROM
      wp_posts as p1
      LEFT JOIN wp_term_relationships as r1 ON p1.ID = r1.object_ID
      LEFT JOIN wp_term_taxonomy as t1 ON r1.term_taxonomy_id = t1.term_taxonomy_id
      LEFT JOIN wp_terms as terms1 ON t1.term_id = terms1.term_id
      JOIN wp_posts as p2 ON p2.ID = p1.ID
      LEFT JOIN wp_term_relationships as r2 ON p2.ID = r2.object_ID
      LEFT JOIN wp_term_taxonomy as t2 ON r2.term_taxonomy_id = t2.term_taxonomy_id
      LEFT JOIN wp_terms as terms2 ON t2.term_id = terms2.term_id
    WHERE
      t1.taxonomy = 'product_cat'
      AND p1.post_status = 'publish'
      AND (
              FIND_IN_SET('224', terms1.term_id) > 0
              AND FIND_IN_SET('229', terms1.term_id) > 0
          )
      AND t2.taxonomy = 'product_tag'
      AND p2.post_status = 'publish'
    ORDER by tag_name

EDIT: according to your last comment, terms1.term_id isn't a comma delimited list. In that case, you would need to join in another instance of wp_terms. Here is what your query needs to look like:
      SELECT DISTINCT terms2.term_id as tag_id,
          terms2.name as tag_name,
          terms2.slug as tag_slug,
          t2.description as tag_desc
      FROM
          wp_posts as p1
          LEFT JOIN wp_term_relationships as r1 ON p1.ID = r1.object_ID
          LEFT JOIN wp_term_taxonomy as t1 ON r1.term_taxonomy_id = t1.term_taxonomy_id
          LEFT JOIN wp_terms as terms1 ON t1.term_id = terms1.term_id
          LEFT JOIN wp_terms as terms3 ON t1.term_id = terms3.term_id
          JOIN wp_posts as p2 ON p2.ID = p1.ID
          LEFT JOIN wp_term_relationships as r2 ON p2.ID = r2.object_ID
          LEFT JOIN wp_term_taxonomy as t2 ON r2.term_taxonomy_id = t2.term_taxonomy_id
          LEFT JOIN wp_terms as terms2 ON t2.term_id = terms2.term_id
        WHERE
          t1.taxonomy = 'product_cat'
          AND p1.post_status = 'publish'
          AND terms1.term_id = '224'
          AND terms3.term_id = '229'
          AND t2.taxonomy = 'product_tag'
          AND p2.post_status = 'publish'
        ORDER by tag_name

One last thing: if you only want results to show where wp_posts has a corresponding wp_terms record where the term_id is both 224 and 229 you shouldn't be using LEFT JOIN on wp_terms, you should use a regular old JOIN, which will improve the performance of your query a lot.
Hope this helps!


text:
Q: $_POST variable empty when send POST I'm trying to send a JSON to my rest-api using RestSharp. Essentially I've created a model class for the json:
public class LogPostData
{
    public string LogMessage { get; set; }
    public string LogStackTrace { get; set; }
    public string LogUserId { get; set; }
    public string LogUserIp { get; set; }
}

so I perform the request in this way:
 var logPost = new LogPostData();
     logPost.LogMessage = "log message"
     logPost.LogStackTrace = "some content";

 var post = JsonConvert.SerializeObject(logPost);

 var client = new RestClient("url of rest api");

 var request = new RestRequest("methodApi", Method.PUT);
     request.RequestFormat = DataFormat.Json;
     request.AddParameter("application/json; charset=utf-8", post, ParameterType.RequestBody);
     request.RequestFormat = DataFormat.Json;

 var response = client.Execute(request);

as you can see I've created the object LogPostData and then serialized it using JsonConvert.SerializeObject.
I called the methodApi passing as parameter the json.
Now, inside my rest api, I did the following:
file_put_contents('debug.txt', serialize($_POST));

the content should be the variable that I sended with RestSharp on post variable, instead I get: a:0:{}
why my $_POST variable is empty?

A: According to the PHP manual, $_POST works with application/x-www-form-urlencoded and multipart/form-data content types.  You are sending JSON (application/json).  Since $_POST is an associative array created from posted form data, and you are not posting a form, it's not surprising that it would be empty.
To get the raw JSON from the request body you need to use php://input
$json = file_get_contents('php://input');

To deserialize the JSON to an object you can use json_decode.
$logPostData = json_decode($json);

If you want the data to be converted into an associative array like $_POST, you can pass true as the second parameter:
$logPostData = json_decode($json, true);

A: Here's what you are sending (JSON):
header: encoding-type=application/json
body: {"param1":"I like horses", "param2":"they are cool"}

This is what PHP needs in a POST request for the $_POST array to work (form submissions)
header: encoding-type=application/x-www-form-urlencoded
body: param1=I%20like%20horses&param2=they%20are%20cool

If you are happy with sending json, you need to receive it properly.
If you want to keep using PUT, then make a handler for it that expects JSON.  (Based on this answer)
$method = $_SERVER['REQUEST_METHOD'];
if ('PUT' === $method) {
    $data = json_decode(file_get_contents('php://input'), true);
    var_dump($data); //$data contains put fields
}


text:
Q: Null check operator used on a null value, Relevant Error causing widget was Material App The app was working just fine till I used listview.builder and added a list of items (mentioned in datalist)  I am unable to understand what exactly is causing the error since there's no error showing in the IDE itself. Can anyone explain what is happening here and possibly give me a solution?
Thanks in advance!
Finance Page:
 import 'package:flutter/material.dart';

class FinancePage extends StatefulWidget {
  const FinancePage({Key? key}) : super(key: key);

  @override
  _FinancePageState createState() => _FinancePageState();
}

class _FinancePageState extends State<FinancePage> {

  final List<DataTiles> dataList = [
    DataTiles(title: "Mobile Home Dealers", subtitle: "Last payment 17 May",color: Colors.deepPurpleAccent.shade50),
    DataTiles(title: "Taxicabs and Limousines", subtitle: "Last payment 26 May",color: Colors.lightBlueAccent),
    DataTiles(title: "Miscellaneous Apparel and Accessory Shops", subtitle: "Last payment 06 April",color: Colors.redAccent),
    DataTiles(title: "Electric, Gas, Sanitary and Water utilities", subtitle: "Last payment 01 May",color: Colors.deepPurpleAccent.shade50),
    DataTiles(title: "Misc. General Merchandise", subtitle: "Last payment 01 March",color: Colors.lightBlueAccent),
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.deepPurple.shade800,
      body: Column(
        children: [
          const SizedBox(
            height: 100,
          ),
          Padding(
              padding: const EdgeInsets.all(10),
              child: Card(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(5),
                ),
                elevation: 3,
                child: ListTile(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(5),
                    ),
                    tileColor: Colors.deepPurpleAccent,
                    leading: const Text(
                      "Card balance",
                      style: TextStyle(color: Colors.white),
                    ),
                    trailing: FittedBox(
                      fit: BoxFit.fill,
                      child: Row(
                        children: const [
                          Text(
                            "0₹",
                            style: TextStyle(color: Colors.white),
                          ),
                          Icon(
                            Icons.arrow_forward_ios,
                            color: Colors.white,
                            size: 10,
                          )
                        ],
                      ),
                    )),
              )),
          const Text("PAYMENT CATEGORIES",
              style: TextStyle(
                color: Colors.grey,
              )),
             SizedBox(
               height: 200,
               child: ListView.builder(
                   scrollDirection: Axis.horizontal,
                   itemCount: dataList.length,
                   itemBuilder: (context, index) {
                     return  SizedBox(
                       width: 170,
                       child: Card(
                         child: Column(
                           children: [
                             Text(dataList[index].title,
                                 style: const TextStyle(
                                   fontSize: 20,
                                 ),
                             ),
                             Text(dataList[index].subtitle,),
                           ],
                         ),
                         shape: RoundedRectangleBorder(
                           borderRadius: BorderRadius.circular(10),
                         ),
                         color: dataList[index].color,
                       ),
                     );
                   }),
             ),
        ],
      ),
    );
  }
}

class DataTiles {
  DataTiles({required this.title, required this.subtitle, required this.color});
  final String title;
  final String subtitle;
  final Color color;
}

main.dart
import 'package:flutter/material.dart';

import 'finance_page.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return  const MaterialApp(
      title: 'Flutter Demo',
      home: FinancePage(),
    );
  }
}

A: Error causing lines are
DataTiles(title: "Mobile Home Dealers", subtitle: "Last payment 17 May",color: Colors.deepPurpleAccent.shade50),
DataTiles(title: "Electric, Gas, Sanitary and Water utilities", subtitle: "Last payment 01 May",color: Colors.deepPurpleAccent.shade50),

Remove the shade50 or change to another color without shade then this will work. Some colors don't have a value for Shade50 eg deepPurpleAccent and deepPurpleAccent. shade100 will work for them. Check the documentation before using shades


text:
Q: collection1: org.apache.solr.common.SolrException:org.apache.solr.common.SolrException: Unknown fieldtype 'text' specified on field Report_Name I am following the tutorial as in http://www.sunilgulabani.com/2013/01/import-mysql-database-with-apache-solr.html. I have modified the data-config.xml as :-
<dataConfig>
    <dataSource driver="sun.jdbc.odbc.JdbcOdbcDriver" type="JdbcDataSource"
       url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\users\\ppreeti\\executive_db.accdb" user="" password="" />
    <document name="products">
       <entity name="Report" query="select * from Report">
           <field column="Report_Name" name="Report_Name" />
           <field column="Report_ID" name="Report_ID" />
           <field column="Section_ID" name="Section_ID" />
           <field column="Contact_ID" name="Contact_ID" />
           <field column="ZipFile_IND" name="ZipFile_IND" />
           <field column="Last_Update" name="Last_Update" />
           <field column="Link" name="Link" />
           <field column="link_id" name="link_id" />
           <!--<entity name="Contact" query="select Contact_Name from Contact where item_id='${item.ID}'">
               <field name="features" column="description" />
           </entity>
           <entity name="item_category" query="select CATEGORY_ID from item_category where item_id='${item.ID}'">
               <entity name="category" query="select description from category where id = '${item_category.CATEGORY_ID}'">
                   <field column="description" name="cat" />
               </entity>
           </entity>-->
       </entity>
    </document>
</dataConfig>

I have also not followed the step 4 as mentioned in the tutorial since I am accessing MS Access database and I found out that it is inbuilt .
I've also modified schema.xml following another tutorial by adding the following lines before the  tag:-
<fields>

    <field name="Report_Name" type="text" indexed="true" stored="true" required="true"/>
    <field name="Report_ID" type="text" indexed="true" stored="true" required="true"/>
    <field name="Section_ID" type="text" indexed="true" stored="true" required="true"/>
    <field name="Contact_ID" type="text" indexed="true" stored="true" required="true"/>
    <field name="ZipFile_IND" type="text" indexed="true" stored="true" required="true"/>
    <field name="Last_Update" type="text" indexed="true" stored="true" required="true"/>
    <field name="Link" type="text" indexed="true" stored="true" required="true"/>
    <field name="link_id" type="text" indexed="true" stored="true" required="true"/>

    <dynamicField name="*" type="ignored" />
 </fields>

 <uniqueKey>Report_ID</uniqueKey>
 <!-- field for the QueryParser to use when an explicit fieldname is absent -->
 <defaultSearchField>Report_Name</defaultSearchField>

So,when I run on browser as described in step-5 , I get the error as:-
collection1: org.apache.solr.common.SolrException:org.apache.solr.common.SolrException: Unknown fieldtype 'text' specified on field Report_Name
So, how should I resolve the error ?

A: There is no longer a fieldType of text defined in the default solrconfig.xml file anymore.  Try changing all the fields in your schema.xml file to use type="text_general" as this is a suitable replacement found in the current solrconfig.xml file.
I would also recommend that you look at the solrconfig.xml file in your installation as well as reading the Analyzers, Tokenizers, and Token Filters page on the Solr Wiki to better understand how the fieldType definitions are setup.


text:
Q: como combinar eventos con if-else actualmente estoy aprendiendo js y tengo un problema para hacer un condicional usando una entrada les dejo un ejemplo (cuando lo hago sin la entrada funciona bien) que puedo hacer alguien tendra algun ejemplo de eventos usando condicionales o loops para ayudarme, busque en youtube y no encontre respuestas muchas gracias
javascript DOM
<input id="getInto" type="text" >
<button onClick="doTask()">press</button>

<script>

    const input = document.getElementById("getInto");
    function doTask() {

 let age = input

if (age >= 18 ){

    alert("vote")
}
else {
    alert("does not vote");
}

}

A:

<html>
    <!-- creamos un imput type number con un color de fondo blanco con un valor entre 0 y 95 -->
    <input type="number" min="0" max="95" value="0" style="background-color: white;" class="inputnumeral">
    <!-- creamos un imput type text en oculto y con un valor igual a 0 -->
    <input type="text" value="" style="display: none;"class="inputexto">
    <!-- creamos dos botones uno de color rojo y otro azul, con un texto en el medio de votar-->

    <button class="btnrojo botones red" style="background-color:red;" disabled >Votar</button>
    <button class="btnazul botones blue"style="background-color:blue;" disabled >Votar</button>

    <script>
        //buscamos un input con una classe inputnumeral
        var inputnumeral = document.querySelector('.inputnumeral');
        //buscamos un input con una classe inputexto
        var inputexto = document.querySelector('.inputexto');
        //buscamos un boton con una classe botones
        var botones = document.querySelectorAll('.botones');
        //comprobamos cada vez qye el valor de inputnumeral cambia
        inputnumeral.onchange = function(){
            //si el valor de inputnumeral es mayor o igual que 18 y menor o igual que 65 entonces el valor de inputexto sera "PUEDES VOTAR", el color de fondo del inputnumeral sera verde, inputexto sera visible y los botones se podran pulsar

            if(inputnumeral.value >= 18 && inputnumeral.value <= 65){
                inputexto.value = "PUEDES VOTAR";
                inputnumeral.style.backgroundColor = "green";
                inputexto.style.display = "block";
                botones[0].disabled = false;
                botones[1].disabled = false;
            }
            //si el valor de inputnumeral es mayor que 65 y menor de 18 entonces el valor de inputexto sera "NO PUEDES VOTAR", el color de fondo del inputnumeral sera rojo, inputexto sera visible y los botones se podran pulsar
            else if(inputnumeral.value > 65 || inputnumeral.value < 18){
                inputexto.value = "NO PUEDES VOTAR";
                inputnumeral.style.backgroundColor = "red";
                inputexto.style.display = "block";
                botones[0].disabled = true;
                botones[1].disabled = true;
            }}

    </script>
</html>

A: cuando ejecutas const input = document.getElementById("getInto");, estás obteniendo el elemento HTML con el id de getInto (un input en este caso). Para obtener la información que contiene el input usas la propiedad value, que devuelve un string; en este caso, conviertes dicho string a un número para poder compararlo con otro número (usand parseInt o el operador unario +) y ya debería funcionar.

<input id="getInto" type="text" >
<button onClick="doTask()">press</button>

<script>

    const input = document.getElementById("getInto");
    function doTask() {

      let age = +input.value; //o parseInt(input.value)

      if (age >= 18 ){

        alert("vote")
      } else {
    alert("does not vote");
      }
}
</script>


text:
Q: regex to extract second matching record from brackets regex to get data from below string.
below is input String
insert into data (name, Id, address) values (:name,:id,:add)

it should return only second bracket values excluding bracket
Expected output
:name,:id,:add

I tried below regex but it not working. it is highlighting only first bracket. I need second bracket records
(?<=\()[\w, ?]+(?=\))

A: You may use this regex and grab captured group #1:
/.*\(([^)]*)\)/

RegEx Demo

*

*.* is greedy to make sure we always match last pair of (...)

*\(: Match literal (

*(([^)]*): Match 0 or more characters that is not ) in captured group #1

*\): Match literal )

However if intent is to always match 2nd pair of (...) then use this regex and grab captured group #1:
/\([^)]*\)[^()]*\(([^)]*)\)/

RegEx Demo 2
Code:
final String regex = "\\([^)]*\\)[^()]*\\(([^)]*)\\)";
final String string = "insert into data (name, Id, address) values (:name,:id,:add) (:foo,\"bar)";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

if (matcher.find()) {
    System.out.println(matcher.group(1));
}

output:
:name,:id,:add

A: I would use this one: ([:][\w]+) so you got the results in own match group and it´s easy to say which param needed on which place in case oan a error.
Have a look on the demo


text:
Q: HHVM + symfony2 + capifony deployment error Did anyone came across issues when deploying with capifony hhvm stack?
I am getting errors just after vendors are done:

Script
  Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::buildBootstrap
  handling the post-install-cmd event terminated with an exception

https://gist.github.com/pawmart/15da1cc55d1ab5c4ba7c
This is Symfony 2.3.9
"sensio/distribution-bundle": "2.3.*",


text:
Q: error: Failed to establish TLS connection: underlying network error (Connection reset by peer) I am using Centos 7.6.
When running rudder agent update, I get a TLS connection error. The web console is working, and the machine is registered.  However, there are no reports from the server.
Any suggestions on what could be causing this would be helpful.
$ sudo rudder agent update
error: Failed to establish TLS connection: underlying network error (Connection reset by peer)
error: No suitable server found
error: Failed to establish TLS connection: underlying network error (Connection reset by peer)
error: No suitable server found R:
*********************************************************************************
* rudder-agent could not get an updated configuration from the policy server.   *
* This can be caused by:                                                        *
*   * an agent key that has been changed                                        *
*   * if this node is not accepted or deleted node on the Rudder root server    *
*   * if this node has changed policy server without sending a new inventory    *
* Any existing configuration policy will continue to be applied without change. *
*********************************************************************************
error: Rudder agent promises could not be updated.

A: To debug the problem, you can use rudder server debug <NODE-IP-OR-HOSTNAME> on your Rudder server (with the ip or hostname of the failing node as parameter), it will start a debug server and display more information about the connection.
Then run rudder agent update on the node and check the output on the server, it should indicate the cause of the problem. If you see nothing on the server, it is probably a network configuration issue, you need to check if tcp/5309 is correctly open from your node to the Rudder server.
Note: On the other hand, if the policy updates succeeds in debug mode (and only in debug mode), the problem probably lies in the policy server daemon on your Rudder server, and rudder agent restart on you Rudder server should fix it.


text:
Q: urgent help fatal error magento 2 website is working but all the styles are gone after running command need serious and urgent help.
i was trying to disable a module in magento2.2 by command line.
first i run the command: php bin/magento setup:upgrade
and after that i ran the command to disable the module : php bin/magento module:disable My-ModuleName
after doing that when i went ot my website and dashboard it was all like the following screen shot

i tried to clear cache but nothing is working. can someone please help me!!!

A: bin/magento setup:static-content:deploy


text:
Q: API key vs. Access Token Paypal Adaptive Payments Intro
Paypal API intro
What is the difference is between an API key and an Access Token? They both seem to work as "passwords" for the paypal communications.
I'm running the code on the paypal API intro(using curl in PHP, which I'm also just starting to understand), and I'm not sure how to get from that the the paypal adaptive payments stuff. I'm having trouble figuring out how I call "Adaptive Payments" in my code. Do I actually put that in there somewhere or is it implied when I call for multiple payments with one transaction?


text:
Q: Ajax get in wordpress I would like to ask if where should the ajax url be pointed when I want to load a post through ajax get. I'm coming from a php framewor so basically there you just define ajax url using the routes that you have set. In wordpress how do you implement it. Here's my code so far:
$liquor = new WP_Query( array(
    'post_type'   => 'product',
    'posts_per_page'    => 10,
    'meta_query'  => array(
        array(
            'key'   => '_stock_status',
            'value' => 'instock',
        )
    ),
    'tax_query'             => array(
        array(
            'taxonomy'      => 'product_cat',
            'terms'         => $category['category_slug'],
            'field'         => 'slug',
            'operator' => 'IN'
        )
    )
) );

A: in your functions.php which is located in your theme add
function YourAjaxFunction() {
    //your code here
}

After that, add your hook with connects to the WP AJAX
add_action('wp_ajax_your_ajax_function', 'YourAjaxFunction');
add_action('wp_ajax_your_ajax_function', 'YourAjaxFunction');

wp_ajax_nopriv_%s allows it to be called from the front end.
And then, in your javascript file, you just fire off your ajax request.
$.post(ajaxurl, { action: 'your_ajax_function' }, function(output) {
alert(output);
});

source : How to add ajax to wordpress theme


text:
Q: WebView intent Facebook and Instagram I have WebView. On the site i click Social button(Facebook,Twitter, VK, OK, Instagram, Telegram). Work is VK, Twitter, YouTube and Telegram.  When I click this social button, I need to launch the application (if it is installed on my phone) But it starts only in WebView

A: You have to use Intent to launch the installed apps. Pass the package name to launch the application.
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.package.address");
if (launchIntent != null) {
    startActivity(launchIntent);//null pointer check in case package name was not found
}


text:
Q: Why is twitter bootstrap carousel class "slide" unknown in bootsrap 3 I have downloaded the twitter bootsrap carousel example. I noticed that when I navigate the slide nothing happens and in my view the "slide" class from the bootstrap.css version 3 is unknown.
Based on the head section below I believe I have all the necessary js and css files.
I have 2 questions. Why is the the "slide" class unknown and should the carousel be navigable straight out of the box?

<link href ="/Content/bootstrap/css/bootstrap.min.css" rel="stylesheet">
        <link href ="/Content/bootstrap/css/bootstrap-responsive.css" rel="stylesheet">

        ...

    ...

</div

A: Here is a working code for carousel,
     <!DOCTYPE html>

    <link href="../../dist/css/bootstrap.css" rel="stylesheet">
     <link href="carousel.css" rel="stylesheet">

Slide 1.

Sign up today

Slide 2

Learn more

Slide 3

Browse gallery


text:
Q: Unable to Access my own website from the Server console I am having a weird issue hosting my web application. I am able to access the website from any other computer (from outside the network and from within the network) but unable to
access it from the Server!! (using the browser )
The details are as follows

*

*Windows Server 2003

*IIS 6.0

*The system has got a private IP and a public ip

*Accessing by Domain name/Public IP from external and intranet clients works fine.

*Accessing by Private IP from the  intranet clients works fine

*Accessing by PrivateIP or localhost  works from the server

*Accessing by Public IP or Domain name from the server doesn't work!!

As an extra troubleshooting, I did
telnet localhost 443 - works
telnet publicip 443 - doesn't work

A: Maybe public IP isn't routeable from your server.
Verify what happens when you try to access publicip:
tracert publicip

Check your network settings:
ipconfig /all

Check your socket listenings:
netstat -a -n

Local firewall rules?

A: Also, there's always the issue of server loopback, wherein a server cannot resolve a named reference to itself from within the server. Most commonly occurs on intranets, or on SharePoint sites, I've noticed.

A: The problem was with our DNS settings. We recently changed from Public IP to Private IP and the DNS reply was somewhat messed up when we tried opening it from the Server!!.
Thanks for your answers!


text:
Q: Updating nodes from multiple xml strings I basically need to encrypt the data that is stored in field of a table as xml string.
I am using AES encryption. I already have the logic for encryption and decryption. All I want to do is load the xml string and update two nodes.
Basically I need to update
<Bankaccountnumber>23232323</Bankaccountnumber>Banksortcode>232323</Banksortcode> nodes.
I basically have around 60,000 records and want to do it efficiently using C# program. Please see the sample of the xml string below
 <?xml version="1.0" encoding="utf-16"?><callvalidate><authentication><company>Bestinvest Brokers</company><username>API@bestinvest.co.uk</username><password>Pa55word67</password></authentication><sessions><session RID="0cee7f47-59b4-4fb2-a8eb-bafba9dec8ee"><data><Checksrequired><BankStandard>Yes</BankStandard><BankEnhanced>Yes</BankEnhanced><CardLive>No</CardLive><CardEnhanced>No</CardEnhanced><IDEnhanced>Yes</IDEnhanced><DeliveryFraud>No</DeliveryFraud><EmailValidate>No</EmailValidate><CreditScore>No</CreditScore><Zodiac>No</Zodiac><IPAddress>No</IPAddress></Checksrequired><Personalinformation><IndividualDetails><Title>Mr.</Title><Firstname>test</Firstname><Surname>test</Surname><Dateofbirth>1996-02-01T00:00:00</Dateofbirth><Emailaddress>ranjit.menon9@gmail.com</Emailaddress></IndividualDetails><AddressDetails><Buildingname></Buildingname><Postcode>se93qS</Postcode><Previouspostcode /></AddressDetails></Personalinformation><Bankaccountnumber>23232323</Bankaccountnumber><Banksortcode>232323</Banksortcode></data></session></sessions><application>LT-API-BEML</application></callvalidate>

A: Try XML Linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument callvalidate = XDocument.Load(FILENAME);

            List<XElement> bankAccountNumbers = callvalidate.Descendants("Bankaccountnumber").ToList();
            for(int index = 0; index < bankAccountNumbers.Count; index++)
            {
                XElement bankAccountNumber = bankAccountNumbers[index];

                int accountNumber = int.Parse(bankAccountNumber.Value);
                XElement newBankAccountNumber = new XElement("Bankaccountnumber", new object[] {
                    accountNumber,
                    new XElement("Banksortcode",accountNumber)
                });
                bankAccountNumber = newBankAccountNumber;
            }
        }
    }
}


text:
Q: How can I construct an sql query for the following result? I have 2 tables:

*

*table1
    id|val1|val2
    1 | 100|200
    2 | 200|400

*table2
id|val1|val2
1 | 100|250
3 | 500|400

table3 should be like,
id|val1|val2
1 | 100|250
2 | 200|400
3 | 500|400

These 2 tables have some common elements.
I want to write a  query which results in  following condition:
Table3 = Table2 + ( Table1- Table2)
The common elements should be deleted from Table1 and the remaining data should be taken.

A: Use the following:
select ifnull(id_2, id_1) id,
       ifnull(val1_2, val1_1) val1,
       ifnull(val2_2, val2_1) val2
from (
       select t1.id id_1, t1.val1 val1_1, t1.val2 val2_1,
              t2.id id_2, t2.val1 val1_2, t2.val2 val2_2
       from table1 t1 left join table2 t2 on t1.id = t2.id
       union
       select * from table1 t1 right join table2 t2 on t1.id = t2.id
) x

SQL Fiddle


text:
Q: Can I use HTML5 to send a client-side email? I want to send an email in HTML5. I don't want to force the user to open a mail client, I want to send the email directly from the web page.
On a side note, is there any way at all to do this in JavaScript? I know it's probably not possible, just wondering if there are any crafty ways to pull it off going completely through the client.

A: Yes it is possible. But not practical ** See Edit 2
Some HTML5 implementations include support for websockets, essentially a tcp connection to a server. Overlay some send/recv code and you can build a SMTP client.
In fact it looks like nodejs and websocket support has been used to implement a smtp client ... see here ...
You would still need a smtp server, username, password, etc just like a standard smtp client in order for it to work.
Using this method for spam would be unlikely as your smtp provider could easily cancel your account.
=== EDIT ===
Actually you could build a server less version, it would have to also implement name server lookups to find mx records. Chances are however that any decent SMTP servers maintain spamlist blacklist tables and connecting from an random ip address would see the email commonly marked as spam.
Also talking to smtp servers that require secure mail connections could be difficult.
As others have mentioned there are malicious uses to this implementation like sending spam. I guess it is possible you could be a HTML5 botnet creator but I would have thought that you would know most of this already :)
=== EDIT 2 ===
As Mark At Ramp51 mentioned, Handshaking is required with websockets. This was something I wasn't aware of. You would have to hack the websocket implementation to bypass handshaking.
The correct way is to have the web server forward the email.

A: This is not possible.
Instead, you should use AJAX to send the email on the server.

A: In short NO not directly from the client (excluding hacks).
you could make an ajax call to your server and send an email.
the problem with doing it from the client and not using a mail client is complicated.  For example most consumer ISPs have their own SMTP relay that all outbound mail on  port 25 must be transmitted over.  You website will have trouble obtaining the proper information to do this.  Secondly the webbrowser doesn't understand the SMTP protocol and neither does the XMLHttpRequest object.
So if you are a hacker ninja, maybe you can figure something out with ActiveX, Java Applets, or flash, but you basically would have to be operating directly with a tcp socket and issuing SMTP protocol commands over that socket.
There are many obstacles to overcome, in fact I don't know how to do it, but where there is will there is a way.  Don't be surprised that if you do find a hack, it may be plugged swiftly by the major browser vendors.

A: You can't send the email using JavaScript alone. You'll need some form of server side processing (PHP, ASP, etc) to send the actual email.
There's a good tutorial on setting up an ajax form here:
http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
It doesn't include the PHP (or ASP, etc) for sending the email, but there are plenty of tutorials out there for how to send an email using PHP.

A: Send email directly from Javascript
From official resource:

How does it work?

*

*Connect your email service
Choose from a wide variety of email services. We support both
transactional email services (Mailgun, Mailjet, Mandrill, SendGrid, Amazon SES and Postmark) and personal email services (AOL, Gmail, FastMail, iCloud, Mail.ru, Outlook, Yahoo, Yandex and Zoho).

*Create email templates
Choose from a list of our template designs, or easily build your own.
Templates are parametrized, so that you can further customize them via Javascript.

*Send email with our Javascript API
Add our Javscript SDK, and start sending emails!
Here's what a typical call looks like:
var service_id = 'my_mandrill';
var template_id = 'feedback';
var template_params = {
  name: 'John',
  reply_email: 'john@doe.com',
  message: 'This is awesome!'
};

emailjs.send(service_id,template_id,template_params);

All existing APIs require using a secret key, which you obviously wouldn't want to share in your front-end code. Specified service overcome this by allowing sending only predefined templates, so for a "Share with a friend" feature you'd create a template called "share".

A: You can't do it purely through client side code.
You can do it with a server callback, AJAX.


text:
Q: Load Images from memory (libharu) from Magick++ images I am working on some pdf generation software in c++ based on libharu and I would like to be able to first manipulate images using Magick++ and then load them from memory using libharu function:
HPDF_LoadRawImageFromMem()

Which according to the documentation essentially load images from some void *buffer.
My goal is to be able to get this void* data out of a Magick::Image instance and load this image into my haru pdf based on this data.
I have tried writing to a void*or to a Magick::Blob but the only achievement I have had so far was some black rectangle instead of the image I am expecting.
Does anyone have any experience in converting Raw image data from one library into another one ?
The reason I am trying to do this from memory is because so far I am writing Magick::Image instances into a file and then reading from this file to load then in haru, which is a huge performance hit in the context of my Application.

A: I'm a little late to answer I guess, but here's a real-life answer.
I successfully added an itk::Image to my pdf using LibHaru so it should work about the same for you. First, you need to know if the library you use is row major or column major. LibHaru (and all the libraries I know) works in row major, so your library should too, or you will need to "transpose" your data.
// Black and white image (8 bits per pixel)
itk::Image<unsigned char, 2>::Pointer image = ...;
const unsigned char *imageData = image->GetBufferPointer();
const HPDF_Image image = HPDF_LoadRawImageFromMem(m_Document,
    imageData, width, height, HPDF_CS_DEVICE_GRAY, 8);

// Or color image (24 bits per pixel, 8 bits per color component)
itk::Image<RGBPixel, 2>::Pointer image = ...;
const RGBPixel *imageData = image->GetBufferPointer();
const HPDF_Image image = HPDF_LoadRawImageFromMem(m_Document,
    reinterpret_cast<const unsigned char *>(imageData),
    width, height, HPDF_CS_DEVICE_RGB, 8);

// Usual LibHaru code. EndText, Position, Draw, StartText, etc.
// This code should not be dependant on the type
InsertImage(image);

I think the only complicated part is the reinterpret_cast. The black and white image don't need one because it's already defined as byte. For example, if you have this image
102 255 255
 99 200   0
255   0 100
imageData == {102, 255, 255, 99, 200, 0, 255, 0, 100};

However, if you have this color image
(  0,   0, 255) (0, 255, 255) ( 42, 255, 242)
(200, 200, 255) (0, 199, 199) (190, 190, 190)
imageData == {0, 0, 255, 0, 255, 255, 42, 255, 242, 200, 200, 255, ... }

which LibHaru will inderstand because you tell him to use HPDF_CS_DEVICE_RGB, which means that it will group the data in (R, G, B).
Of course, using ImageMagick, you need to find how to access the first pixel. It's probably a method like data(), begin(), pointer(), etc.

A: Unfortunately I neither worked with ImageMagic nor libharu, however I have some experience with image processing and since nobody answered yet, maybe I can be of some help.
The problem is probably that there is a plethora of raw image formats and I'm quite sure that both libraries do not have the same understanding of these.  What makes things worse is that the raw image interpretation of libharu is virtually not documented. However the conclusions that libharu handles raw data quite straightforward can be drawn from the parameters of: "HPDF_LoadRawImageFromMem".
Width and Height are pretty much self-explanatory, with the only question of the used (probably pixels).  More interesting is: "bits_per_component".  This parameter probably describes how many bits are used to define one pixel (common values are 8: indexed from a palette of 256 values, 16: indexed from a palette of 65535 values, 24: one byte for red, green, and blue respectivly [RGB], 32: as 24 but with alpha channel or 8 bits for cyan, magenta, yellow, and black [CMYK], 36: as 32 but with 9 bit per value for easier transpostion...).  A problem is the lousy documentation of the type: HPDF_ColorSpace, since it probably describes how color values of with: "bits_per_component" are to be interpreted.
A totally different approach seems to be implemented by ImageMagic.  An image object seems to have always an image format (JPEG, PNG, GIF), therefore an image object probably never has a "straightforward" memory representation but is encoded.
My recommendation would be to switch the ImagaMagic image to the TIFF format, since it condones compression and therefore has a similar approach to the assumed raw interpretation by libharu.
Hope this helped at least a bit...
Cheers
             Mark.

A: It is never late to answer.
I have used a PNG blob as intermediate step:
Image image;
image.read("file.jpg");

Blob blob;
image.write(blob, "PNG");

HPDF_Image pdfImg = HPDF_LoadPngImageFromMem(doc, (const HPDF_BYTE*)blob.data(), blob.length());
HPDF_Page_DrawImage(doc, pdfImg, 0, 0, image.columns(), image.rows());

PDF document and page creation omitted for brevity.