text:
Q: HttpMessage.setMethod(HttpMessage.POST) is changed by GET, on BlockingSenderDestination I am trying to migrate a Blackberry application from OS 6 to OS 7 (my app currently works on OS 6). Theoretically it should not cause any problems, but I found an issue that I still cannot resolve. When executing calls to web services (SOAP), I'm setting the HttpMessages to use the POST method, but when the call is executed, it arrives at the server as a GET. This is a big problem for me because the Sever with which am working doesn't support GET's (always results in an "Http 500 error"). This issue doesn't occur on the simulator, just on the device.
Do you know any workaround for this? Is it a problem with OS version? (See below for the code that I'm using).
Device
Model: Bold 9930
Carrier: Sprint
OS: 7.0 Bundle 1296 (v7.0.0.241, Platform 5.0.0.442)
Simulator (On the simulator side I don't have any problems)
Model: Bold 9930
OS: 7.0 Bundle 1962(v7.0.0.440, Sept_24_2011_signed, Platform 4.0.0.141)
public void run() {
        context.setEnableBtnsend(false);
        BlockingSenderDestination blockSendDest = null;

        try {
            URI uri = URI.create(URL_BASE);
            blockSendDest
                = (BlockingSenderDestination) DestinationFactory.getSenderDestination(
                senderContext.getName(), uri);

            if (blockSendDest == null) {
                blockSendDest = DestinationFactory.createBlockingSenderDestination(
                    senderContext, uri);
            }

            ByteMessage requestMessage = blockSendDest.createByteMessage();
            requestMessage.setTransportHeader("Content-Type", "text/xml;charset=UTF-8");
            requestMessage.setTransportHeader("SOAPAction", "\"\"");
            // getBodyRequest() -> Insert SOAP request, works fine, was tested on SOAP UI
            requestMessage.setStringPayload(getBodyRequest());
            ((HttpMessage) requestMessage).setMethod(HttpMessage.POST);
            blockSendDest.resume();
            Message response = blockSendDest.sendReceive(requestMessage);

            if (response != null) {
                procesMessageResponse(response);
            }
            // ...
        }
        catch (Exception ex) {
             handleException(ex);
        }


text:
Q: Dividing a geographic region I have a certain geographic region defined by the bottom left and top right coordinates. How can I divide this region into areas of 20x20km. I mean in practial the shape of the earth is not flat it's round. The bounding box is just an approximation. It's not even rectangular in actual sense. It's just an assumption. Lets say the bottomleft coordinate is given by x1,y1 and the topright coordinate is given by x2,y2, the length of x1 to x2 at y1 is different than that of the length between x1 to x2 at y2. How can I overcome this issue
Actually, I have to create a spatial meshgrid for this region using matlab's meshgrid function. So that the grids are of area 20x20km.
meshgrid(x1:deltaY:x2,y1:deltaX:y2)

As you can see I can have only one deltaX and one deltaY. I want to choose deltaX and deltaY such that the increments create grid of size 20x20km. However this deltaX and deltaY are supposed to vary based upon the location. Any suggestions?
I mean lets say deltaX=del1. Then distance between points (x1,y1) to (x1,y1+del1) is 20km. BUt when I measure the distance between points (x2,y1) to (x2, y1_del1) the distance is < 20km. The meshgrid function above does creates mesh. But the distances are not consistent. Any ideas how to overcome this issue?
For finding point p(1,0)
deg = km2deg(20)

deg =

    0.1799

>> reckon(25,-120,0.1799,-18)

ans =

   25.1711 -120.0614

Function to calculate distance between two points
function [ distance ] = calculateDistance( latitude1,longitude1,latitude2,longitude2 )
radius = 6371;
dLat = degtorad(latitude2-latitude1);
dLon = degtorad(longitude2-longitude1);
a = sin(dLat/2) * sin(dLat/2) + cos(degtorad(latitude1)) * cos(degtorad(latitude2)) * sin(dLon/2) * sin(dLon/2);
c = 2 * atan2(sqrt(a), sqrt(1-a));
distance = radius * c;
end

Referring to whuber's suggestions
syms p(1,1).lat p(1,1).lon
solve ( calculateDistance(p(0,1).lat,p(0,1).lon,p(1,1).lat,p(1,1).lon), calculateDistance(p(1,0).lat,p(1,0).lon,p(1,1).lat,p(1,1).lon))

A: This can be accomplished in the same way we would lay out a grid of squares in the plane:

*

*Lay off a baseline in any direction.  Mark it off in equal increments (of 20 km).  Call these points p(0,0), p(0,1), ..., p(0,n), in order.  It does not have to be geodesically straight, but it should be close to straight.

*Starting with the first marked point p(0,0), choose a direction beta not parallel to the baseline (perhaps perpendicular to the baseline, for instance). Move 20 km in that direction and stop.  Call this point p(1,0).

*Begin with the first two points on the baseline, p(0,0) and p(0,1).  There will be two locations that are 20 km from each of p(0,1) and p(1,0): these are the intersections of circles of radius 20 km centered at p(0,1) and p(1,0).  One of these points, by construction, is p(0,0).  Define p(1,1) to be the other point.
Iteratively determine p(1,j), j = 2, ..., n, in this fashion.

*Repeating steps 2 and 3, iteratively determine as many rows as desired, using the most recent row p(i,0), p(i,1), ..., p(i,n) as the baseline and keeping beta constant (at least approximately).
Retain only those grid points falling within one's region of interest.
The earth's curvature begins having a pronounced effect on grids more than a thousand kilometers on a side (or so).  To illustrate this, here is a grid with 400 km spacing constructed to cover the conterminous United States.

This is a Mercator projection.  The baseline of the grid is the bottom row of points, starting at (lat, lon) = (25, -120) and proceeding along the geodesic oriented 89.5 degrees east of north.  The angle 'beta' is 18 degrees west of north: that determines the orientation of the left side of the grid.
(There's a limit to how far one can go with this approach: eventually such grids will wrap around the globe and return to cover the same areas.  They will never match up unless they are extremely large (and effectively create a cube, octahedron, or prism).)

Note that apart from the aforementioned exceptions, it is impossible to create a grid of congruent squares (or any other shape) on the sphere (or any ellipsoid).  This is because the congruencies would generate a discrete subgroup of the group of rotations of space and those subgroups correspond to the five Platonic solids, prisms, and pyramids.  So, something has to give: if you want the grid cells to have equal areas or equal angles, the lengths of their sides must vary; if you want the side lengths to be the same, then the areas and angles must vary.  This is why the cell shapes appear so distorted and non-square in the figure: such distortion is unavoidable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Proving that ${{X}_{m}}=\{P\in {{k}^{n}}\left| {{f}_{1}}(P)=...={{f}_{m-1}}(P)=0 \;\;\hbox{and} \;\; {{f}_{m}}(P)=1\} \right. $ is eventually empty. We consider a field $k$, $n \in \mathbb{N}$ and ${{f}_{1}},{{f}_{2}},...\in k[{{x}_{1}},...,{{x}_{n}}]$. For every integer $m\ge 2$, we define ${{X}_{m}}=\{P\in {{k}^{n}}\left| {{f}_{1}}(P)=...={{f}_{m-1}}(P)=0 \;\;\hbox{and} \;\; {{f}_{m}}(P)=1\}. \right.$
I need to show that there exists an integer $N$ such that ${{X}_{m}}=\varnothing $ for every $m \ge N$.
I encountered this problem in a course of commutative algebra, in the chapter of Noetherian rings.
First, I suspected that I should use the property "every increasing sequence of ideals is eventually constant", which characterizes a Noetherian Ring, but I am not very sure.
Any help would be greatly appreciated.

A: For $m \geq 1$, let $ I_m $ be the ideal generated by $f_1, f_2, \dots, f_m$. These ideals form an ascending sequence
$$I_1 \subseteq I_2 \subseteq I_3 \subseteq \cdots$$
which must stabilise since $k[x_1, \dots, x_n]$ is Noetherian. Let $N$ be minimal such that $I_{N-1} = I_N$. We find in particular that, for all $m \geq N$, we have $f_m \in I_{N-1}$,which can be rephrased as $f_m = \sum_{r=1}^{N-1} \lambda_r f_r$ for some $\lambda_r \in k[x_1, \dots, x_n]$.
Observe that if $P \in k^n$ satsifies $$f_1(P) = f_2(P) = \cdots f_{N-1}(P) = 0$$
then, for $m \geq N$, we have
$$f_m(P) = \sum_{r=1}^{N-1} \lambda_r f_r(P) = \sum_{r=1}^{N-1} \lambda_r(P) \cdot 0 = 0\text{.}$$
Let $m \geq N$ and suppose for contradiction that there exists $P \in X_m$. By definition of $X_r$ we have $f_r(P)=0$ for all $1 \leq r \leq N-1$ which, by the preceding, implies $f_m(P)=0$. Yet $f_m(P)=1$, again from the definition of $X_m$. This is absurd. We conclude that $X_m = \emptyset$ for all $m \geq N$, as desired.


text:
Q: Create user to MySQL with ssh I'm trying to create an mysql user from ssh with this command :
sshpass -p "PASSWORD" ssh -t -o StrictHostKeyChecking=no USER@IP "echo "CREATE USER 'NAME'@'localhost' IDENTIFIED BY 'MDP'" | mysql"

but it's not working
ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'MDP' at line 1

An idea ?

A: The problem is you seem to be using double-quotes inside a double-quoted string:
sshpass -p "PASSWORD" ssh -t -o StrictHostKeyChecking=no USER@IP "echo "CREATE USER 'NAME'@'localhost' IDENTIFIED BY 'MDP'" | mysql"
                                                                 ^     ^

I indicated two points in the above line. The first one opens a double-quoted string. I think you believe the second one will open another double-quoted string, but in fact it terminates the first double-quoted string.
Quoting is a tricky thing in shell languages.
I'd suggest this alternative:
echo "CREATE USER 'NAME'@'localhost' IDENTIFIED BY 'MDP'" | sshpass -p "PASSWORD" ssh -t -o StrictHostKeyChecking=no USER@IP "mysql"

With this alternative, there are no double-quoted strings inside double-quoted strings.
I am not familiar with sshpass so I don't know if it changes this, but in general you can pipe input to ssh and have it become the input to the command run remotely (in this case, mysql).


text:
Q: How to count the number of rotation of an object having a pseudo-circular movement from it's coordinates (t, X, Y) So I have an object that has a pseudo-ciruclar movement (EDIT : with a non constant period). I'm filming it with a 30 fps camera, and I extract it's position X and Y every 3 frame. Moreover, the center of this circular movement is moving.
Entry Data :

*

*Frame, a list

*X and Y, 2 lists

To Frame[i], the position of the object is X[i] and Y[i].
If you wanna see what it looks likes (30 mn video) :

Moreover, my data has "gaps", sometime, I can get for instance from frame 600 to 690, because the object wasn't correctly detected in my video. The data is already filter with a first order low-pass filter (after being interpolate by segments).
My problem, is that I can't find a good algorithm to count the number of rotation, without too many variability.
Current algorithm using the pseudo-periodicity of X and Y:
for length = 200, 400, 600, 800, 1000 and 1200 :
    I cut my data (X and Y) in segments of size : length.
    for each segments cutted :
        Mean_X = Mean value of X on the segment
        Mean_Y = Mean value of Y on the segment

        If I get above Mean_X, X_counter += 1, and then I skip the following points until I get under Mean_X.
        Same with Y_counter.

    I sum the counted number of rotation on each segments for the current length to get the number of rotation on the complete duration.

In 2 list, ResX and ResY, I store the counted number of rotation for every length. To resX[i] correspond the length i.
For instance resX[2] give the number counted for length : 600.

But the results on X and Y are different, and have an high variability depending of the length chosen.
So how to choose the real number of rotation on the duration ?

Calculation of the difference of counted number between X and Y for every length.

Then I choose the average of counted X and Y, where there is the smaller difference.

In Python :
    # Découpage en segment de 200 à 1200 de longueur avec un pas de 200
    Segments = range(200, 1400, 200)

    ResX, ResY = [], []

    for k in range(len(Segments)):
        if Segments[k] < len(X):
            X_calc, Y_calc = [], []
            length = len(X) // Segments[k]
            last = len(X) % Segments[k]

            for j in range(length):
                X_calc.append(X[j:j + Segments[k]])
                Y_calc.append(Y[j:j + Segments[k]])

            if last > Segments[k] //2:
                X_calc.append(X[len(X) - last:])
                Y_calc.append(Y[len(Y) - last:])

            else:
                X_calc[len(X_calc) - 1] = X_calc[len(X_calc) - 1] + X[len(X) - last:]
                Y_calc[len(Y_calc) - 1] = Y_calc[len(Y_calc) - 1] + Y[len(Y) - last:]

            # Initialisation of the counter
            Kx = 0
            Ky = 0

            for j in range(len(X_calc)):

                Counter = 0
                b = 0
                Moyenne = np.mean(X_calc[j])
                while b < len(X_calc[j]):
                    if X_calc[j][b] <= Moyenne + 10:
                        b += 1
                        continue
                    else:
                        Counter += 1
                        while X_calc[j][b] >= Moyenne + 10:
                            b += 1
                            try:
                                X_calc[j][b]
                            except:
                                break
                Kx += Counter

                Counter = 0
                b = 0
                Moyenne = np.mean(Y_calc[j])
                while b < len(Y_calc[j]):
                    if Y_calc[j][b] <= Moyenne + 10:
                        b += 1
                        continue
                    else:
                        Counter += 1
                        while Y_calc[j][b] >= Moyenne + 10:
                            b += 1
                            try:
                                Y_calc[j][b]
                            except:
                                break

                Ky += Counter

            ResX.append(Kx)
            ResY.append(Ky)

    # Maintenant on détermine le nombre de tour en comparant les résultats locaux en X et en Y
    Diff = []

    for j in range(len(ResX)):
        Diff.append(abs(ResX[j] - ResY[j]))

    ID = Diff.index(min(Diff))

    Res_F = int((ResX[ID] + ResY[ID]) /2)

This current solution has an high variability depending on :

*

*The length

*The "Count Above Value" : If I take Mean(X) or Mean(X) + 10, I get completely different results.

Do you know anyway to reduce this variability ? Or an idea on an algorithm to count the rotation ? Or a way to combine X and Y before the counting ?
Since a rotation with (t = 0, X = 1, Y = 0) can be describe by X = cos(t) and Y = sin(t), I thought there could be a way to sum or multiply X and Y in order to analyze a linear combination of X and Y.


text:
Q: {subscribe / subscribe to / subscribe for}
I subscribe to the book called Pride and Prejudice.
  I subscribe for the book called Pride and Prejudice.
  I subscribe the book called Pride and Prejudice.

What is the difference?


text:
Q: JAVA: Type parameter hiding class type I have this
abstract class Operand {
    public abstract <T extends Operand> Operand operation(Operator operator, T operand);
}
abstract class Numeric extends Operand {
}
class Integer extends Numeric
    @Override
    public <Integer> Operand operation(Operator operator, Integer operand) {//problem
    }
}

How can I solve this situation?
I don't want to use generics in the class Operand (so I have Operand) because I need Operand to be a single type. Inside the Integer's method I need to call the constructor (new Integer(arg)), a solution could be to call that method in some other way.
Solutions?

A: Try with overloaded method
abstract class Operand {
    public abstract <T extends Operand> Operand operation(Operator operator, T operand);
}

abstract class Numeric<T extends Numeric<T>> extends Operand {
    public abstract Operand operation(Operator operator, T operand);
}

class Integer extends Numeric<Integer> {

    @Override
    public Operand operation(Operator operator, Integer operand) {
        // add your Integer specific code here
        return null; // replace null with actual returned value
    }

    @Override
    public <T extends Operand> Operand operation(Operator operator, T operand) {
        // simply call to overridden Integer specific method
        // no harm to downcast it here
        return operation(operator, (Integer) operand);
    }

}

A: The issue is your method declaration in Operand, which is <T extends Operand>, you must match that "contract" with your implementation -
class Integer extends Numeric {
  @Override
  public <T extends Operand> Operand operation(Operator operator, T operand) {
    // Like this....
  }
}

A: It seems to me you want something like this:
abstract class Operand<T, U> {
    public abstract T operation(Operator operator, U operand);
}
abstract class Numeric<T, U> extends Operand<T, U> {
}
class Integer extends Numeric<Integer, Integer>
    @Override
    public Integer operation(Operator operator, Integer operand) {
    }
}


text:
Q: Concatenate multiindex daframe with series I have a multiindex dataframe that contains the features for training a machine learning model.
X_train

win      -1           0           1
res       A     B     A     B     A     B
id  pos
foo 0     0.1   0.2   0.3   0.1   0.5   0.6
    1     0.3   0.7   0.2   0.1   0.4   0.6
    2     0.1   0.2   0.3   0.1   0.5   0.6
bar 0     0.1   0.0   0.3   0.1   0.5   0.6
    1     0.1   0.2   0.0   0.3   0.9   0.6
    2     0.1   0.2   0.3   0.1   0.5   0.6

And a pandas series (or dataframe) with the class labels
y_train

id  pos
foo 0     0
    1     2
    2     1
bar 0     0
    1     0
    2     1
Name: Class

I want to concatenate them and obtain
full_train

win      -1           0           1          Class
res       A     B     A     B     A     B
id  pos
foo 0     0.1   0.2   0.3   0.1   0.5   0.6  0
    1     0.3   0.7   0.2   0.1   0.4   0.6  2
    2     0.1   0.2   0.3   0.1   0.5   0.6  1
bar 0     0.1   0.0   0.3   0.1   0.5   0.6  0
    1     0.1   0.2   0.0   0.3   0.9   0.6  0
    2     0.1   0.2   0.3   0.1   0.5   0.6  1

But if I do full_train = pd.concat([X_train, y_train], axis=1), I obtain:
          (-1,A)(-1,B)(0,A) (0,B)(1,A) (1,B) Class
id  pos
foo 0     0.1   0.2   0.3   0.1   0.5   0.6  0
    1     0.3   0.7   0.2   0.1   0.4   0.6  2
    2     0.1   0.2   0.3   0.1   0.5   0.6  1
bar 0     0.1   0.0   0.3   0.1   0.5   0.6  0
    1     0.1   0.2   0.0   0.3   0.9   0.6  0
    2     0.1   0.2   0.3   0.1   0.5   0.6  1

Is it possible to obtain my expected output? Does Pandas support this kind of mixed columns being both multiindex and singleindex?

A: Pandas does support this! However there's some roundabout under the hood knowledge you'll need to know for concatenation to get this to work as expected.
For the below examples I'll be using this dataframe and this series y_train:
import pandas as pd
import numpy as np

columns = pd.MultiIndex.from_product([[-1, 0, 1], ["A", "B"]], names=["win", "res"])
index = pd.MultiIndex.from_product([["foo", "bar"], [0, 1, 2]], names=["id", "pos"])

m = len(columns)
n = len(index)

data = np.random.randint(5, size=(m * n)).reshape(m, n)
df = pd.DataFrame(data, index=index, columns=columns)

print(df)
win     -1     0     1
res      A  B  A  B  A  B
id  pos
foo 0    3  4  4  4  4  1
    1    4  1  4  3  1  0
    2    0  4  2  2  3  2
bar 0    3  2  1  4  1  1
    1    0  3  1  1  0  3
    2    2  0  2  1  0  1

Labels:
y_train = pd.Series(np.random.randint(3, size=m), index=index, name="class")

print(y_train)
id   pos
foo  0      2
     1      1
     2      2
bar  0      1
     1      1
     2      2
Name: class, dtype: int32

If your y_train is a Series, you don't need to use concat at all. The most straightforward method is to simply assign your y_train series into the original dataframe.
new_df = df.copy() # preserving original dataframe for use in later examples
new_df["class"] = y_train

print(new_df)
win     -1     0     1    class
res      A  B  A  B  A  B
id  pos
foo 0    3  4  4  4  4  1     2
    1    4  1  4  3  1  0     1
    2    0  4  2  2  3  2     2
bar 0    3  2  1  4  1  1     1
    1    0  3  1  1  0  3     1
    2    2  0  2  1  0  1     2

# We can select our "class" column and get its `Series` out via:
print(new_df["class"])

id   pos
foo  0      2
     1      1
     2      2
bar  0      1
     1      1
     2      2
Name: class, dtype: int32

# Then to access our other columns, we'll need to supply a key as a tuple:
print(new_df[(-1, "A")])

id   pos
foo  0      4
     1      1
     2      4
bar  0      2
     1      3
     2      0
Name: (-1, B), dtype: int32

Now things get a little trickier if your y_train is a dataframe instead of a Series. However this approach also solves your concat question as well. All you need to do is replace your label dataframe's (y_train) column index with a MultiIndex that has the same number of levels with the other dataframe you're attempting to concatenate with. You'll need to use empty levels to achieve this (an empty level is a level whose only value is an empty string. NOT None or NaN)
new_ytrain = y_train.to_frame() # promote y_train to a dataframe

# In order to feed this into concat, we'll need to give our dataframe a columnar multiindex
# This multiindex essentially has an empty second level
new_ytrain.columns = pd.MultiIndex.from_product([new_ytrain.columns, [""]])

print(new_ytrain)
        class

id  pos
foo 0       2
    1       1
    2       2
bar 0       1
    1       1
    2       2

In the representation of our y_train dataframe, you'll see a space between our column titles and the actual data. This represents the empty levels we've inserted. Now that both our original dataframe and our y_train have a columnar MultiIndex with 2 levels, we can use concat as expected with no issues:
out = pd.concat([df, new_ytrain], axis=1)

print(out)
win     -1     0     1    class
res      A  B  A  B  A  B
id  pos
foo 0    3  4  4  4  4  1     2
    1    4  1  4  3  1  0     1
    2    0  4  2  2  3  2     2
bar 0    3  2  1  4  1  1     1
    1    0  3  1  1  0  3     1
    2    2  0  2  1  0  1     2

Like with the assignment approach, we can select our "class" column in this dataframe easily.
print(out["class"])

id   pos
foo  0      2
     1      1
     2      2
bar  0      1
     1      1
     2      2
Name: class, dtype: int32


text:
Q: How to create a simplex algorithm table I am trying to create a table that can have user input. I want to have a table with boxes instead of asking the user for a list of numbers, they can just input a lot of numbers into the table. Right now I have a list of variables and it is asking for user input for all of the variables.
I want it to look a bit like this with some sort of way to input the numbers.
https://imgur.com/a/leUICVS
Here is my code so far. It isn't very good. There is probably a much easier way to do it.
row1X1=input("what is row1X1?: ")

row1X2=input("What is row1X2: ")

row1X3=input("what is row1X3?: ")

row1S1=input("What is row1S1: ")

row1S2=input("what is row1S2?: ")

row1Z=input("What is row1Z: ")

row1Equal=input("What is the equals: ")

row2X1=input("what is row2X1?: ")

row2X2=input("What is row2X2: ")

row2X3=input("what is row2X3?: ")

row2S1=input("What is row2S1: ")

row2S2=input("what is row2S2?: ")

row2Z=input("What is row2Z: ")

row2Equal=input("What is the equals: ")

row3X1=input("what is row3X1?: ")

row3X2=input("What is row3X2: ")

row3X3=input("what is row3X3?: ")

row3S1=input("What is row3S1: ")

row3S2=input("what is row3S2?: ")

row3Z=input("What is row3Z: ")

row3Equal=input("What is the equals: ")

{

print(row1X1, row1X2, row1X3, row1S1, row1S2, row1Z, row1Equal)

print(row2X1, row2X2, row2X3, row2S1, row2S2, row2Z, row2Equal)

print(row3X1, row3X2, row3X3, row3S1, row3S2, row3Z, row3Equal)
}

I eventually want to be able to input numbers and then have the program pivot the table based on the most negative number in the bottom row. I am not sure how to go about doing this, however.

A: What you've asked for here is a GUI.  In Python, that's done with tools like Tkinter or Qt or wxWidgets, but that's a huge problem.  Surely, for now, the best plan is you have your users enter their data in a text file with a simple text editor, then have your program read that file.  Then you can concentrate on the math.


text:
Q: Merge 2 xml files using XSLT in unix I have 2 XML files as shown below:
File1.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Schedule name="myOffice">
  <taskItem taskId="1" startDate="2013-01-01" stopDate="2037-12-31">
    <measurements>
      <measurement>USD</measurement>
    </measurements>
    <timings>
      <period day="0" duration="0" hour="0" interval="28" minutes="0"/>
    </timings>
  </taskItem>
  <taskItem taskId="2" startDate="2013-01-01" stopDate="2037-12-31">
    <measurements>
      <measurement>Rupee</measurement>
    </measurements>
    <timings>
      <period day="0" duration="0" hour="0" interval="15" minutes="0"/>
    </timings>
  </taskItem>
</Schedule>

File2.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Schedule name="myOffice">
  <taskItem taskId="1" startDate="2015-12-01" stopDate="2037-12-31">
    <measurements>
      <measurement>Rupee</measurement>
    </measurements>
    <timings>
      <period day="5" duration="10" hour="0" interval="20" minutes="0"/>
    </timings>
  </taskItem>
</Schedule>

I am using XSLT to get the following output:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Schedule name="myOffice">
  <taskItem taskId="1" startDate="2013-01-01" stopDate="2037-12-31">
    <measurements>
      <measurement>USD</measurement>
    </measurements>
    <timings>
      <period day="0" duration="0" hour="0" interval="28" minutes="0"/>
    </timings>
  </taskItem>
  <taskItem taskId="2" startDate="2013-01-01" stopDate="2037-12-31">
    <measurements>
      <measurement>Rupee</measurement>
    </measurements>
    <timings>
      <period day="5" duration="10" hour="0" interval="20" minutes="0"/>
    </timings>
  </taskItem>
</Schedule>

But getting this as output:
<Schedule name="myOffice">
  <taskItem taskId="1" startDate="2015-12-01" stopDate="2037-12-31">
    <measurements>
      <measurement>Rupee</measurement>
    </measurements>
    <timings>
      <period day="5" duration="10" hour="0" interval="20" minutes="0"/>
    </timings>
  </taskItem>
</Schedule>

I am not able to get where I am lagging....
My idea is, based on field Measurement, I have to update attributes stopDate in taskItem, and day,duration,hour,interval,minutes in period tag.
My XSLT file is
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes" omit-xml-declaration="yes"/>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="taskItem//measurement">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()" />
      <xsl:apply-templates
        select="document('file1.xml')
              /Schedule/taskItem/timings/period[@day = current()/../../timings/period/@day and
                                                @duration = current()/../../timings/period/@duration and
                                                @hour = current()/../../timings/period/@hour and
                                                @interval = current()/../../timings/period/@interval and
                                                @minutes = current()/../../timings/period/@minutes]/*" />
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

I am executing the command in unix as follows:
xsltproc xs.xslt file2.xml

A: I think you want to do:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" omit-xml-declaration="yes"/>

<xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
</xsl:template>

<xsl:template match="timings">
    <xsl:variable name="match" select="document('file2.xml')/Schedule/taskItem[measurements/measurement=current()/../measurements/measurement]/timings"/>
    <xsl:choose>
        <xsl:when test="$match">
            <xsl:copy-of select="$match"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:copy-of select="."/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

</xsl:stylesheet>

and specify file1.xml as the file to be processed.

A: This is my (verbose) solution from what I understood. I explicitly update each attributes/fields so you can tweak this solution to adapt it to your needs. The taskId and startDate from the taskItem are taken from file1.xml. The stopDate and timings are take from file2.xml. You must call this XSLT sheet with file1.xml as parameter.
 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes" omit-xml-declaration="yes"/>
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
  </xsl:template>
  <!-- For all taskItem in file1.xml -->
  <xsl:template match="taskItem">
    <!-- Get all taskItems from file2.xml -->
    <xsl:variable name="tiother" select="document('file2.xml')/Schedule/taskItem" />
    <!-- Get measurement text from current and other taskItems (from file1.xml and file2.xml) -->
    <xsl:variable name="namethis" select="./measurements/measurement/text()" />
    <xsl:variable name="nameother" select="$tiother/measurements/measurement/text()" />
    <xsl:choose>
      <!-- if the measurement texts are the same -->
      <xsl:when test="$namethis = $nameother">
        <!-- Yes ? create a new taskItem updated -->
        <xsl:element name="taskItem">
          <!-- Get taskId from the current task item (the one in file1.xml) -->
          <xsl:attribute name="taskId"><xsl:value-of select="./@taskId"/></xsl:attribute>
          <!-- Get startDate from the current task item (the one in file1.xml) -->
          <xsl:attribute name="startDate"><xsl:value-of select="./@startDate"/></xsl:attribute>
          <!-- Get stopDate from the other task item (the one in file2.xml) -->
          <xsl:attribute name="stopDate"><xsl:value-of select="$tiother/@stopDate"/></xsl:attribute>
          <!-- Get the measurements from the current task item (the one in file1.xml) -->
          <xsl:copy-of select="./measurements"/>
          <!-- Get the timings from the other task item (the one in file2.xml) -->
          <xsl:copy-of select="$tiother/timings"/>
        </xsl:element>
      </xsl:when>
      <xsl:otherwise>
        <!-- No ? just copy the current taskItem -->
        <xsl:copy-of select="."/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
</xsl:stylesheet>


text:
Q: $data['main_content'] to load view in subfolder in CodeIgniter Here is my function:
function single_resonator() {
            $data['title'] = 'Single Resonator Operating Parameters';
            $data['main_content'] = 'products/single_res_view';
            $this->load->view('templates/main.php', $data);
        }

But the single_res_view doesn't load if it is in the products folder in the views folder.  How do I accomplish this?  I tried a file called MY_router.php from a post elsewhere on this site and it didn't help.  CI will only load the single_res_view if it is in the root of the views folder.
Here is templates/main.php
<?php $this->load->view('includes/header.php'); ?>

<?php $this->load->view('includes/nav.php'); ?>

<?php $this->load->view($main_content); ?>

<?php $this->load->view('includes/footer.php'); ?>

A: Have you tried this:
$data['main_content'] = 'products/single_res_view.php';

If not, can you triple check that the path and file names are correct? Otherwise, can you echo the value of $main_content just in case you're overwriting it somewhere?


text:
Q: Can I search by a reference name, solution-wise, to see in which projects it was referenced? Is there any possibiliy to searh the whole solution to see a particular refrence's usage?
Let's say, can I see in what projects the reference "Xyxyxyxy.dll" is referenced?
(ReSharper based answers are also acceptable! :) )
Thanks!

A: You can do this through notepad++ quite easily by giving the solution directory and *.csproj as the filter i.e. searching the csproj files for the references.

*

*In case you want to search for GAC assembly references, search for the following string
<Reference Include="System.Data" /> where System.Data is the assembly name

*In case you want to search for a non GAC referenced assembly then search for the following string
<Reference Include="WindowsFormsApplication2, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">

A: You can use Project Hierarchy feature of ReSharper to see back and forward reference links. Right click your reference or project, choose Project Hierarchy.

A: Devendra's answer already shows how you can get an answer to the question by doing a simple text search. I thought it might be worth showing that you can do the same thing using only PowerShell (in case you don't have an editor other than Visual Studio installed):
gci -Recurse -Filter '*.csproj' |
    where { $_ | sls '<Reference.*"System\.Data("|,)' } |
    select -ExpandProperty Name

Replace System\.Data with the full name of the assembly you're searching for.


text:
Q: Sickness expressions Why when we have a fever we say

I have a fever.

But when I have diarrhea we say

I have diarrhea.

Why don't we say

I have a diarrhea.

Is there any rule? If I come across a new symptom, how do I decide whether to add "a" or not adding it into my sentence?

A:
I have diarrhea.

is correct. Disease names do not use an article (for example cancer, diabetes, hepatitis, pneumonia, etc).

I have a fever.

Descriptive conditions do (for example headache, broken arm, strained back, etc.)

A: Yes, there's a rule.With a plural (countable) noun you should use an article. The first noun is countable in this meaning (if you aren't sure,consult a good dictionary).The second noun is a mass noun.You don't need an article here.


text:
Q: Postgres schema add column condition Im using postgres and would like to add a condition to a column in my table schema.
Suppose if have the following table
CREATE TABLE people (
  ID  SERIAL PRIMARY KEY,
  NAME varchar(20) NOT NULL,
  ADDRESS varchar(50)
)

Im trying to figure out how I can update this schema so if an update happens, if the ADDRESS column is not null DON'T overwrite it. Basically only update that column ONLY if it's null or empty and ignore the new value being passed in with the next update.
Any help appreciated
What Iv tried so far
update people
set name = 'John', address = '12 Oak road, Hong Kong'
where id = 1;

CREATE OR REPLACE FUNCTION check_address() RETURNS TRIGGER AS
$BODY$
BEGIN
  IF (TG_OP='UPDATE') THEN
      IF OLD.address is not NULL THEN
        NEW.address = OLD.address;
      END IF;
  END IF;
  RETURN NULL;
END;
$BODY$
  LANGUAGE plpgsql;

CREATE TRIGGER tr_check_address
BEFORE update
on people
EXECUTE PROCEDURE check_address();

The above trigger returns an error after I run the update...
SQL Error [55000]: ERROR: record "old" is not assigned yet

A: The functionality you describe could be achieved by writing a trigger.
https://www.postgresql.org/docs/current/sql-createtrigger.html


text:
Q: How to undo a ParseUser.setPassword() call? I am letting the user change his credentials.
He types new username, email and password and I go like:
ParseUser user = ParseUser.getCurrentUser();
user.setUsername("MY NEW NAME");
user.setEmail(email);
user.setPassword("MY NEW PW");
user.saveInBackground(...);

So what? So this save() call might fail, for a big number of reasons (example: username already taken by someone else). I can tell that in this case none of the above fields gets updated, which is fair: I show an error, user knows that all went wrong.
Things get complicated if you notice that, even after the ParseException, the user above keeps its dirty fields, which couldn't be saved to the server. I.e.
//saveInBackground fails
//...
user.getUsername().equals("MY NEW NAME") // true!

Issue
Now, I am able to get these fields back to the right values by calling user.fetch(), but this doesn't work with the password field.
This is particularly unwanted, because any future call to save() or such (which might not fail because maybe it's a completely different call) will update the password too! I.e.
//later
ParseUser user = ParseUser.getCurrentUser();
user.put("stuff");
user.save();

This won't only put "stuff", but also change the password to "MY NEW PW".. without the user ever knowing.
Is there any way to reset the local password field, other than fetch() which doesn't work? I know I could save username, email and password with three different queries but that is not a possible solution for my case.

A: A workaround could be to use
+ becomeInBackground:

on PFUser class (with PFUser.currentUser().sessionToken as token) when save fails, but that is still a risk for becomeInBackground to fail.
It could at least prevent some cases to happend if becomeInBackground effectively undoes setPassword, and accepts current sessionToken as parameter, I haven't tested that

A: Looking at the newest release I've read in the changelog:

V1.10.2 — SEPTEMBER 15, 2015
New: Added ParseObject.revert() and revert(key) to allow reverting
  dirty changes

Looks like this could be it. It was definitely needed.

A: If it was my problem I would try to create an oldUser first and save all current data to it, then when failing, it would be time to change every thing back to normal value, or if success it is time to kill oldUser. Hope it may help.

A: The password plain text is not stored in Parse and as such it cannot be obtained by your app. Found it here https://www.parse.com/questions/get-current-users-password-to-compare-it-with-a-string
If you want to change password you can use ParseUser.requestPasswordResetInBackground() so you will change the password with the help of email.
But if you need to get password really hard, you can store it in the SharedPreferences after the login.

A: After some test and check, here are some conclusion.

*

*In parse, "password" is a special field, you cannot access it by ParseUser, That is way ParseUser have setPassword() but haven't getPassword() method

*Even in back-stage management [Core] - [Data] - [User], you can see "password" field is Hidden

*That is why fetch() method cannot recover original "password" value

So, I think if want implements above you need, try this way
// First time register //
ParseUser user = ParseUser.getCurrentUser();
user.setUsername("MY NAME");
user.setEmail(email);
user.setPassword("MY PW");
user.put("_password", "MY PW");
// The key can't use "password", this's reserve key word in Parse //
user.saveInBackground(...);

// Next time update //
user.setUsername("MY NEW NAME");
user.setPassword("MY NEW PW");
user.saveInBackground(...);

// if have something exception //
user.fetch();
// user.setPassword(user.get("_password"));
user.save();
ParseUser.login("MY NAME", "MY PW"); // Error
ParseUser.login("MY NAME", "MY NEW PW"); // Ok

user.fetch();
user.setPassword(user.get("_password"));
user.save();
ParseUser.login("MY NAME", "MY PW"); // OK


text:
Q: Using a temporary table to replace a WHERE IN clause I've got the user entering a list of values that I need to query for in a table. The list could be potentially very large, and the length isn't known at compile time. Rather than using WHERE ... IN (...) I was thinking it would be more efficient to use a temporary table and execute a join against it. I read this suggestion in another SO question (can't find it at the moment, but will edit when I do).
The gist is something like:
CREATE TEMP TABLE my_temp_table (name varchar(160) NOT NULL PRIMARY KEY);

INSERT INTO my_temp_table VALUES ('hello');
INSERT INTO my_temp_table VALUES ('world');
//... etc

SELECT f.* FROM foo f INNER JOIN my_temp_table t ON f.name = t.name;

DROP TABLE my_temp_table;

If I have two of these going at the same time, would I not get an error if Thread 2 tries to create the TEMP table after Thread 1?
Should I randomly generate a name for the TEMP table instead?
Or, if I wrap the whole thing in a transaction, will the naming conflict go away?
This is Postgresql 8.2.
Thanks!

A: There is no need to worry about the conflict.
The pg_temp schema is session specific. If you've a concurrent statement in a separate session, it'll use a different schema (even if you see it as having the same name).
Two notes, however:

*

*Every time you create temporary objects, the system catalog creates a temporary schema and the objects themselves. This can lead to clutter if used frequently.
Thus, for small sets/frequent uses, it's usually better stick to an in or a with statement (both of which Postgres copes quite well with). It's also occasionally useful to "trick" the planner into using whichever plan you're seeking by using an immutable set returning function.

*In the event you decide to actually use temporary tables, it's usually better to index and analyze them once you've filled them up. Else you're doing little more than writing a with statement.

A: Consider using WITH query insteed: http://www.postgresql.org/docs/9.0/interactive/queries-with.html
It also creates temporary table, which is destroyed when query / transaction finishes, so I believe there should be no concurrency conflicts.


text:
Q: Process finished with exit code 0 I have this:
import  math
class Point:
    def move(self, x, y):
        self.x = x
        self.y = y
def reset(self):
    self.move(0, 0)
def calculate_distance(self, other_point):
    return math.sqrt(
(self.x - other_point.x)**2 +(self.y - other_point.y)**2)
# how to use it:
    point1 = Point()
    point2 = Point()
    point1.reset()
    point2.move(5,0)
    print(point2.calculate_distance(point1))
    assert (point2.calculate_distance(point1) ==   point1.calculate_distance(point2))
    point1.move(3,4)
    print(point1.calculate_distance(point2))
    print(point1.calculate_distance(point1))

So I expect that it prints like this:
5.0
4.472135955
0.0

But In pycharm in the console it only prints this:
Process finished with exit code 0

Where you can see the output?
I also add a attachment for clearness.
Thank you

A: The problem is that reset and calculate_distance functions aren't in the Point class because of lack of indentation.
Try this. Now the functions are methods for Point class and all is working properly:
import  math

class Point:

    def move(self, x, y):
        self.x = x
        self.y = y

    def reset(self):
        self.move(0, 0)

    def calculate_distance(self, other_point):
        return math.sqrt((self.x - other_point.x)**2 +(self.y - other_point.y)**2)

# how to use it:
point1 = Point()
point2 = Point()
point1.reset()
point2.move(5,0)
print(point2.calculate_distance(point1))
assert (point2.calculate_distance(point1) ==   point1.calculate_distance(point2))
point1.move(3,4)
print(point1.calculate_distance(point2))
print(point1.calculate_distance(point1))

A: There is a window called "python console". The output of your script should be there...


text:
Q: Creating Layer for Selected Features, then Moving it using ArcGIS for Desktop? I have a problem with ArcGis 10.1 which I rarely use.
In an edit session I select a polygon. I would like to 'Create Layer for Selected Features' and can do this; the new layer appears in the table of contents. When I try and move the new layer, the old layer moves with it.
When I click on the polygon the option of selecting the two coincident polygons appears but I can't get these to separate. It seems to be impossible to do anything to one feature and not the other.
The strange thing is that yesterday the program wasn't behaving like this.
Can anyone can explain what is going on?

A: A layer is just a view of data - not the data itself. When you create a layer from a selection, you're just making another view of the same data. So if you edit the data, then both views are going to change.
If you want two independent features, you need to actually copy the data - either via copy in an edit session which just duplicates the feature in that dataset, or by exporting your selection which creates an entirely new dataset out of your selection.


text:
Q: C++ How to print unicode character over 0xFFFF? I'm trying to print all chinese character with c++.
my project uses wchar_t for handling unicode string.
wikipedia said: chinese chars are located in:
4E00–62FF
6300–77FF
7800–8CFF
8D00–9FFF
3400–4DBF
20000–215FF
21600–230FF
23100–245FF
24600–260FF
26100–275FF
27600–290FF
29100–2A6DF
2A700–2B73F
2B740–2B81F
2B820–2CEAF
2CEB0–2EBEF
30000–3134F
but my code said wchar_t is 2byte.
this means wchar_t support 0x0000 - 0xFFFF.
how can I print unicode char over 0xFFFF? should I use another thing (such as wstring?) rather than wchar_t?
thanks in advance.


text:
Q: Properly declare 2D array of Ints I'm trying to declare this initialized variable in my Objective-C program. I want it to be private and reference it in my implementation file. However, when I placed this in the .m file, I get an error saying "Array has incomplete element type 'int []'"
So, question is where am I supposed to place this and what is the correct syntax? I want my variable's syntax to be close to C as possible.
int evaluationTable[][] = {{3, 4, 5, 7, 5, 4, 3},
    {4, 6, 8, 10, 8, 6, 4},
    {5, 8, 11, 13, 11, 8, 5},
    {5, 8, 11, 13, 11, 8, 5},
    {4, 6, 8, 10, 8, 6, 4},
    {3, 4, 5, 7, 5, 4, 3}};


text:
Q: PX4 python dronekit, how to move a drone? I am using a quadrotor drone with PX4 1.8.0
I would like to write a python script which, according to some input, makes the drone moving in a specific direction (e.g. move 5 meters right,left,up down and so on) or making the drone moving to a specific gps location.
I need to do something very interactive, that is why missions do not suit my needs.
I have tried to use pymavlink/dronekit, both using specific commands like simple_goto()and using message_factory or command_long_send to directly send mavlink messages, but without results.I am also doing some tests on px4 gazebo simulator with the same result as on the drone
Only few commands work, for xample simple_takeoff() or command_long_send with MAV_CMD_NAV_TAKEOFF.
Does someone has an idea to make this drone move in an interactive way?
If you put some example or some guide it would be very appreciated   :)
Thank you very much


text:
Q: How to create a timer loop which will work after page refreshing? I have created my own countdown and it seems that I'm missing a part, whenever I refresh the page it also refresh the timer itself. I am looking to maximize the performance with that script so how can I make it looping infinitely?
Here is the code:
function startGRBTimer(duration, display) {
  var timer = duration,
    hours, minutes, seconds;
  setInterval(function() {
    days = parseInt(timer / (24 * 60 * 60), 10);
    hours = parseInt(timer % (24 * 60 * 60) / (60 * 60), 10);
    minutes = parseInt(timer % (60 * 60) / 60, 10);
    seconds = parseInt(timer % 60, 10);
    hours = hours < 10 ? "0" + hours : hours;
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    display.textContent = days + "d" + " " + hours + "h " + minutes + "m " + seconds + "s";
    --timer;
    if (timer <= 0) {
      timer = duration;
    }
  }, 1000);
}

var display = document.querySelector("#grb");
startGRBTimer(60, display);

A: That's just the way this code works, there is nothing wrong with it. Every time you refresh the page, the script gets re-run, and the var timer =  duration, hours, minutes, seconds; is created whenever the page is loaded.
You should look into creating first, and then storing the variable to the user's local storage, and have your program read the info from that variable (or array).

A: You need to do some job independently from your web application, with ability to live after page refresh, right?
It's highly likely that ServiceWorkers will be useful for you.

A: We could "misuse" window.name (see documentation link) for this case like in following example. Or you could use localStorage, but this does not work for local files (file:///...). And because of this window.name is better and shorter too.
Solution
function startGRBTimer(duration, display)
{
    var timer = window.name == '' ? duration : window.name,
        hours, minutes, seconds;

    setInterval(function()
    {
        days = parseInt(timer / (24 * 60 * 60), 10);
        hours = parseInt(timer % (24 * 60 * 60) / (60 * 60), 10);
        minutes = parseInt(timer % (60 * 60) / 60, 10);
        seconds = parseInt(timer % 60, 10);
        hours = hours < 10 ? "0" + hours : hours;
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        display.textContent = days + "d" + " " + hours + "h " + minutes + "m " + seconds + "s";
        --timer;

        if(timer <= 0)
        {
            timer = duration;
        }

        window.name = timer;
    }, 1000);
}

var display = document.querySelector("#grb");
startGRBTimer(60, display);


text:
Q: ExtJS drag event listeners work differently on Chrome and Firefox I have added an input field to Window's title bar (header). On Chrome selecting and editing the input field works, and I can still drag the window around. On Firefox I can drag the window around the viewport, but I am unable to select the input field and edit it. How should I correct this code so that it would work on both browsers?
Quick'n'dirty demonstration of the problem:
Ext.define('Demo.DemoWindow', {
    extend: 'Ext.window.Window',
    xtype: 'demowindow',

    height: 300,
    width: 400,
    title: 'Window',
    autoShow: true,
    items: [{
            xtype: 'button',
            text : 'Press!',
            listeners: {
              click: function() {
               var win = this.up('window');
               var header = win.getHeader();
               header.setTitle('');

               var killDrag = false;
               var dragEvent = win.dd.on({
                 beforedragstart: function(dd, e) {
                   if (killDrag) {
                     return false;
                   }
                 }
               });

               var field = Ext.create('Ext.form.field.Text', {
                 name: 'Title',
                 allowBlank: false,
                 value: 'Type here something!',
                 listeners: {
                   el: {
                     delegate: 'input',
                     mouseout: function() {
                       killDrag = false;
                     },
                     mouseenter: function() {
                       killDrag = true;
                     }
                   }
                 }
                });

                header.insert(0, field);

              }
            }
    }]
});

Ext.application({
    name: 'Demo',
    launch: function() {
        Ext.create('Ext.container.Viewport', {
            layout: 'absolute',
            items: [
                {
                    xtype: 'demowindow',
                    x: 20,
                    y: 20,
                }
            ]
        });
    }
});

A: Using the mouseover event instead of mouseenter seems to work well with both.


text:
Q: TypeError: callSite.getFileName is not a function at callSiteLocation (/node_modules/depd/index.js:252:23) on npm start When I am doing npm install in the project that I clone from github & then npm start I am getting error:
/Users/abc/Documents/Projects/test-project/node_modules/depd/index.js:252
  var file = callSite.getFileName() || '<anonymous>'
                      ^

TypeError: callSite.getFileName is not a function
    at callSiteLocation (/Users/abc/Documents/Projects/test-project/node_modules/depd/index.js:252:23)
    at depd (/Users/abc/Documents/Projects/test-project/node_modules/depd/index.js:111:14)
    at Object.<anonymous> (/Users/abc/Documents/Projects/test-project/node_modules/body-parser/index.js:14:32)
    at Module._compile (internal/modules/cjs/loader.js:678:30)
    at Module._compile (/Users/abc/Documents/Projects/test-project/node_modules/pirates/lib/index.js:136:24)
    at Module._extensions..js (internal/modules/cjs/loader.js:689:10)
    at Object.newLoader [as .js] (/Users/abc/Documents/Projects/test-project/node_modules/pirates/lib/index.js:141:7)
    at Module.load (internal/modules/cjs/loader.js:589:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:528:12)
    at Function.Module._load (internal/modules/cjs/loader.js:520:3)

This 'depd' library is throwing error from all the occurrences as it is a dependancy in various npm packages like body-parser & express. So it is throwing error from within all of them.
However my existing setup from same github repo where I am not doing npm install from scratch seem to be working fine.
I have tried doing npm install with different nodeJs versions 6.9.5, 10.x.x, 11.x.x, 12.x.x
Also I am using Babel v7.

A: Upgrade Node.js to the latest LTS. I was on 12.x and had this error, so upgrading to 16.x fixed it.


text:
Q: Migration to staging server, pages from other site loading in I'm not really sure how this could happen, but i migrated a wordpress site to a staging server where i have many wordpress sites hosted, everything seemed to go smooth with the exception that all inner pages (not the home page) load a single page from a previous site that is currently hosted on the staging server. Both sites have completely different directories, and their own database tables, and the urls for the inner pages reflect the correct location, yet it is still loading in pages and content from this other site. I'm stumped on how to debug this, and any help is appreciated.

A: You should use some migration plugin, e. g. Migrate DB, because some file paths and URLs are serialized in database and it's not enough to change just siteurl and home. Migrate DB seamlessly do the job.


text:
Q: plt.show() from matplotlib does not open a window I know this question or a related one has been asked many times, but I still have not found a solution: I ssh -X into a linux machine, where I run a conda installation of ipython. After importing matplotlib, I generate a plot (e.g., plt.plot(1,1)) and I want to show the plot in a window, which is forwarded to my local machine with plt.show(). This used to work, but suddenly no longer does: plt.show() does nothing. I guess this is related to a conda update, which I did yesterday, since a conda list --revisions does not show any suspicious recent changes in my environment.
From similar posts, I guess this is related to the matplotlib backend. The default backend 'Agg' generates png's via plt.savefig, but does not produce a plot in its own window, in which I can zoom. I have not managed to change the backend, though:
In [7]: import tkinter
In [8]: import matplotlib
In [9]: matplotlib.use('TkAgg')
In [10]: import matplotlib.pyplot as plt

gives
ImportError: Cannot load backend 'TkAgg' which requires the 'tk' interactive framework, as 'headless' is currently running

I have tried various similar things but with no success. Any suggestions?
Thank you!


text:
Q: The right way to plot multiple y values as separate lines with ggplot2 I often run into an issue where I have a data frame that has a single x variable, one or more facet variables, and multiple different other variables.  Sometimes I would like to simultaneously plot different y variables as separate lines.  But it is always only a subset I want.  I've tried using melt to get "variable" as a column and use that, and it works if I want every single column that was in the original dataset.  Usually I don't.
Right now I've been doing things really roundabout it feels like. Suppose with mtcars I want to plot disp, hp, and wt against mpg:
ggplot(mtcars, aes(x=mpg)) +
  geom_line(aes(y=disp, color="disp")) +
  geom_line(aes(y=hp, color="hp")) +
  geom_line(aes(y=wt, color="wt"))

This feels really redundant. If I first melt mtcars, then all variables will get melted, and then I will wind up plotting other variables that I don't want to.
Does anyone have a good way of doing this?

A: With reshape2 being deprecated, I updated @kohske answer using pivot_longer from tidyverse package.
Pivoting is explained here and involves specifying the data to reshape, second argument describes which columns need to be reshape (use - to exclude that column). Third is names_to gives the name of the variable that will be created from the data stored in the column names. Finally values_to gives the name of the variable that will be created from the data stored in the cell value, i.e. count. They also have more complex examples like numbers in column names  e.g. wk1 wk2 etc.
# new suggestion
library(tidyverse)

# I subset to just the variables wanted so e.g. gear and cab are not included
mtcars.long <- mtcars %>%
  select("mpg","disp", "hp", "wt") %>%
  pivot_longer(-mpg, names_to = "variable", values_to = "value")

head(mtcars.long)
# # A tibble: 6 x 3
# mpg variable  value
# <dbl> <chr>     <dbl>
#   1    21 disp     160
# 2    21 hp       110
# 3    21 wt         2.62
# 4    21 disp     160
# 5    21 hp       110
# 6    21 wt         2.88

ggplot(mtcars.long, aes(mpg, value, colour = variable)) + geom_line()

Chart is:

A: ggplot always prefers long format dataframe, so melt it:
library(reshape2)
mtcars.long <- melt(mtcars, id = "mpg", measure = c("disp", "hp", "wt"))
ggplot(mtcars.long, aes(mpg, value, colour = variable)) + geom_line()

There are many other options for doing this transformation. You can see the R-FAQ on converting data from wide to long for an overview.


text:
Q: Understanding on frequency compensation on driving capacitive loads with an op-amp I am trying to understand an example circuit of frequency compensation on driving capacitive loads with an op-amp from:
https://www.allaboutcircuits.com/technical-articles/how-to-drive-large-capacitive-loads-op-amp-circuit/
I understand how the capacitive loads cause the stability issue and the idea of using a capacitor to neutralize the phase lag caused by the capacitive load.
It is just very confusing to me how the value of compensation capacitor Cf is determined in the below example.

The second condition imposes:

to make the phase lead introduced by Cf exactly neutralize the phase lag caused by CL. I tried to figure out how this condition was derived but still got no clue. Anyone can help on this? many thanks.

A: In addition to the nice answers you will no doubt get about this theoretical exercise (e.g. from V.V.T), I want to add a practical word of caution (it does not answer your question):
Capacitor values have large tolerances and Class II ceramics have strong DC dependence. Also the output impedance is not well known typically.
So even though you did all the calculations correctly, you might still end up with oscillations. To find a good value for the feedback capacitance will require some experimentation, if you really need the maximum possible bandwidth.
If you anyway are only going to use a bandwidth much below the possible bandwidth, you can and should be very generous about the value of the feedback capacitor. Making it larger than its critical value has no bad consequences other than restricting your bandwidth. Restricting bandwidth is often a good practise to help against interference and aliasing. By way overspeccing this capacitor (e.g. 10x) you also make yourself independent of component variations and guarantee that your designs always work.

A: Actually, the equation
$$
{f_2 \over f_1} = {R_2 \over R_1} \tag{0}
$$
is a crucial point of the How to Drive Large Capacitive Loads.. article. Learning aids sometime equate the technique of straightening the transfer function of the linear circuit with pole/zero cancellation, which is bad, because the zero values are unstable w.r.t small variations of circuit parameters which makes the results of circuit analysis often simply wrong. So, if I need to analyze, I do a symbolic calculation on simple circuits like those of frequency compensation feedback designs by directly applying KCL. It is not extraordinary difficult, but takes a certain amount of time and effort.
In his article, Dr. Sergio Franco ingeniously applies a relation which connects only pole values: the pole values do not suffer the uncertainty of zero values. It seems this trick should be credited to him -- I have not found the eqn. 0 some other place.
As for derivation of this equation, he mentions only that "we wish the phase lead introduced by Cf to neutralize the phase lag due to CL". In my answer to the question, I am going to derive this equation and also calculate the recommended feedback capacitor and serial resistor values for the inloop frequency compensation circuit ab ovo.
Assuming the familiarity with Bode plots, for the purely capacitive linear feedback circuit I'd like to calculate the real negative pole values. Notice the values are real and I would rather not name these values "frequencies". My purpose is to derive the ratio of two real negative pole values for the linear circuit with two capacitors and four resistors:

Notice an internal output resistance Ro shown in the opamp symbol: the opamp output resistance is placed "in the loop" as well as the other elements discussed below. VA is the "internal" output of the opamp excluding the output resistance and the feedback circuit input, VFB is the opamp input and the feedback circuit output.
Let us draw a feedback loop and the capacitive load separately from opamp (only opamp output resistance is included in the loop):

There are three nodes in this circuit; we write down KCL equations for three voltages at these nodes. The input signal \$V_{in}\$ for the feedback circuit is the opamp's internal output VA, \$V_3\$ is the output node connected to the opamp negative input. For this writing convenience, I use conductances g_x rather than resistances R_x, \$g_x = 1/R_x\$:
$$
g_o·(V_1-V_{in}) + g_s·(V_1-V_2) + sC_f·(V_1-V_3) = 0
\\
g_s·(V_2-V_1) + g_2·(V_2-V_3) + sC_L·V_2 = 0
\\
g_2·(V_3-V_2) + g_1·V_3 + sC_f·(V_3-V_1) = 0
$$
We need to find the Rs and Cf component values that give the frequency-independent TF.
First we require that \$V_3(s=0) ≡ V_3(s=∞)\$ and immediately arrive at \$g_s = {g_o·g_1 \over g_2}\$ to fulfill this requirement (see the How To Drive... article, Equation 5). We substitute this value into the equations.
$$
g_o·(V_1-V_{in}) + {g_o·g_1 \over g_2}·(V_1-V_2) + s·C_f·(V_1-V_3) = 0 \tag {1}
$$
$$
{g_o·g_1 \over g_2}·(V_2-V_1) + g_2·(V_2-V_3) + s·C_L·V_2 = 0 \tag {2}
$$
$$
g_2·(V_3-V_2) + g_1·V_3 + sC_f·(V_3-V_1) = 0 \tag {3}
$$
The equations are still unwieldy if we want to immediately derive the \$V_3(C_f)\$ formula and see what \$C_f\$ value makes TF frequency independent. To cope with this difficulty, I use the lemma declaring that for a transfer function, with two real LHP poles and two real LHP zeros, that satisfies the requirement \$TF(s=0)=TF(s=∞)\$, this statement is true: if its first derivative is zero at \$s=0\$, its poles and zeros mutually cancel one another and TF is constant everywhere (all the higher order derivatives are also zero). You can see the proof at the end of this answer.
By force of this lemma, for the frequency-independent TF, it is sufficient to verify that TF's first derivative is zero at \$s=0\$.
Let us write down the power expansions of V1, V2, V3 at \$s=0\$ (McLaurin series) to the first order on \$s\$:
$$
V_1(s) = V0_1(1+s·τ_1)
\\
V_2(s) = V0_2(1+s·τ_2)
\\
V_3(s) = V0_3(1+s·τ_3) \tag {s-linearized voltage defs}
$$
\$V0_1,V0_2,V0_3\$ are voltages at nodes 1, 2, 3 for a DC solution (notice that \$R_o + R_s + R_1 + R_2 = (R_o + R_2)(1 + R_1/R_2)\$. To further simplify the expressions, I introduce a variable \$k\$, the ratio of feedback resistor values \$k = R_2/R_1 = g_1/g_2\$. It's been shown that from \$V_3(s=0) ≡ V_3(s=∞)\$ also follows \$g_s = {g_o·g_1 \over g_2} = k·g_o \$:
$$
V0_1/V_{in} = {\frac {R_0 R_1 / R_2 + R_1 + R_2} {(R_o + R_2)(1 + R_1/R_2)}} = {\frac {g_o} {g_o + g_2}} + {\frac {g_2} {(k+1)·(g_o + g_2)}}
\\
V0_2/V_{in} = {\frac {R_1 + R_2} {(R_o + R_2)(1 + R_1/R_2)}} = {\frac {g_0} {(k+1)·(g_o + g_2)}}
\\
V0_3/V_{in} = {\frac {R_1} {(R_o + R_2)(1 + R_1/R_2)}} = {\frac {g_o} {k·(k+1)·(g_o + g_2)}}
$$
Substituting the linearized voltage defs into eqns. 1, 2, 3 and omitting second-order \$s\$ terms, we arrive at a new set of equations with unknown variables \$τ_1, τ_2, τ_3\$:
$$
(k+1)·g_o·V0_1·s·τ_1 - k·g_o·V0_2·s·τ_2 = s·C_f(V0_3-V0_1) \\
k·g_o·V0_1·s·τ_1 + (k·g_o + g_2)·V0_2·s·τ_2 + g_2·V0_3·s·τ_3 = -s·C_L·V0_2 \\
-g_2·V0_2·s·τ_2 + (k+1)·g_2·V0_3·s·τ_3 = s·C_f·(V0_3-V0_1)
$$
Notice that zero-order \$s\$ terms are gone because \$V0_1,V0_2,V0_3\$ satisfy the circuit's DC equations.
Now, one more time we are replacing unknown variables with a new set of new variables \$w_1=(V0_1/V_{in})·τ_1, \, w_2=(V0_2/V_{in})·τ_2, \, w_3=(V0_3/V_{in})·τ_3\$:
$$
(k+1)·g_o·w_1 - k·g_o·w_2 = C_f·\left(\frac {g_o} {k·(k+1)·(g_o + g_2)} - {\frac {g_o} {g_o + g_2}} - {\frac {g_2} {(k+1)·(g_o + g_2)}}\right) \tag{4}
$$
$$
k·g_o·w_1 + (k·g_o + g_2)·w_2 + g_2·w_3 = -C_L·{\frac {g_0} {(k+1)·(g_o + g_2)}} \tag{5}
$$
$$
-g_2·w_2 + (k+1)·g_2·w_3 = C_f·{\frac {g_o} {k·(k+1)·(g_o + g_2)}} \tag{6}
$$
After Gaussian elimination (reducing variables w1 and w2), we arrive at the formula for w3
$$
(g_2/k + k·g_o - g_2)·w_3 = -C_L·{\frac {g_0} {(k+1)·(g_o + g_2)}} + C_f{\frac {g_o} {g_o + g_2}}·{\frac {g_2} {(k+1)·(g_o + g_2)}}\left({k·g_o \over g_2}+1\right){1 \over {k+1}}
$$
We need not even solve for w3: zeroing the right side gives you the formula for Cf
$$
C_f = {\frac {(k+1)^2·g_o·g_2} {(k·g_o+g_2)^2}} C_L \tag {7}
$$
In the approximation R0 << R1, R2 we arrive at Dr. Franco's formula
$$
C_f = (R_o/R_2)(1 + R1/R_2)^2 C_L \tag {8}
$$
To find the pole values for our feedback circuit, we are back to eqns. 1,2,3, where \$k·g_2\$ is substituted for \$g_1\$:
$$
((k+1)·g_o + s·C_f)·V_1 - k·g_o·V_2 - s·C_f·V_3 = g_o·V_{in} \tag {9}
$$
$$
-k·g_o·V_1 + (k·g_o + g_2 +s·C_L)·V_2 - g_2·V3 = 0 \tag {10}
$$
$$
-s·C_f·V_1 - g_2·V_2 + ((k+1)·g_2 + s·C_f)·V_3 = 0 \tag {11}
$$
Poles (singularities) are arisen at \$s\$ values where the determinant of the coefficient matrix for these equations
$$
A =
\begin{bmatrix}
    (k+1)·g_o + sC_f    & -k·g_o        & -s·C_f·V_3    \\
    -k·g_o      & (k·g_o + g_2 +s·C_L)  & - g_2     \\
    -s·C_f·V_1      & -g_2          & (k+1)·g_2 + s·C_f
\end{bmatrix}
$$
is zero:
$$
\det[A] =
k·(k+1)·g_o·g_2·(g_o+g_2) + \\
s·(C_L·(k+1)^2·g_o·g_2 + C_f·(k·g_o^2 + (k^2+1)·g_o·g_2 + k·g_o^2)) + \\
s^2·C_f·c_L·(k+1)·(g_o+g_2) = 0
$$
Substituting \$C_f\$ from eqn. 7 and solving the quadratic equation
$$
k·(k+1)·g_o·g_2·(g_o+g_2) + s·C_L·(k+1)^2·g_o·g_2(k+1)(g_o+g_2)/(k·g_o+g_2) + s^2·c_L^2·(k+1)^3·g_o·g_2·(g_o+g_2) = 0
$$
we have two roots
$$
s_{1,2} = -{\frac {k+1±|k-1|} {2}} {\frac {k·g_o + g_2} {C_L·(k+1)}}
$$
The ratio of this two root values is
$$
{s_2 \over s_1} = k = {R_2 \over R_1}
$$
We have derived Sergio Franco's formula.
APPENDIX
LEMMA:  Transfer Function of Two-Capacitor Linear Circuit with Zero First Derivative at s=0 is Constant
A two-capacitor linear circuit have two poles and two zeros:
$$
\text {TF}(s) = {\frac {(1-s/z_1)(1-s/z_2)} {(1-s/p_1)(1-s/p_2)}} \\
\text {TF}(0) = 1; \, \text {TF}(∞) = p_1·p_2/z_1·z_2
$$
From \$\text {TF}(0) = \text {TF}(∞) = 1\$ we have \$p_1·p_2 = z_1·z_2\$.
From \$d(\text {TF}(s))/ds|_{s=0} = (1/p_1 + 1/p_2 - 1/z_1 - 1/z_2) = 0\$ (the first derivative is zero at \$s=0\$) we have \$p_1+p_2 = z_1+z_2\$.
Let \$r_1 = p_1/z_2, \, r_2 = p_2/z_1\$, then \$r_1 = 1/r_2 = r\$. From \$p_1+p_2 = z_1+z_2\$ we have \$r·z_2 + (1/r)·z_1 = z_1 + z_2\$.
Ergo, either \$r=1\$ or \$z_1 = z_2 = 0\$.

A: This is not an answer, but extended comment. The target readers of this post are visitors that come here through searches or links.
There are a few questions on electronics SE about frequency compensation techniques for opamp circuits with capacitive load. The questions have received answers of different quality, and one answer even insists on being "very generous about the value of the feedback capacitor."
Let us follow this instruction for stabilizing a circuit with a quite popular high bandwidth low noise OPA657:

The circuit is unstable with component values as given in the circuit drawing. The voltage at opamp's output demonstrates instability:

Following the instruction, we increase Cf to a value of 100 pF:

Instead of alleviating, the effect of Rf increase on stability is detrimental.
Back to Cf=1pF, then apply the out-of-loop frequency compensation trick with an isolation resistor. With Rs=10, the circuit is stable:

The reason for this behavior is, of course, the peculiar frequency characteristic of OPA657. The "advice" would work for some other opamps and in the frequency ranges where these opamp's poles satisfy certain requirements, but in a "real world" we have many opamp types for diverse applications.
The cited article on Frequency Compensation, How to Drive Large Capacitive Loads.., is about a circuit with the idealized one-pole opamp, and the OP question is about a missed link in the chain of formula derivations, not about capacitor tolerances or output impedance scattering. What's more, I cannot understand how "strong DC dependence" of "Class II ceramics" are the first class citizens for engineers and "guarantee that your designs always work" while symbolic calculations are inferior to the same ends. Why, indeed, the OP should be warned with "a practical word of caution" against learning in depth the frequency compensation techniques?
I hate to discuss the negative phenomena that sometimes can be noticed in engineering Q&A portals. To add positivity to my post, I dare to offer for the attention of electronics practitioners (as opposing to "theoreticians") an online course TI Precision Labs - Op amps, specifically, the section on Stability. If (or when) electronics practitioners master the content of this course, they can follow a more direct route to calculating, for example, the feedback capacitance for one important design, a Si photodiode and opamp circuit, in Hamamatsu's Handbook on Si photodiodes. Section Connection to an op amp (page 9) discusses gain peaking instability and the ways of its elimination, with equations and formulas at only the necessary minimum. Specifically, pay attention to Figure 1-20 Graphical representation of gain peaking with its f1/f2/f3/f4 frequency ranges and how these are used for optimal design. This is a perfect example of practical approach to circuit design, of which the electronics "practitioners" are fervent proponents.


text:
Q: Should an exception be thrown when the data from db is bad? In this particular application, there is no separate data layer and the data access code is in the Entity itself. For example, consider a Customer entity, then in the Customer.cs file where the members and properties are defined, you have methods to load the Customer object as below
public bool TryLoad(int customerID, out Customer customer)
{
    bool success = false
    try
    {
        //code which calls the db and fills a SqlDataReader
        ReadDataFromSqlDataReader(reader);
        success = true;
    }
    catch(Exception ex)
    {
      LogError();
      success = false;
    }
    return success;
}

Now, in the ReadDataFromSqlDataReader(reader), tryparse is used to load data from the reader into the object. e.g.
public void ReadDataFromSqlDataReader(reader)
{
   int.TryParse(reader["CustomerID"].ToString(), out this.CustomerID);
   PhoneNumber.TryParse(reader["PhoneNumber"].ToString(), out this.PhoneNumber);
   ... similar TryParse code for all the other fields..
}

Is using TryParse to read all the properties from the reader a good practise? A dev told me that its done this way as TryParse has a better performance than int.Parse. But wouldnt you want an exception to be throw when the value you are reading from the db does not conform to what your code expects? I mean in this case, if there is a wrong phone number in the db then perhaps the object shouldn't be initialized at all instead of loading an object with an empty phone number?

A: Yes, following the fail-fast principle, you would want an exception to be thrown the moment a value comes back that cannot be converted into the expected type.
If one of these operations fails and you continue as if nothing happened, you are likely to get weird errors that are hard to catch and hard to pinpoint: objects being added to the database when they should have been updating an existing row, data mysteriously disappearing, dogs and cats living together... you get the idea.
On the other hand, if you throw an exception immediately, you know exactly where your problem is and you can catch it and fix it before it becomes worse.
TryParse will work faster than Parse in case of failure simply because it doesn't have to throw an exception (which can be expensive), but if you're assuming that things will succeed (which this code is doing by not using the result of the parse), you should get equivalent performance using Parse.

A: What sort of validation are  you doing when the data is being inserted and/or updated?
As long as you are applying some form of validation here, I personally would not be validating the data coming out of the Database as you should be confident that you are only putting in valid data.

A: Effective validation be performed when data is inserted into the database. It's not a good design with which bad data could be entered in the database. If database contains bad phone number, user should be asked to enter phone number again if its mandatory and if phone number is not that important, you could initialize phone number to null in case of bad data.

A: I wouldn't be using TryParse for that.
If my db had rubbish in it, I'd want that addressed.
If the data was ambiguous in terms of parsing (e.g. Varchar with int or double in it as a string)
I'd want to sort out my schema, TryParse as type detection would be a quick and simple hack.

A: If you would handle it, well yes you should throw an exception. But if you don't care about the exception and if you would filter the right data and use it (in this case non zeros) you can skip.

A: As, TryParse returns Boolean value. So, I can ByPass/Continue the Upcoming Logic/Any Database request on the  basis of Boolean Value. I will not let the exception to occur in such scenaria. For that I will do the logging etc.
Parse

*

*Throws an exception.

*Use it if you are sure the value will be valid

TryParse

*

*Returns a bool indicating whether it succeeded

*It just try/catch internally that why is implemented without exceptions so that it is fast

*Use it in case the value may be InValid


text:
Q: sizeof() function in C main()
{
char a[] = "Visual C++";
char *b = "Visual C++";
printf("\n %d %d",sizeof(a),sizeof(b));
printf("\n %d %d",sizeof(*a),sizeof(*b));
}

sizeof(a) gives me output: 11  ( that is length of the string)
Why is it so ?
Why isn't the output sizeof(a)=4 since when I try to print a it gives me an address value and hence an integer?

A: In the declaration char a[] = "Visual C++", a is an array of 11 char. So its size is 11 bytes.
In the declaration char *b = "Visual C++", b is a pointer to char. So its size is four bytes (in the C implementation you are using).
In the expression printf("%s", a), a is also an array. However, it is automatically converted to a pointer to the first element of the array. So a pointer to char is passed to printf.
This conversion happens automatically unless an array is the argument of &, sizeof, or _Alignof or is a string literal used to initialize an array of char. Because it happens automatically, people tend to think of array names as pointers. However, they are not.
Incidentally, sizeof is an operator, not a function.

A: Whenever you refer to the name of the array in your program, It normally decays to a pointer to the first element of the array. One of the exception to this rule is the sizeof operator. So when you consider the following code.
int main()
{
   char a[] = "Visual C++";
   printf("sizeof(a)=%d\n",sizeof(a)); /* Here sizeof(a) indicates sizeof array */
   printf("a=%p",a); /* Here the array name, passed as an argument to printf decays into a pointer of type (char *) */
   return 0;
}

A: When sizeof is applied to the name of a static array (not an array allocated through malloc), the result is the size in bytes of the whole array. This is one of the few exceptions to the rule that the name of an array is converted to a pointer to the first element of the array, and is possible just because the actual array size is fixed and known at compile time, when sizeof operator is evaluated.

A: There are lots of errors, here.
"sizeof(a) gives me output: 11 (length of the string)"
The length of the string is 10, not 11. sizeof(a) gives you the length of the array.
"why is it so, why isn't the output sizeof(a)=4 since when I try to print a it gives me an address value"
Here are two methods of "printing a" which do not "give you an address value":
puts(a);

and:
printf("%s\n", a);

so your logic is flawed, and this is the source of your confusion. "Printing a" only "gives you an address value" when you explicitly or implicitly elect to do so.
sizeof(a) gives 11 in this case because the C language defines the sizeof operator to give you the size of an array when an array is the operand. This, I'd argue, is the most natural behavior people would expect, so presumably that's why it is defined as such.
"and hence an integer."
In any case, an address is an address, not an integer. At best you could argue that it ought to give you the size of a pointer, but certainly not the size of an integer.


text:
Q: Tkinter have 2 different font sizes on the same text I would like to display the time inside of a tkinter frame in a stylish way, like this :
However I can't find any way to do this, please note the label with the time is centered on my frame.
I've also tried putting 2 labels on the same grid cell but the label with hours and minutes is removed when I add the label with the seconds.
Is there a way to put 2 labels in one ? or group them ?
class MainPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent, background = "black")
        self.root = parent

        self.columnconfigure(0, weight = 1, uniform = "x")
        self.columnconfigure(1, weight = 1, uniform = "x")
        self.columnconfigure(2, weight = 1, uniform = "x")
        self.rowconfigure(0, weight = 1, uniform = "x")
        self.rowconfigure(1, weight = 1, uniform = "x")

        self.HM = tk.Label(self, text = getHM(), fg = "white", bg = "black", font = LARGE_FONT)
        self.HM.grid(row = 0, column = 1, pady=10, sticky = 'nwe')

        self.S = tk.Label(self, text = getS(), fg = "white", bg = "black", font = LARGE_FONT)
        self.S.grid(row = 0, column = 1, pady=10, sticky = 'nwe')

        self.update_clock()

    def update_clock(self):
        HM = "10:20:"
        S = "45"
        self.HM.configure(text=HM)
        self.S.configure(text=S)
        self.root.after(1000, self.update_clock)

Thanks in advance !
Shraneid

A: Here is a working example that takes some of your code and the use of Font from tkinter to set 2 labels with one smaller size font.
import tkinter as tk
from tkinter.font import Font

class MainPage(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent, background = "black")
        time_frame = tk.Frame(self)
        time_frame.grid(row=0, column=1)
        big_font = Font(family='Helvetica', size=33, weight='bold')
        small_font = Font(family='Helvetica', size=12, weight='bold')
        HM = tk.Label(time_frame, text="{} :".format(getHM()), fg="white", bg="black", font=big_font)
        HM.grid(row=0, column=0, pady=10)

        S = tk.Label(time_frame, text=getS(), fg="white", bg="black", font=small_font)
        S.grid(row=0, column=1, pady=10, sticky='s')

root = tk.Tk()

def getHM():
    return("10 : 00")

def getS():
    return("34")

MainPage(root).grid(row=0, column=0)
root.mainloop()


text:
Q: Breakpoints conditionated by default Context
Eclipse for PHP Developers
Version: Oxygen.3a Release (4.7.3a)
Build id: 20180405-1200
The problem
Every breakpoints I create, are created with "Enable Set Condition" checked, and an empty condition. To use them as non-conditional breakpoints (95% of times) I have to open breakpoint properties panel and uncheck this checkbox.
Reproduction

*

*Double click on left side ruler:

*Breakpoint automatically configured as conditionated:

I don't know if it's a bug, and/or if it can be re-configured... Any ideas?


text:
Q: difference between node n and new node If I declare a struct node in C++,after which I declare:
n = new node;

or
node n;

Are both these notations representing the same thing?

A: No.
n = new Node;

is a pointer, the correct code is
Node* n = new Node;

or, with C++11 (the latest C++ standard published in 2011, ant not yet implemented by several compilers, even if latest GCC 4.7 or soon to be released 4.8 is quite near)
auto n = new Node;

Actually, using raw pointers like above is frowned upon. You should consider using smart pointers e.g.
std::shared_ptr<Node> n = new Node;

The pointed-to node will be destroyed by later calling (perhaps indirectly)
delete n;

(notice that smart pointers do that "magically" for you)
But
Node n;

declare a variable of type Node. That Node data is destroyed at the end of current scope (i.e. at the closing } containing brace).
Read also about RAII.

A: *

*node* n = new node; is allocated on heap

*node n; is allocated on stack

In case 1. when you allocate on heap using the new keyword you must use node* because you're saving a pointer to the object not the object itself. Using heap allocation is especially useful when you are going to want to use the object outside the current scope, although you have to always remember to call delete n; on every object allocated with the new keyword (unless you're using std::shared_ptr or anything along those lines).
node* make_node()
{
    node* n = new node;
    n->do_something();
    return n;
} // node n does not go out of scope here, but you'll have to call delete on it when you're done

In case 2. the object is being allocated on stack, while you don't have to call delete here, this one is going to go out of scope at the end of the current block:
void function()
{
    node n;
    n.do_something();
} // node n goes out of scope here.

Additional information about std::shared_ptr and other <memory> goodies.

A: Although they represent the same thing, n in the second case is created on the stack, where as the n in n = new node; is created on the heap storage, which must be manually deleted.
Also, the n in n = new node must be a pointer, created like this: node* n;


text:
Q: Передать данные из c# в delphi Запущено два приложения. Одно на c#, второе на delphi
Необходимо передать число из c# в delphi.
Как сделать даже не знаю, гуглил, говорят через dll или оперативную память, запись и считывание файла.

A: Примерно так например (средствами SendMessage WM_COPYDATA):
Отправка:
Type
  TSendForm = Class(TForm)
    btnSend: TButton;
    edtNumber: TEdit;
    procedure btnSendClick(Sender: TObject);
  Private
    { Private-Deklarationen }
  Public
    { Public-Deklarationen }
  End;

Const
  CMD_SETNUMBER = 1; //Задаем ID команды

Var
  SendForm: TSendForm;

Implementation

{$R *.dfm}

Procedure TSendForm.btnSendClick(Sender: TObject);
Var
  CDS: TCopyDataStruct;
Begin
  //Устанавливаем тип команды
  CDS.dwData := CMD_SETNUMBER;
  //Устанавливаем длину передаваемых данных
  CDS.cbData := Length(edtNumber.Text) + 1;
  //Выделяем память буфера для передачи данных
  GetMem(CDS.lpData, CDS.cbData);
  Try
    //Копируем данные в буфер
    StrPCopy(CDS.lpData, AnsiString(edtNumber.Text));
    //Отсылаем сообщение в окно с заголовком StringReceiver
    SendMessage(FindWindow(Nil, 'Receiver'), WM_COPYDATA, Handle, Integer(@CDS));
  Finally
    //Высвобождаем буфер
    FreeMem(CDS.lpData, CDS.cbData);
  End;
End;

End.

Обработка:
Type
  TRecvForm = Class(TForm)
    mLog: TMemo;
  Private
    FNumber: Integer;
    //Обработчик сообщения WM_COPYDATA
    Procedure WMCopyData(Var MessageData: TWMCopyData); Message WM_COPYDATA;
  Public
    Property Number: Integer Read FNumber Write FNumber;
  End;

Const
  CMD_SETNUMBER = 1;

Var
  RecvForm: TRecvForm;

Implementation

{$R *.dfm}

Procedure TRecvForm.WMCopyData(Var MessageData: TWMCopyData);
Begin
  If MessageData.CopyDataStruct.dwData = CMD_SETNUMBER Then Begin
    Try
      Number := StrToInt(String(PAnsiChar((MessageData.CopyDataStruct.lpData))));
    Except
      On E: Exception Do Begin
        mLog.Lines.Append(Format('Ошибка: %s', [E.Message]));
        MessageData.Result := 0;
        Exit;
      End;
    End;
    mLog.Lines.Append(Format('Получено число: %d', [Number]));
    MessageData.Result := 1;
  End
  Else
    MessageData.Result := 0;
End;

End.

Соответственно одно из них реализуете на C#

A: Сделал так:
using System.Runtime.InteropServices;
using System.Security;

class ProgramSend
{
    public const int WM_COPYDATA = 0x004A;
    [return: MarshalAs(UnmanagedType.Bool)]

    [DllImport("user32.dll")]
    public static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll")]
    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr SendMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);

    [DllImport("user32.dll", EntryPoint = "FindWindow")]
    public static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public struct MyStruct
    {
        public double coins;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
        public string status;
    }

    public static IntPtr IntPtrAlloc<T>(T param)
    {
        IntPtr retval = Marshal.AllocHGlobal(Marshal.SizeOf(param));
        Marshal.StructureToPtr(param, retval, false);
        return (retval);
    }

    public static void IntPtrFree(IntPtr preAllocated)
    {
        if (IntPtr.Zero == preAllocated) throw (new Exception("Go Home"));
        Marshal.FreeHGlobal(preAllocated); preAllocated = IntPtr.Zero;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct COPYDATASTRUCT
    {
        public IntPtr dwData;       // Specifies data to be passed
        public int cbData;          // Specifies the data size in bytes
        public IntPtr lpData;       // Pointer to data to be passed
    }

    [SuppressUnmanagedCodeSecurity]
    public class NativeMethod
    {
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern IntPtr SendMessage(IntPtr hWnd, int Msg,
            IntPtr wParam, ref COPYDATASTRUCT lParam);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    }
}

public static class MyCalss
{
    public static System.String MyFunc(string sMsg)
    {

        IntPtr hTargetWnd = ProgramSend.NativeMethod.FindWindow(null, "CCDemo");
        if (hTargetWnd == IntPtr.Zero)
        {
            MessageBox.Show("Unable to find the \"ReceiverMainForm\" window",
                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        try
        {
            ProgramSend.COPYDATASTRUCT cds = new ProgramSend.COPYDATASTRUCT();
            cds.dwData = (IntPtr)1; //some data
            cds.cbData = sMsg.Length + 1;
            cds.lpData = Marshal.StringToCoTaskMemAnsi(sMsg);

            ProgramSend.NativeMethod.SendMessage(hTargetWnd, ProgramSend.WM_COPYDATA, IntPtr.Zero, ref cds);

            Marshal.FreeCoTaskMem(cds.lpData);

            int result = Marshal.GetLastWin32Error();
            if (result != 0)
            {
                MessageBox.Show(String.Format(
                    "SendMessage(WM_COPYDATA) failed w/err 0x{0:X}", result));
            }
        }
        finally
        {
            //Marshal.FreeHGlobal(pMyStruct);
        }
        return "done";
    }

}

На делфи:
type
  TMyRecord = packed record
    coins: Double;
    status: string[255];
  end;
  PMyRecord = ^TMyRecord;

procedure TFMain.WMCOPYDATA(var msg: TWMCopyData);
var
  coins: Double;
  status: String[255];
  sText: String;
begin
status:=Pansichar(msg.CopyDataStruct.lpData);
coins := msg.CopyDataStruct.dwData;
ShowMessage('Msg: ' + status + ' Number: ' + FloatToStr(coins));
end;


text:
Q: how to determine the level of an element by matching its id in xslt? How to get output like below example? I want to generate ids for section elements based on their level and position. Please notice the result of <link>, where the matching ids are called.
Any help would be appreciable.
INPUT:
<book>

xxxxxx

yyyyyyyyy

            <link href="book1:s19"/>

            <link href="book1:s2"/>

</book>

OUTPUT should be as:
<book>

xxxxxx

yyyyyyyyy

</book>

By implementing below xslt, I am just able to generate the ids for
 elements. But unable to get the correct output in  i.e. the resulting section id for the matched id in @href of link element.
<?xml version="1.0" encoding="utf-8"?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="2.0">
    <xsl:output method="xml"/>
<xsl:key name="KEY" match="section" use="id" />
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="book">
        <book><xsl:apply-templates/></book>
    </xsl:template>

    <xsl:template match="section">
        <xsl:variable name="ORDER" select="count(ancestor::section)+1"/>
        <xsl:element name="section">
            <xsl:if test="$ORDER=1">
                <xsl:attribute name="id"><xsl:text>s</xsl:text>
                    <xsl:value-of select="count(preceding-sibling::section)+1"/>
                </xsl:attribute>
            </xsl:if>
            <xsl:if test="$ORDER=2">
                <xsl:attribute name="id"><xsl:text>s</xsl:text>
                    <xsl:value-of select="($ORDER - 1) + count(parent::section/preceding-sibling::section)"/>
                    <xsl:text>.</xsl:text>
                    <xsl:value-of select="count(preceding-sibling::section)+1"/>
                </xsl:attribute>
            </xsl:if>
            <xsl:if test="$ORDER=3">
                <xsl:attribute name="id"><xsl:text>s</xsl:text>
                    <xsl:value-of select="($ORDER - 2)"/>
                    <xsl:text>.</xsl:text>
                    <xsl:value-of select="count(parent::section/preceding-sibling::section)+1"/>
                    <xsl:text>.</xsl:text>
                    <xsl:value-of select="count(preceding-sibling::section)+1"/>
                </xsl:attribute>
            </xsl:if>
            <xsl:attribute name="order">
                <xsl:value-of select="count(ancestor::section)+1"/>
            </xsl:attribute>
            <xsl:apply-templates/>
        </xsl:element>
    </xsl:template>

    <xsl:template match="link">
        <xsl:element name="a">
            <xsl:attribute name="id">
                <xsl:value-of select="generate-id()"/>
            </xsl:attribute>
            <xsl:attribute name="href">
                <xsl:value-of select="count(//section[@id=substring-after(@href,':')])"/>
            </xsl:attribute>
            <xsl:apply-templates/>
        </xsl:element>
    </xsl:template>

</xsl:transform>

Anybody has the answer please help?
Thanks...

A: Numbering can be done with xsl:number, the cross-references can be found with a key and the computation of the the new number can be factored out into a template of its own so that both the element as well as the referencing one can use it to compute the same id:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:math="http://www.w3.org/2005/xpath-functions/math"
    xmlns:map="http://www.w3.org/2005/xpath-functions/map"
    xmlns:array="http://www.w3.org/2005/xpath-functions/array"
    exclude-result-prefixes="xs math map array"
    version="3.0">

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:key name="section-ref" match="section" use="@id"/>

  <xsl:template match="section">
      <xsl:copy>
          <xsl:attribute name="id">
            <xsl:apply-templates select="." mode="generate-id"/>
          </xsl:attribute>
          <xsl:attribute name="order" select="count(ancestor-or-self::section)"/>
          <xsl:apply-templates/>
      </xsl:copy>
  </xsl:template>

  <xsl:template match="link[@href]">

          <xsl:attribute name="href">
              <xsl:apply-templates select="key('section-ref', substring-after(@href, ':'))" mode="generate-id"/>
          </xsl:attribute>

  </xsl:template>

  <xsl:template match="section" mode="generate-id">
      <xsl:text>s</xsl:text>
      <xsl:number level="multiple" format="1-1"/>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/eiZQaFC is an online XSLT 3 sample but for XSLT 2 the code should work as well if you remove the xsl:mode and keep your identity transformation template.


text:
Q: File type is not validated I'm trying to validate file type before saving it to database. This is my rule
array('picture', 'file', 'types'=>'jpg, gif, png, jpeg', 'allowEmpty'=>true, 'maxSize'=>1024*1024/*1mb*/, 'tooLarge'=>Yii::t('default', 'File is too large'), 'on'=>'create'),

I'm trying to upload multiple images
foreach($_FILES["picture"]["name"] as $key=>$value)
{
    $images->picture='file';
    $images->IDbuyitnow=1;
    if($images->validate())
        echo $value." ";
    else
        echo "doesnt work";
}

HTML code
<?php echo CHtml::fileField('picture[]','',array('class'=>'form-control' ,'multiple'=>true, 'accept'=>'image/*')); ?>

I know I should use CMultiUpload but I wanted to make it like that. But it always validate it even if $images->picture="file" or "25.docx". var_dump($images->validate()) returns true

A: [SOLVED] Weirdest thing ever, attribute shouldn't be called "picture" but "image" instead.
FULL SOLUTION
HTML
<?php echo CHtml::fileField('image_file[]','',array('class'=>'form-control' ,'multiple'=>true, 'accept'=>'image/*')); ?>

CONTROLLER
$images=new BuyItNowImage;
$file=CUploadedFile::getInstancesByName('image_file');
foreach($fileas $key=>$value)
{
    $images->image_file=$value;
    $images->IDbuyitnow=1;

    if($images->validate())
        echo "ok";
    else
        echo "not ok";

}

MODEL
array('image_file', 'file', 'types'=>'jpg, gif, png, jpeg', 'allowEmpty'=>true, 'maxSize'=>1024*1024/*1mb*/, 'tooLarge'=>Yii::t('default', 'File is too large')),