text:
Q: PDE with integral I came across the following functional equation :
$$\partial_t \phi(t,x) = a -(x+a)\phi(t,x)+ x \left[ \int_0^\infty \nu(x,y) \phi(t,y) dy \right]^2 $$
where $\nu(x,y)$ is a log-normal distribution function:
$$\nu(x,y)=\frac{1}{\sqrt{2\pi} \sigma y} \exp \left(-\frac{(\log y - \log x)^2}{2\sigma^2} \right)$$
In this, $a$ is positive, $x$ and $t$ are positive, and initial conditions are $\phi(0,x)=\phi_0$ for all $x$, $0 < \phi_0 < 1$.
I'm solving this numerically (by discretization of the integral) but I need a lot of values of $x$ and this takes a lot of computing time.
I'm wondering if there are some methods to simplify the computation or improve the convergence, or even better if there is a closed form !
I tried to find the limit as $t\rightarrow \infty$ but I cannot solve the integral equation, is there some way to do it ?
Edit :

*

*I tried to expand in $x$ as suggested below but the series is badly divergent because of $e ^{n^2}$ like terms and does not approximate well the numerical solution.

*I thought of defining an operator $$A[\phi(x)]=\int_0^\infty \nu(x,y) \phi(t,y) dy$$
and solve the differential equation as an ODE
$$\partial_t \phi = a - B \phi + x[A\phi]^2$$
and then interpret the solution as an analytic series of the operators $B$ and $A^{-1}$. Does this have any chance of succeeding, and if so how can we invert $A$ ?
Just to be clear, my main goal is to improve the speed and reliability of the numerical integration of the above equation (the computation is long and I have to cut off the integral at some point). I'll be also happy if some analytic properties of the solution can be found.

A: As I was looking at the Wikipedia page for the log-normal distribution I noticed that it apparently has the property.
$$E[X^n] = e^{n\mu + n^2 \sigma^2 /2}$$
This I find a bit suggestive as using your variation of the distribtion it seems to imply
$$\int_0^\infty \nu(x,y)y^n \, dy = e^{n\log x + n^2\sigma^2/2}= x^n e^{n^2 \sigma^2 /2}$$ meaning $x^n$ is sort of an eigenfunction of the integration operator. I'm sure that can be used somehow but my initial attempt to exploit it was just introducing a series representation of the function
$$\phi(t,x) = \sum_{n = 0}^\infty c_n(t)x^n$$
and inserting it into the equation. This doesn't seem to end up working but is at least an idea. Firstly
$$\int_0^\infty \nu(x,y)\phi(t,y)\, dy = \sum_{n = 0}^\infty c_n(t)x^ne^{n^2 \sigma^2 /2}$$
then squaring the series and applying cauchy product formula
$$\left (\sum_{n = 0}^\infty c_n(t)x^ne^{n^2 \sigma^2 /2} \right )^2 = \sum_{n = 0}^\infty \left (\sum_{k = 0}^n c_{k}(t)e^{k^2\sigma^2/2}c_{n-k}(t)e^{(n-k)^2\sigma^2/2} \right )x^n$$
followed by some simplifications
$$\left (\sum_{n = 0}^\infty c_n(t)x^ne^{n^2 \sigma^2 /2} \right )^2 = \sum_{n = 0}^\infty \left (\sum_{k = 0}^n c_{k}(t)c_{n-k}(t)e^{n(n - 2k)\sigma^2/2}\right )x^n$$
Plugging everything into the original equation we get this mess
$$\sum_{n = 0}^\infty c_n'(t)x^n = a - (x + a)\sum_{n = 0}^\infty c_n(t)x^n + x  \sum_{n = 0}^\infty \left (\sum_{k = 0}^n c_{k}(t)c_{n-k}(t)e^{n(n - 2k)\sigma^2/2}\right )x^n$$
where after collecting all the sums we finally obtain
$$\sum_{n = 0}^\infty c_n'(t)x^n = a - ac_0(t) + \sum_{n = 1}^\infty \left (\sum_{k = 0}^{n-1} c_{k}(t)c_{n-1-k}(t)e^{(n-1)(n-1- 2k)\sigma^2/2} - ac_n(t) - c_{n-1}(t)\right ) x^n$$
Then you can maaybe you could truncate this and set up differential equation
$$c_n'(t) = f_n(c_1(t), c_2(t), ..., c_N(t)), \quad (0\leq n \leq N)$$
where at least you don't have to deal with the integral anymore but the $e^{n^2\sigma^2/2}$-factors are kind of scary when it comes to convergence and I'm reserved as to whether it works.
EDIT A few hours later looking at this it makes a lot more sense to incorporate the exponential factors in the series expansion instead, that is starting from the series exansion $$\phi(t,x) = \sum_{n = 0}^\infty c_n(t)e^{-n^2 \sigma^2 / 2}x^n$$
$$\sum_{n = 0}^\infty c_n'(t)e^{-n^2 \sigma^2 / 2}x^n = a - ac_0(t) + \sum_{n = 1}^\infty \left (\sum_{k = 0}^{n-1} c_{k}(t)c_{n-1-k}(t)- ac_n(t)e^{-n^2 \sigma^2 / 2} - c_{n-1}(t)e^{-(n-1)^2 \sigma^2 / 2}\right ) x^n$$
Which renders a somewhat simpler form of the associated differential equation
$$c_n'(t) = e^{n^2\sigma^2/2}\sum_{k = 0}^{n-1} c_{k}(t)c_{n-1-k}(t) - ac_n(t) - c_{n-1} e^{(2n + 1)\sigma^2/2}, \quad (n \geq 1)$$

A: A change of variables helps. Put $u=\log(x)$, $v=\log(y)$, $\phi(t, x) = f(t, u)$. Define $n(w) = \frac{1}{\sqrt{2\pi}\sigma}\exp(\frac{-w^2}{2\sigma^2})$ so that $\nu(x, y) = y n(u-v)$. Then the PDE becomes:
$$\frac{\partial f(t, u)}{\partial t} = a - (e^u + a)f(t, u) + e^u \left[\int_{-\infty}^{\infty} n(u-v) f(t, v) \mathrm{d}v\right]^2$$
The integral is then just a convolution, which blurs $f$ on length scale $\sigma$. This constrains how many samples to take in the $u$ direction: the spacing (uniform in $u$ not $x$) should be no more than about $\sigma$. Also, the spacing should be no more than about 1 in order to represent the function $e^u$ properly. The question does not say so, but I'm guessing $\sigma \ll 1$, i.e. the former constraint is more important.
To study the stability, let us make an approximation. Suppose that $f$ is already fairly blurry on the relevant scale, so that blurring it further makes no difference. Then we can approximate the integral by $f(t, u)$. This gives a nice simplification:
$$\frac{\partial f}{\partial t} = (e^u f - a)(f-1)$$
There are two steady states: $f=1$ and $f=ae^{-u}$. Differentiate the RHS wrt $f$ at each of these points to show that the former is stable (attractive) if $e^u< a$ and the latter is stable if $e^u > a$. The question is kind enough to grant us $f<1$, so we are in the region of convergence for all $u$, and we can expect $f \rightarrow \min(ae^{-u}, 1)$ as $t \rightarrow \infty$.
This approximate analysis also gives us the rate of convergence: the time step needs to be less than about $e^{-u}$. It's a pity that this depends on $u$, but all the interesting behaviour occurs in a fairly small $u$ interval.
Without the approximation, I find it difficult to guess what will happen. I suppose you'll just have to try!


text:
Q: The adaptation of script to using Interpolation in 3D Here I need to interpolate my function in 3D. I already know how works interpolation but I didn't get how can I come to this interpolation function from my script. Actually, I already had few different trajectories which have a different number of points. That is why I need interpolation to decrease the number of points and make it equal. I tried to find an answer but couldn't find any.
So, here is my script:
C1 = np.add.accumulate(K)
C2 = np.array([0, 0, 0])
Kz = np.vstack((C2, C1));
x_new = Kz[:, 0];
y_new = Kz[:, 1];
z_new = Kz[:, 2];

-----here I don't know how to come to the next step
def f(x_new, y_new, z_new):
    return 2 * x_new ** 3 + 3 * y_new ** 2 - z_new

x_new = np.linspace(1, 940, 200)
y_new = np.linspace(940, 1568, 200)
z_new = np.linspace(1568, 2195, 200)
data = f(*np.meshgrid(x_new, y_new, z_new, indexing='ij', sparse=True))
my_interpolating_function = RegularGridInterpolator((x_new, y_new, z_new), data)
pts = np.array([[10, 950, 1600], [930, 1550, 2150]])
my_interpolating_function(pts)

Thank you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is whitespace between the two ='s in an equality operator legal in C++? I am currently learning C++ from 'Problem solving with C++' (9th, W. Savitch). The book shows an example of a while loop. The while loop looks as follows.
while (ans = = 'Y' || ans = = 'y')
{
    //compound statement
}

ans is of type char.
The boolean expression appears to be trying to use the equality operator, and in the context of the //compound statement this makes sense. However, I always thought whitespace was illegal within the equality operator. i.e == is legal, but = = is illegal.
When I copy the code and compile it, my compiler throws the error 'expected expression' when it hits = = as if I am trying to assign an expression to a variable. I am almost certain this is a typo within the book. However, just in case the book is trying to throw a curveball I thought I would ask...
Many thanks!

A:
Is whitespace between the two ='s in an equality operator legal in C++?

No. = = is two = tokens. == is one == token. You can't use the former when you mean the latter.


text:
Q: Mysql SELECT not working I have the tables:
users
ID | RANK | NAME | EMAIL       | PASS
01 |  1   | Foo  | foo@bar.com | $06$uhAMXXZowVIDQ.ZR1gky.u3f/UBkLW8Kd8cbyDt2eNx1qnZH2AUmW

allow
ID | RANK | STEP
01 |  1   |  1
02 |  1   |  2
03 |  1   |  3
04 |  2   |  1
05 |  4   |  *

And, I need to know all allowed steps from user rank.
My code:
SELECT users.*, allow.step AS allow_step
  FROM users AS users LEFT JOIN allow ON users.rank = allow.rank

But only one step are selected.
Thanks for help!

A:    SELECT u.*, GROUP_CONCAT(a.step) allow_step
     FROM users u
LEFT JOIN allow a
       ON u.rank = a.rank
 GROUP BY a.rank_id

This should select a list of steps separated by commas. Something like 1,2,3.

If you need the concatenated values to be ordered, change the first line of the query to:
   SELECT u.*, GROUP_CONCAT(a.step ORDER BY a.step) allow_step

A: The given SQL and data will yield three rows - and would even without the use of a LEFT JOIN (a simple JOIN would suffice).
You don't show or describe how you are running the SQL; do you need to fetch multiple rows in a loop, or use some 'fetch all rows' method?


text:
Q: Visual Studio 2015 projects start at 15mb I'm hoping someone can point me in the right direction as I can't seem to find anything about it over the last few days.
We're currently looking at upgrading from Visual Studio 2013 to 2015.  Whenever creating a new ASP.Net project, the project immediately starts at 15mb where previously it was only a few kb.
Items of note are the inclusion of the following files causing the project to bloat:

*

*Microsoft.Net.Compilers.1.0.0.nupkg file at 4.26mb

*Microsoft.CodeAnalysis.dll at 1.68mb

*Microsoft.CodeAnalysis.CSharp.dll at 3.90mb

*Microsoft.CodeAnalysis.VisualBasic.dll at 4.79mb

*

*Why are these files now being included in VS 2015?

*From what I have found online, the Compilers nugget contains the exact compiler to use on the project, though I can't figure out why it's not like all previous versions of VS as I'm running 2008, 2010, 2012, 2013 and 2015 on the same box and until now the others have worked just fine.

*I get the code analysis, but trying to create a quick example project completely bloats the project when I'm not even interested in it.  Also, why is both C# AND VB included when the project is only using C# for example?

A: Appears to be related to the Roslyn Compiler as indicated by this thread.  It really "feels" like VS2015 wasn't quite ready to be nudged out the nest but we'll see what update 1 holds.
For now I'll create VS2013 projects, upgrade them to 2015 and then check them into Source Control and continue from there.


text:
Q: Changing VkBuffers used in command with out re-building the command buffers? This might be an X Y problem, so here's my issue:
I'm trying to send a command buffer to the GPU that adds values to a shader buffer, eg:
#version 450
#define INPUT_ARRAY_SIZE 1024
layout(std430, binding = 1) buffer InputArray{
    float array[ ];
}input_array;

void main()
{

    uint index = gl_GlobalInvocationID.x;
    if (index >= INPUT_ARRAY_SIZE){
        return;
    }
    InputArray.input_array[index] += 3;
}

I would like to be able to swap out the VkBuffer I use to back the shader buffer with other buffers.  ie:
void addValue(device, queue, command_buffer, buffer);

or
void addValue(device, queue, command_buffer, descriptor_set);

where I would swap out buffer for other buffers I want to add values to.
Unfortunately I don't see a way to do that with out re-recording my command buffer.   As far as I can tell my only options for minimizing the command buffer impact (which is large when my invocations take nano seconds), is to use secondary command buffers, and use pipeline cache some how.  Otherwise I would have to create a command buffer for every single new buffer, which is not feasible when I have more than 100 commands. It doesn't seem to be possible to use VkUpdateDescriptorSets with out re-recording as well.
Is there a way to use pre-recorded command buffers, and change the VkBuffer used behind the shader buffer at will with out re-recording the command?

A: Not without the EXT_descriptor_index extension. Descriptor values (the location of the GPU resources they represent) are supposed to be baked into the CB at write time, not read from some external source.
Even with descriptor index, you need to ensure that the CB is not being executed before you can update the descriptor. So that would require a GPU/CPU sync (which may or may not be bad, depending on your semaphore/submission code structure).

Otherwise I would have to create a command buffer for every single new buffer, which is not feasible when I have more than 100 commands.

You should not put each command in its own buffer. You should bundle as many commands together as possible.
In general, the cost of building command buffers is pretty low. Coupled with threading their construction, they shouldn't be your primary concern here. Especially when the number of commands is as low as "more than 100 commands;" Vulkan users routinely issue thousands of commands into CBs repeatedly, every frame.


text:
Q: See which option was just selected in a multiselect I have a multiselect bootstrap picker and would like to find the specific option that was just selected. For example, if I have the picker set to something like this:
<select class="form-select selectpicker" multiple aria-label="Default example">
<option value="Apple">Apple</option>
<option value="Cherry">Cherry</option>
<option value="Papaya">Papaya</option>
<option value="Kiwi">Kiwi</option>
</select>

When the user selects their first option, "Cherry", I would like to alert("Cherry"). When the user then selects their second option, "Apple", I would like to alert("Apple").
I have tried to use the option:selected:last value, but this only works to display the last option in the array of selected option. I would like to display the option that was most recently selected, regardless of its place in the array of selected options. Any insight is greatly appreciated.
EDIT: This questions was closed due to being marked as similar to the question found here: Get selected value in dropdown list using JavaScript
After looking through all of the provided answers in that link, I am not convinced that the questions are the same. I would like to get the most recently selected text in a multiselect picker, not the only selected option in a single select. So, if a user has both Apple and Papaya options selected, but selected the Apple option after selecting the Papaya option, I would like to alert("Apple"). Thanks.

A: Here Are Two Methods By which you can Use Alert.
First Method: With OnChange
<select class="form-select selectpicker" multiple aria-label="Default example" onchange = "alert(this.value)">
<option value="Apple">Apple</option>
<option value="Cherry">Cherry</option>
<option value="Papaya">Papaya</option>
<option value="Kiwi">Kiwi</option>
</select>

Second Method: Involves An Event Listener But Its Doing The Same Thing(Javascript)(Assuming That The ID of The Select Tag is selector
function change(){
    alert(this.value)
}
document.getElementByID("selector").addEventListener("onchange",change)


text:
Q: Store each character of a String in a list I have a list object of Strings as given below:
s = ['ABC','DEF','GHI','JKL']

I want to store the individual characters as a list of list items separately as below:
output = [['A','B','C'],['D','E','F'],['G','H','I'],['J','K','L']]

I know I can extract the individual items using their indexes. But am not able to store them in the above given manner. Could someone please help me out..!

A: use a list comprehension:
In [24]: s = ['ABC','DEF','GHI','JKL']

In [25]: lis=[list(x) for x in s]

In [26]: lis
Out[26]: [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I'], ['J', 'K', 'L']]

or use map():
In [27]: lis1=map(list,s)

In [28]: lis1
Out[28]: [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I'], ['J', 'K', 'L']]

A: You can make a list from a str:
output = map(list, s)


text:
Q: Vector spaces, subspace. Examine that $W$ is a subspace of the vector space $M_{3x3}$
$W=({A:det(A) \ge} 0)$
I have two conditions:
1) $ \vec u + \vec v \in W $
2) $ \alpha \cdot \vec u \in W $
$ B,C \in W $
$det(B) + det(C) \ge 0 $
I don't know any properties of determine of matrix which could help with these.

A: $W=\{A\colon \det A\geq 0\}$ is not a subspace of the vector space $M_{3\times3}$ (I assume it is over the reals). Take for example
$$
I=\begin{bmatrix}
1 & 0& 0\\
0&1&0\\
0&0&1
\end{bmatrix}.
$$
Obviously $\det I=1$ and $I\in W$. Now take $(-1)I$ and observe that $\det (-1)I=(-1)^3\det I$.

A: This claim is not true:
First, note that $A=diag(-2,-8,1),B=diag(3,3,3)\in W$ but $A+B\not\in W$.
Moreover, if $A\in W$ then $|-A|=(-1)^{3}|A|\leq0$ and so $-A\in W$
iff $|A|=0$ but there are matrices in $W$ with non-zero determinant


text:
Q: Advantage of within transformation over pooled OLS with dummies? First, apply the within transformation (fixed effects transformation) on a panel data set. Then, apply pooled OLS with dummies for each cross-sectional unit on the same panel data set.
When you compare both regression results you get exactly the same estimates of the coefficients for the exogeneous variables, also the standard errors and the t-values are the same.
Even the unit-specific dummy estimates are equal to the unit-specific unobserved effects you can estimate after applying the within transformation regression. Well, there is one caveat in this respect: You have to add the intercept of the pooled OLS regression to a dummy estimate to get the respective unobserved effects estimate from the within transformation.
The only difference I figured out, is that the within transformation appears to be less efficient in estimating the unit-specific unobserved effects. So, ceteris paribus, the p-values of the unit-specific dummy estimates for the pooled OLS dummy regression are lower than the p-values of the unit-specific unobserved effects from the within transformation (I'm not sure why that happens?).
Hence, performing a pooled OLS regression with unit-specific dummies appears to be supperior to performing a basic within transformation regression. Still, the latter appears to be more often applied. Is there a reason for that? To come back to the title of this post: Is there an advantage of a within transformation over pooled OLS with dummies?
EDIT:
So, as I understood, there appears to be only a computational advantage of the within transformation. Now, the essential question for me is: Why are the p-values of the unit-specific dummy estimates for the pooled OLS dummy regression lower than the p-values of the unit-specific unobserved effects from the within transformation? This really baffles my mind. Because, for small panels (where the computational burden is low), the dummy regression would be advantageous over the within transformation as it yields estimates of the unobserved effects (dummies) with lower p-values?!
EDIT #2:
See @ChristophHanck's answer, which solved the mistery of getting different p-values. I incorrectly included an intercept into the pooled OLS dummies regression. After excluding the intercept, the p-values where the same for both models.

A: As stated in the comments, given that either way of computing the fixed effects leads to numerically the same estimates, there should also be no reason to expect either approach to be more "efficient" (in the statistical sense of an estimator's property), and thus to lead to smaller p-values. This is also not the case, as this illustration demonstrates:
library(plm)

# generate some data
m = 2
n = 20
beta = -2
alpha = rep(runif(n), each=m)
X <- rnorm(m*n)
u <- rnorm(m*n)
y <- alpha + X*beta + u

paneldata <- data.frame(rep(1:n,each=m),rep(1:m,n), y, X) # first two columns are for plm to understand the panel structure
within.reg <- plm(y~X, data = paneldata, model = "within")
FEs <- fixef(within.reg) # retrieve fixed effect estimates
summary(FEs) # report these along with p-values

# dummy approach
dummy.matrix <- matrix(c(rep(1,m), rep(0,n*m)), nrow = n*m, ncol= n) # throws a warning, but indeed intended here as vector is longer than column dimension so that the recycling R then does starts at the right position in each new column
summary(lm(y~dummy.matrix+X-1)) # intercept suppressed to avoid nmulticollinearity, as we have one dummy per unit

# same p-values:
all.equal(summary(FEs)[,4], summary(lm(y~dummy.matrix+X-1))$coefficients[1:n,4], check.attributes = F) # TRUE

The numerical advantages I mention below only refer to the work the computer has to do - they are irrelevant to the statistical precision of the estimator and hence have no impact on the p-values etc.
One point where our approaches might differ that I could think of is that you talk about an overall intercept that you add in a pooled regression (amounting to summary(lm(y~dummy.matrix+X)) in the code above). Then, the individual-specific intercepts would measure the distance to that overall intercept (omitting one category which serves as the baseline category) and thus also produce different point estimates. Correspondingly, p-values would be for the hypothesis that the intercepts differ significantly from the overall intercept, and not from zero.
Of course, if different hypotheses are tested, there is no longer a reason to expect p-values to agree.
The situation is analogous to the textbook example of avoiding the dummy-variable trap of either specifying an intercept and a, say, dummy for women or no intercept and dummies for both men and women (assuming of course that everybody in the dataset identifies himself/herself as either man or woman).


text:
Q: How can I go about sorting pushout vectors in collision resolution? Recently I've been working on my game and so far I've got SAT collision detection-resolution working fine (I can detect two polygons intersecting and figure out the correct vector to push one out of another ('pushout' vectors))
However, I have run into a problem when applying the pushout vectors to other polygons. When a polygon gets into contact with 2 or more polygons, I end up with 2 or more pushout vectors, which need to be applied in the right order to get a realistic result (aka not glitching through the other polygons or getting stuck on corners that aren't there)
Currently, I apply every push vector and each time I apply it I check if the polygon is still intersecting with the others it collided with, if so, I keep applying the rest of the vectors. If not, just stop applying as they are not colliding anymore.
The issue with this is that I need to apply the vectors in a specific order, not just in the other they are in the list. I dont know of a good solution to ordering them.
Here's my code (collider is the object that needs to have the pushout vectors applied to it) (otherColliders is a list of colliders that the collider is intersecting):
List<Vector2> pushoutVectors = getPushoutVectors(otherColliders);

foreach (Vector2 pushout in pushoutVectors)
{
    collider.Transform.Position += pushout;

    if (!collider.checkForIntersecting(otherColliders))
        break;
}

The picture below shows my current issue. Is there a solution to getting vector (-1, 0) before (0, 1)?

A: The solution was to sort based on distance from the centre of each collider. Do not sort from the origin point or similar - sort by the distance between the centre of both colliders in ASCENDING order. This ensures that the pushout vectors are applied properly and no clipping or getting stuck occurs.
sample code:
public struct Hit
{
    public Collider Me;
    public Collider Other;
    public Vector2 Pushout;

    public float getCenteredDistanceFromOtherSquared()
    {
        return Vector2.DistanceSquared(Me.getWorldBounds().Center, Other.getWorldBounds().Center);
    }
}

List<Hit> hits = getHits(otherColliders);

// note: this is a long function name for the sake of being clear.
// it returns the distance between the 'collider' and the 'other' collider in the collision
// its squared simply because we just need to order by size not get the actual size, so its just to prevent use of a performance-costly sqrt function
List<Hit> sortedhits = hits.OrderBy(x => x.getCenteredDistanceFromOtherSquared()).ToList();

foreach (Hit hit in sortedhits)
{
    // apply pushout
    collider.Transform.Position += hit.Pushout;

    // check if we're still colliding with any other colliders
    // if we aren't, stop applying hits
    // if we are, keep applying hits
    // this is to prevent getting stuck on edges and such
    if (!collider.checkForIntersecting(otherColliders))
        break;
}


text:
Q: PCIe End-Point configuration for communication with Root Complex I have an ambiguity regarding the PCIe initial configuration which is performed by the root complex (RC) on the end-points (EP).
Both devices have their own base address registers (BARs). The RC configures an address on the EP BAR. What does that address represent?
Also, how does the EP know the value of the RC BARs to initiate some read or write transactions with the RC as only RC can send configuration read/write requests? I have read the specification document but still don't fully understand the mechanism.
Clarity on the above would be greatly appreciated.

A: When an endpoint has some memory - be that physical RAM, control/status registers, Flash, etc. - the system needs some way of knowing how to address that memory. Remember that software running in the system uses memory addresses to access data. By assigning a physical address to the device, the memory can be accessed by software just like any other memory.
The address programmed into the BAR on an endpoint represents the physical memory address in the system that software can use to communicate with the corresponding memory in the endpoint. An EP can have up to 6 of these regions. The lower N bits of the BAR will always be 0, where N is the width of the memory. For example if you had a 64kWord memory on your EP, that would be a 16b wide word address, so the lower 16b of the BAR will be hardwired to 0's.
The EP doesn't necessarily know the address values of the RC. It doesn't initially need to. EPs start as being passive devices - only responding to requests from the RC. If they need to send their own write and read requests, the OS must configure them to be capable of performing bus mastering.
Once capable of bus mastering, software on the system (typically device driver) will configure the device to initiate requests - for example if you wanted to DMA a chunk of data from say system RAM to your device or vice versa, the driver would work out the physical memory address it is required to communicate with and send that information to the EP as part of setting up an operation.
If you have two PCIe devices that are intended to talk directly to each other (P2P), again it would be up to the device driver or other such software to read the BAR addresses for the two EPs and pass that information to both devices so that they know how to address each other.

A: There is only a single address space, and it is decoded from the root complex downwards.
The root complex acts as a bridge between the platform bus and the PCIe domain below it, so the addresses programmed into the RC are the (memory, IO and bus) ranges that exist in this domain, anything included in the range is expected to be connected to a downstream port, anything not included is connected elsewhere -- so this is basically the routing table for address-based routing.
Endpoints can initiate (bus/device/function routed) messages to other devices in the same domain, and (address routed) transactions to any destination in the system, including main memory and other devices.
Driver software is responsible for writing working addresses into hardware registers, for example you could have a register pointing to a DMA buffer, and that DMA buffer could be located on another device (in which case the address is inside the ranges programmed into all bridges above that device, so the access is routed correctly).
The mechanism for storing another device's (bus/device/function or memory) address is not specified in PCI(e), because that will depend on the requirements of the application.


text:
Q: Logistic regression with partially observed variables Let's say I have a binary variable to explain using "some" logistic regression approach. The set of variables I have at disposal are exhaustive for a given period of time and for a longer period a subset of those data are missing.
I think this is a very common issue and was looking for some references about the classic (or maybe more exotic) methodologies available to deal with this kind of situation.
Ideally, I would like to fit the model to all the available data without filling the missing value with best estimates. I was thinking that maybe nesting model or conditionning appriopriately would be possible.

A: I guess you'd have to move towards data augmentation techniques. Introductions are given in this rather old article by Van Dyk and Meng and more generally, but also from some time ago in Pigott's article on missing data. These could be good starting points for your literature research.
The machine learning field is quite extensively covered on Wikipedia and reading up on expectation–maximization (EM) algorithm could also be a good starting point for you.
This literature is quite varied, and some methods are well developed and incorporated in standard statistical software packages, while others are rather basic. Generally, the ideal method depends on the finer peculiarities of your data and the desired type of inference. So if you could provide more information on that part, people here will be more likely to provide specific help.


text:
Q: TYPO3 blog posts in one page I am quite new to TYPO3 and i am trying to build something which i am not sure how to do!
I have installed the T3G/blog extension.
On my website i have a "Blog" page, where i would like to show the blog posts like this (for each post):

*

*Post Title

*Post Date

*Full Post Content

*Post Author

I imagine i have to use a for loop to go through the blog posts available, but i can't find a way to make it work.
Right now i have something like this:

   <f:debug>{_all}</f:debug>

The output of the debug is an array with my posts, but now my question is:
how can i render the right information on the right place?
Thank you!

A: You have to loop through all posts of a blog.
<f:for each="{blog.posts}" as="post">

{post.title}

{post.content}

</f:for>

There are so many tutorials about blog. Have a look at https://docs.typo3.org/typo3cms/ExtbaseFluidBook/3-BlogExample/Index.html

A: Debug
When you see the output in your debug, you can use the information in your template. Say your debug output sais the following:
 - Blog
  > Headline
  > Text

You can call these items in your template as {blog.headline} (for example).
Using original files as base for your own template

*

*I suggest taking a look at the default templates provided. You can find these template in your typo3/typo3conf/ext/{extension}/Resources/Private Folder.

*Take a look at the tags being used! You can use these in your template.

*You should download the Layouts, Partials and Template folder, and upload these in your fileadmin/{blogmodule}/ folder. Set the path in TypoScript, You'll probably find an example in the plugin documentation.


text:
Q: how to get entire document in scrapy using hxs.select I've been at this for 12hrs and I'm hoping someone can give me a leg up.
Here is my code all I want is to get the anchor and url of every link on a page as it crawls along.
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from scrapy.utils.url import urljoin_rfc
from scrapy.utils.response import get_base_url
from urlparse import urljoin

#from scrapy.item import Item
from tutorial.items import DmozItem

class HopitaloneSpider(CrawlSpider):
name = 'dmoz'
allowed_domains = ['domain.co.uk']
start_urls = [
    'http://www.domain.co.uk'
]

rules = (
    #Rule(SgmlLinkExtractor(allow='>example\.org', )),
    Rule(SgmlLinkExtractor(allow=('\w+$', )), callback='parse_item', follow=True),
)

user_agent = 'Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))'

def parse_item(self, response):
    #self.log('Hi, this is an item page! %s' % response.url)

    hxs = HtmlXPathSelector(response)
    #print response.url
    sites = hxs.select('//html')
    #item = DmozItem()
    items = []

    for site in sites:

                   item = DmozItem()
                   item['title'] = site.select('a/text()').extract()
                   item['link'] = site.select('a/@href').extract()

                   items.append(item)

    return items

What I'm doing wrong... my eyes hurt now.

A: response.body should be what you want
def parse_item(self, response):
    #self.log('Hi, this is an item page! %s' % response.url)

    body = response.body
    item = ....

A: To get all links on a single page:
def parse_item(self, response):
  hxs = HtmlXPathSelector(response)
  items = []
  links = hxs.select("//a")

  for link in links:

                 item = DmozItem()
                 item['title'] = site.select('text()').extract()
                 item['link'] = site.select('@href').extract()

                 items.append(item)

return items


text:
Q: How can I access my static variable from other page? Enqueue / Dequeue I'm enqueuing the incoming customer in my KioskController.
public ActionResult SetQueueInfo([Bind(Include = "QueueId,Name,QueueNumber,ServiceId,ServiceName,ServiceLetter")] Queue queue/*, int? id,string Name, string QueueNumber, string ServiceLetter, int ServiceId*/, int? id)
{
    if (ModelState.IsValid)
    {
        MyQueue.todayQueue.Enqueue(queue);
        db.Queues.Add(queue);
        db.SaveChanges();
        return View(queue);
    }

    return View();
}

I want to Dequeue it on my TellerScreenController how can I use the static variable to Dequeue it,
Here is my TellerScreenController:
    public ActionResult BtnNext()
    {
        var first = MyQueue.todayQueue.Dequeue();

        TempData["QueueItem"] = first;

        return View();
    }

Here is my Queue Class:
public class MyQueue
{
    public int MyQueueId { get; set; }

    public string Name { get; set; }

    public string QueueNumber
    {
        get
        {
            return string.Format("{0}{1:000}", ServiceLetter ?? "?", QueueId);
        }
        set { }
    }

    public static Queue<MyQueue> todayQueue = new Queue<MyQueue>();

    public string ServiceLetter { get; set; }

    public virtual Service Service { get; set; }
}

A: You can create a class for TodayQueue
public class QueueHelper{
     public static Queue<Queue> TodayQueue = new Queue<Queue>();
}

In Kios controller
public ActionResult SetQueueInfo([Bind(Include = "QueueId,Name,QueueNumber,ServiceId,ServiceName,ServiceLetter")] Queue queue/*, int? id,string Name, string QueueNumber, string ServiceLetter, int ServiceId*/, int? id)
{
    if (ModelState.IsValid)
    {
        QueueHelper.TodayQueue.Enqueue(queue);
        db.Queues.Add(queue);
        db.SaveChanges();
        return View(queue);
    }

    return View();
}

In Teller screen
  public ActionResult BtnFinish()
    {
        var first = QueueHelper.TodayQueue.Dequeue();

        TempData["QueueItem"] = first;

        return RedirectToAction("Index");
    }

In Index cshtml view
@{
   var item = (MyQueue)TempData["QueueItem"];
}

<p>@item.Name</p>


text:
Q: Macbook 8,1 Ubuntu 12.10 CPU Heat Installed Ubuntu on another partition on my Macbook, which works well sorted the wifi but the problem is that the heat coming off the thing is mental. The fans are going to cool it, and i have installed macfanctl which seems to have helped a little but its still way to hot for idle.
I have managed to boot with EFI yet going to try and sort that but, is that the only factor? Any help with this would be great really want to move from OSX to ubuntu but this will just not work with the heat. I have heard that if i boot with EFI then the graphics switching will work which would be great so im going to try and get that working, but the CPU heat is still a issue.
Thanks

A: Thanks Merri.
It was related to EFI, now that I am booting from grub-efi, heat and battery performance are much better. The CPU is still slightly warmer than in OSX but not by too much, idles at around 45 - 55 which is quite good for a laptop. If you are having similar problems I would suggest using EFI boot instead of the legacy BIOS.
Here is a post i put on the UBuntu forums on the problem an solution.
http://ubuntuforums.org/showthread.php?t=2104817
Bill


text:
Q: undefined is not an object react native I am not having any idea why i am getting

"undefined is not an object (evaluating
  '_this.props.navigation.navigate')"

I am new bie in react but i have gone through each possible solution but still getting this err. I am sharing my code below:
App.js
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Login from './app/components/Login/Login';
import Dashboard from './app/components/Dashboard/Dashboard';
import {StackNavigator} from 'react-navigation';

const Application = StackNavigator({
        Home: { screen: Login },
        Dashboard: { screen: Dashboard },
    }, {
        navigationOptions: {
            header: false
        }
});

export default class App extends React.Component {
  render() {
    return (
        <Application />
    );
  }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
});

Login.js
import React from 'react';
import { StyleSheet, View, Image, Text, TextInput, KeyboardAvoidingView } from 'react-native';
import LoginForm from './LoginForm';
import {StackNavigator} from 'react-navigation';

export default class Login extends React.Component {

    render() {
        return (
            <KeyboardAvoidingView behavior='padding' style={styles.container}>
                <View style={styles.logoContainer}>
                    <Image source={require('../../images/logo.png')}
                           style={styles.logo}
                    />
                </View>
                <Text style={styles.title}>Share Emotions Instantly..</Text>
                <View style={styles.formContainer}>
                    <LoginForm></LoginForm>
                </View>
            </KeyboardAvoidingView>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#bdc3c7',
        alignItems: 'center',
        justifyContent: 'center',
    },

    logoContainer: {
        alignItems: 'center',
        justifyContent: 'center'
    },

    logo: {
        width: 70,
        height: 70
    }
});

LoginForm.js
import React from 'react';
import { StyleSheet, View, TextInput, TouchableOpacity, Text, Alert } from 'react-native';
import Dashboard from '../Dashboard/Dashboard';
import {StackNavigator} from 'react-navigation';

export default class LoginForm extends React.Component {

    constructor(props) {
        super(props);
    }

    onButtonPress = () => {
        alert('ok');
        const { navigate } = this.props.navigation;
        navigate('Dashboard');
    }

    render() {
        return (
            <View style={styles.container}>
                <TextInput underlineColorAndroid="transparent"
                           style={styles.input}
                           placeholder="username or email"
                           placeholderTextColor='rgba(255,255,255,0.5)'
                           returnKeyType="next"
                           keyboardType="email-address"
                           autoCapitalize="none"
                           autoCorrect={false}
                           onSubmitEditing={() => this.passwordInput.focus()}>
                </TextInput>

                <TextInput underlineColorAndroid="transparent"
                           style={styles.input}
                           placeholder="password"
                           placeholderTextColor='rgba(255,255,255,0.5)'
                           returnKeyType='go'
                           ref={(input) => this.passwordInput = input}
                           secureTextEntry>
                </TextInput>

                <TouchableOpacity style={styles.buttonContainer}
                                  onPress={this.onButtonPress}>
                    <Text style={styles.buttonText}>Login</Text>
                </TouchableOpacity>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        padding: 20
    },

    input: {
        height: 40,
        marginBottom: 15,
        backgroundColor: 'rgba(255,255,255,0.2)',
        paddingHorizontal: 10,
        width: 300
    },

    buttonContainer: {
        backgroundColor: '#888',
        paddingVertical: 10
    },

    buttonText: {
        textAlign: 'center',
        color: '#fff',
        fontWeight: '700'
    }
});

Dashboard.js
import React from 'react';
import { StyleSheet, View } from 'react-native';
import {StackNavigator} from 'react-navigation';

export default class Dashboard extends React.Component {
    render() {
        return (
            <View style={styles.container}>
                <Text>this is Dashboard</Text>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1
    }
});

I know this is a common issue, but I'm still not getting why 'navigation' object has not passed through as props to the other components.

A: The navigation property will be injected into all screens that you add to the route configs for ScreenNavigator (in your case Home and Dashboard).  However, for child components of those screens you will have to pass down the navigation property.
<LoginForm navigation={this.props.navigation} />


text:
Q: How to force child div to overflow it's parent width but only to the width of the screen So let me start with the JSFiddle example - click here.
The problem is with the styling/positioning of the div with class class="overflow-parent". The name of the class is descriptive for the current problem, but in fact it's the div that's supposed to display the site content.
The horizontal divs and the vertical div with the red border are for the navigation features that I'll provide and I want my content to be displayed inside them which in terms of this example means :

*

*The content (the green-bordered div with aaaaa.. paragraph should be positioned next to the red vertical menu and not overflowing it too like it's happening right now.

*The class="overflow-parent" should overflow it's parent on the right side but only to reach the size of the screen. Not as you can see now - with the horizontal scroll.

Also as sub problems - I would like my vertical menu (the red-bordered div) to be at least with the height of the display and if the content is bigger then the height of the screen then to adjust it's height to be equal with that of the <div class="overflow-parent"> which is supposed to show the page content.
Also - I don't have much experience with designing but the structure and the approach are entirely mine and it's possible to have a much better and/or easier approach to achieve the final result and I don't mind such an answer. Just to keep the same final appearance as it is now (without the problem ofcourse).
EDIT
It's important to keep the navigation centered, that's why the .container class is
.container {
  width: 970px;
  padding-left: 0px;
  padding-right: 0px;
  margin-right: auto;
  margin-left: auto;
}

I need it 970px; and centered, so it's expected to have white space on both ends. The tricky part is that because of the vertical menu the left side will remain empty white, but I want to use the right side at it fullest but not exceeding the width of the screen.

A: The content (the green-bordered div with aaaaa.. paragraph should be positioned next to the red vertical menu and not overflowing it too like it's happening right now.
Remove the position: absolute;
The class="overflow-parent" should overflow it's parent on the right side but only to reach the size of the screen. Not as you can see now - with the horizontal scroll.
Setting the width to auto (width: auto;) should solve this.
I add some properties:
to .vertical-menu
width: 25%;

to .overflow-parent
  width: auto;
  max-width: 72.6%; /* -(.4%) to compesate the border width */
  word-wrap:break-word; /* To prevent big words to break the layout */

http://jsfiddle.net/A5wge/4/


text:
Q: How can I achieve such layout in LaTeX (memoir)?
Before "Exercise 1.2", the page has 'margin note' and 'body' on its own but after that, the 'body' seems to have merged with the 'margin note'. I want to have the similar layout on my book.
\documentclass[10pt]{memoir}
\setstocksize{10in}{8.5in}
\setpageml{0.9\stockheight}{0.9\stockwidth}{*}
\setlrmarginsandblock{1in}{2in}{*}
\setulmarginsandblock{0.75in}{0.75in}{*}
\checkandfixthelayout[fixed]

\usepackage[]{showframe}
\usepackage{graphicx}
\usepackage{xsim}

\begin{document}
\chapter{Lorem Ipsum}
\lipsum[1]

\marginparmargin{outer}
\marginpar{%
\centering
\includegraphics[width=4cm]{example-image-a}}

\begin{exercise}    %   this environment needs to typeset throughout the paper width
\lipsum[2]
\end{exercise}
\end{document}


text:
Q: How to add hash after domain in every url in react js I have one application in react which are working on fine and I am developing  new app in react and its working in local machine when I uploaded on server it not worked when I added hash after domain it working, the old app also having hash in url. I did not get how to add the hash in url for every page. If I open url it will automatically add hash like this

www.example.com/#/signin
www.example.com/#/about

A: Change <BrowserRouter> to <HashRouter>


text:
Q: Which distribution has the following variance formula? Given a set of data $x_i$, for $i=1\ldots N$. I know their variance is calculated by
$$\sigma^2 = A \sum_{i=2}^N \ln^2\left(\frac{x_i}{x_{i-1}}\right)$$
where $A$ is a constant.
how can I determine how my data set is distributed?


text:
Q: Make your collections thread-safe? When designing a collection class, is there any reason not to implement locking privately to make it thread safe? Or should I leave that responsibility up to the consumer of the collection?

A: Thread safe collections can be deceiving. Jared Par posted a couple of interesting articles about thread safe collections:

The problem is there are several
levels of thread safe collections.  I
find that when most people say thread
safe collection what they really mean
"a collection that will not be
corrupted when modified and accessed
from multiple threads"
...
But if building a data thread safe
list is so easy, why doesn't Microsoft
add these standard collections in the
framework?
Answer: ThreadSafeList is a
virtually unusable class because the
design leads you down the path to bad
code.
The flaws in this design are not
apparent until you examine how lists
are commonly used.  For example,  take
the following code which attempts to
grab the first element out of the list
if there is one.

static int GetFirstOrDefault(ThreadSafeList<int> list) {
    if (list.Count > 0) {
        return list[0];
    }
    return 0; }

This code is a classic race condition.  Consider the case where there is only one > element in the list.  If another thread removes that element in between the if statement and the return statement, the return statement will throw an exception because it's trying to access an invalid index in the list.  Even though ThreadSafeList is data thread safe, there is nothing guaranteeing the validity of a return value of one call across the next call to the same object

http://blogs.msdn.com/b/jaredpar/archive/2009/02/11/why-are-thread-safe-collections-so-hard.aspx
http://blogs.msdn.com/b/jaredpar/archive/2009/02/16/a-more-usable-thread-safe-collection.aspx

A: Collection classes need to be as fast as possible. Hence leave the locks out.
The calling code will know where the locks best lie the collection class doesn't. In the worst case scenario the app will have to add an additional lock meaning that two locks occur making it double the perf hit.

A: I personally would leave it up to the consumers.  It will make your collection class more generic.

A: Just be clear in your documentation that your are not making it thread safe and leave it out, or if, for your application, you want it thread safe, make it thread safe and note that in your documentation for it.  The only rule is to document it.  Other than that, make your class for you and if other people want to use it, they can.

A: If I'm looking for a collection class and I need thread safe capabilities and your class doesn't have them, I'm immediately going to skip to the next offering out there to see what they provide.  Your collection won't get any more of my attention.
Note the "If" at the beginning.  Some customers will want it, some will not, and some won't care.  If you're going to build a tool-kit for consumers, then why not offer both varieties?  That way I can choose which one to use, but if I want thread-safe you still have my attention and I don't have to write it myself.

A: Making the collection threadsafe is what killed Java's Vector and Hashtable classes.  It is far easier for a client to wrap it in a threadsafe wrapper, as previously suggested, or to synchronize data access on the subset of methods, than to take a synchronization hit every time the class is accessed.  Hardly anyone uses Vector or Hashtable, and if they do, they get laughed at, because their replacements (ArrayList and HashMap) are worlds faster.  Which is unfortunate, as I (coming from a C++ background) much prefer the "Vector" name (STL), but ArrayList is here to stay.

A:
is there any reason not to implement locking privately to make it thread safe?

It depends. Is your goal to write a collection class which is accessed by multiple threads?
If so, make it thread safe. If not, don't waste your time. This kind of thing is what people refer to when they talk about 'premature optimization'
Solve the problems that you have. Don't try to solve future problems that you think you may have some years in the future, because you can't see the future, and you'll invariably be wrong.
Note: You still need to write your code in a maintainable way, such that if you did need to come along and add locking to the collection, it wouldn't be terribly hard. My point is "don't implement features that you don't need and won't use"

A: For Java, you should leave unsynchronized for speed.  Consumer of the collection can wrap in a synchronization wrapper if desired.

A: The primary reason not to make it thread safe is performance.  Thread safe code can be 100s of times slower than non-safe code, so if you client doesn't want the feature, that's a pretty big waste.

A: Note that if you attempt to make any class thread-safe you need to decide on common usage scenarios.
For instance, in the case of a collection, just making all the properties and methods individually thread-safe might not be good enough for a consumer, as reading first the count, and then looping, or similar, would not do much good if the count changed after reading it.

A: Basically, design your collection as thread-safe, with locking implemented in two methods of your class: lock() and unlock(). Call them anywhere needed, but leave them empty. Then subclass your collection implementing the lock() and unlock() methods. Two classes for the price of one.

A: A really good reason to NOT make your collection thread-safe is for improved single-thread performance.  Example:  ArrayList over Vector.  Deferring thread-safety to the caller allows the unsynchronized use case to optimize by avoiding locking.
A really good reason to make your collection thread-safe is for improved multi-threaded performance.  Example:  ConcurrentHashMap over HashMap.  Because CHM internalizes the multi-threaded concerns, it can stripe locking for greater concurrent access more effectively than external synchronization.

A: This would make it impossible to simultaneously access a collection from several threads even if you know that the element you touch is not used by anyone else.
An example would be a collection with an integer based index accessor. Each thread might know from its id which index values it can access without worrying about dirty reads/writes.
Another case where you would get an unnecessary performance hit would be when data is only read from the collection and not written to.

A: I agree that leaving it up to the consumer is the right approach.  If provides the consumer much more flexibility as to whether the Collection instance is synchronized on or a different object is synchronized on.  For example, if you had two lists that both needed to be updated it might make sense to have them in a single sychronized block using a single lock.

A: If you make a collection class, do not make it thread safe. It's quite hard to do right (e.g. correct and fast), and the problems for your consumer when you do it wrong (heisenbugs) are difficult to debug.
In stead, implement one of the Collection APIs and use Collections.synchronizedCollection( yourCollectionInstance) to obtain a thread-safe implementation if they need it.
Just refer to the appropriate Collections.synchronizedXXX method in your class javadoc; it will make clear that you have considered thread-safety in your design and ensured the consumer has a thread-safe option at his disposal.

A: Here's a good start.
thread-safe-dictionary
But you will notice you lose one of the great features of collections - enumeration.  You cannot thread-safe an enumerator, it's just not really feasible, unless you implement your own enumerator which holds an instance lock back to the collection itself.  I would suspect this would cause major bottlenecks and potential deadlocks.

A: As of JDK 5 if you need a thread-safe collection I'd first see if one of the already implemented collections in java.util.concurrent would work.  As the authors of Java Concurrency In Practice point out (including the guy who wrote most of the classes) implementing these correctly is very difficult, especially if performance is important.
Quoting http://download.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html

Concurrent Collections
Besides Queues, this package supplies
  Collection implementations designed
  for use in multithreaded contexts:
  ConcurrentHashMap,
  ConcurrentSkipListMap,
  ConcurrentSkipListSet,
  CopyOnWriteArrayList, and
  CopyOnWriteArraySet. When many threads
  are expected to access a given
  collection, a ConcurrentHashMap is
  normally preferable to a synchronized
  HashMap, and a ConcurrentSkipListMap
  is normally preferable to a
  synchronized TreeMap. A
  CopyOnWriteArrayList is preferable to
  a synchronized ArrayList when the
  expected number of reads and
  traversals greatly outnumber the
  number of updates to a list.


text:
Q: sidenav generates drawer already declared for end I have the following code:
<mat-card class="settings-panel">
  <mat-card-title>
    Settings
  </mat-card-title>
  <mat-card-content>
    <mat-sidenav-container class="settings-container">
      <mat-sidenav #sides align="end" class="settings-sidenav" mode="side">
        <app-sides></app-sides>
      </mat-sidenav>

      <mat-sidenav #toppings align="end" class="settings-sidenav" mode="side">
        <app-toppings></app-toppings>
      </mat-sidenav>

        <button type="button" mat-button (click)="sides.open()">
          Sides
        </button>

        <button type="button" mat-button (click)="toppings.open()">
          Toppings
        </button>

    </mat-sidenav-container>
  </mat-card-content>
</mat-card>

And it appears to be working, but there's an error in the web console:
Error: A drawer was already declared for 'position'="end"

This makes me think I'm abusing the control, but I don't know how to proceed.

A: You declared mat-sidnav twice on the same side. Stick to one, or assign second
 to other side align="start"
 <mat-sidenav #sides align="end" class="settings-sidenav" mode="side">
    <app-sides></app-sides>
  </mat-sidenav>

  <mat-sidenav #toppings align="start" class="settings-sidenav" mode="side">
    <app-toppings></app-toppings>
  </mat-sidenav>

If you're really trying to create dynamic side nav on same side, you can try to get away with two sidenav-containers or render using ngIf or route to modify which component it shows
Side note, align is deprecated, it's position now.


text:
Q: different select options depending on the row I have a table set up like this

                Look
                Lease Company

                <select data-bind="options: $parent.leaseCompanies, optionsText: 'name', optionsValue: 'name', value: leaseCompany" />

My view model:
leaseCompanies(datacontext.lookups.applicationCompanies);

This returns an array with a name, type fields
Depending on the row I want to display different options:
For example:
Row 1, show all Type = 1, 2
Row 2, show all Type = 2
How would I go about doing this?

A: Set up a different array for each of the types you want.  If they are dynamic in length then set up child observable arrays of your leaseApplicationLooks and populate those by iterating through you list of lease companies.  It's pretty simple actual, just use plain all javascript loops


text:
Q: Numpy: Creation of a variable length sequence from a pandas data-frame Lets say that I have the following data frame:
df_raw = pd.DataFrame({"person_id": [101, 101, 102, 102, 102, 103], "date": [0, 5, 0, 7, 11, 0], "val1": [99, 11, 22, 33, 44, 22], "val2": [77, 88, 22, 66, 55, 33]})

What I want to achieve is create a 3 dimensional numpy array such that the result should be the following:
np_pros = np.array([[[0, 99, 77], [5, 11, 88]], [[0, 22, 22], [7, 33, 66], [11, 44, 55]], [[0, 22, 33]]])

In other words, the 3D array should have the following shape [unique_ids, None, feature_size]. In my case, the number of unique_ids is 3, the feature size is 3 (all columns except the person_id), and the y column is of variable length and it indicates the number of measurments for a person_id.
I am well aware that I can create an np.zeros((unique_ids, max_num_features, feature_size)) array, populate it and then delete the elements that I don't need but  I want something faster. The reason being is that my actual data-frame is huge (roughly [50000, 455]) which will result in a numpy array of roughly [12500, 200, 455].
Looking forward to your answers!

A: Here's one way to do it:
ix = np.flatnonzero(df1.person_id != df1.person_id.shift(1))
np.split(df1.drop('person_id', axis=1).values, ix[1:])

[array([[ 0, 99, 77],
        [ 5, 11, 88]], dtype=int64),
 array([[ 0, 22, 22],
        [ 7, 33, 66],
        [11, 44, 55]], dtype=int64),
 array([[ 0, 22, 33]], dtype=int64)]

 Details
Use np.flatnonzero after comparing df1 with a shifted version of itself (pd.shift) in order to get the indices where changes in person_id take place:
ix = np.flatnonzero(df1.person_id != df1.person_id.shift(1))
#array([0, 2, 5])

Use np.split in order to split the dataframe's columns of interest according to the obtained index:
np.split(df1.drop('person_id', axis=1).values, ix[1:])

[array([[ 0, 99, 77],
        [ 5, 11, 88]], dtype=int64),
 array([[ 0, 22, 22],
        [ 7, 33, 66],
        [11, 44, 55]], dtype=int64),
 array([[ 0, 22, 33]], dtype=int64)]

A: You could use groupby:
import pandas as pd

df_raw = pd.DataFrame({"person_id": [101, 101, 102, 102, 102, 103], "date": [0, 5, 0, 7, 11, 0], "val1": [99, 11, 22, 33, 44, 22], "val2": [77, 88, 22, 66, 55, 33]})

result = [group.values for _, group in df_raw.groupby('person_id')[['date', 'val1', 'val2']]]
print(result)

Output
[array([[  0, 101,  99,  77],
       [  5, 101,  11,  88]]), array([[  0, 102,  22,  22],
       [  7, 102,  33,  66],
       [ 11, 102,  44,  55]]), array([[  0, 103,  22,  33]])]

A: Another solution with xarray

Let's create the dimension implied by the duplicity of person_id
>>> df['newdim'] = df.person_id.duplicated()
>>> df.newdim    = df.groupby('person_id').newdim.cumsum()
>>> df           = df.set_index(["newdim", "person_id"])
>>> df
                  date  val1  val2
newdim person_id
0.0    101           0    99    77
1.0    101           5    11    88
0.0    102           0    22    22
1.0    102           7    33    66
2.0    102          11    44    55
0.0    103           0    22    33

For the sake of readability, we may want to turn df into an xarray.Dataset-object
>>> xa = df.to_xarray()
>>> xa
<xarray.Dataset>
Dimensions:    (newdim: 3, person_id: 3)
Coordinates:
  * newdim     (newdim) float64 0.0 1.0 2.0
  * person_id  (person_id) int64 101 102 103
Data variables:
    date       (newdim, person_id) float64 0.0 0.0 0.0 5.0 7.0 nan nan 11.0 nan
    val1       (newdim, person_id) float64 99.0 22.0 22.0 11.0 33.0 nan nan ...
    val2       (newdim, person_id) float64 77.0 22.0 33.0 88.0 66.0 nan nan ...

and then into a dimensionally-healthy numpy array
>>> ar = xa.to_array().T.values
>>> ar
array([[[ 0., 99., 77.],
        [ 5., 11., 88.],
        [nan, nan, nan]],

       [[ 0., 22., 22.],
        [ 7., 33., 66.],
        [11., 44., 55.]],

       [[ 0., 22., 33.],
        [nan, nan, nan],
        [nan, nan, nan]]])

Note that nan-values have been introduced by coercion.


text:
Q: Update values on multi level nested Object with javascript I have an Object on sessionStorage for which I need to update values on user input. I am able to update at the root of the Object but not the values that are nested on a deeper level.
request('http://localhost:7474/graphql/', query).then(data => {...}

sessionStorage.setItem('queryData', JSON.stringify(data));

function update(value){
    let prevData = JSON.parse(sessionStorage.getItem('queryData'));

    Object.keys(value).forEach(function(val, key){
        prevData[val] = value[val];
    });

    sessionStorage.setItem('queryData', JSON.stringify(prevData));
}

update({ maritalStatus: "single" });

So maritalStatus ends up been added and not replaced and I must replace the value:
Object: [,...]
   0: {id: "x", maritalStatus: "married"} //want to replace this value here
   maritalStatus: "single"  // this is where the value is been written

A: Your data in storage is an Array. So the way you are updating it like prevData[val] = value[val]; is adding another property to the array with index of maritalStatus and value of "single". The object at index 0 is untouched.
My suggested fix is to also include the id in your update call. Then loop through the array in storage and look for the object with the matching id.
Once the id matches update that object, or log if no id matches are found.

let dataInStorage = [{
  id: "x",
  maritalStatus: "married"
}];

function update(updateObj) {
  let prevData = dataInStorage;
  let id = updateObj.id;

  dataInStorage.forEach(function(data) {
    if (data.id === id) {
      Object.keys(updateObj).forEach(function(key, index) {
        data[key] = updateObj[key];
      });
    } else {
      console.log(`did not find object with id: ${id}`);
    }
  });
  console.log(prevData)
  //sessionStorage.setItem('queryData', JSON.stringify(prevData));
}

update({
  id: "x",
  maritalStatus: "single"
});


text:
Q: d3.js with a datepicker I want d3.js graph is selected by a date range chosen with my datepicker.
The d3.js code is as follows:
 </script>

The code views is the next:
  @extends('layouts.app')
  @section('title', 'Historical')
  @section('content')

   @lang('processdefinition.definition')

   @lang('processdefinition.executions')

     @lang('executions.processexecutions')

 @lang('executions.errors')

 @lang('executions.logvolume')

       @lang('executions.executiontime')

 @include('recursos.datepicker')

   <button id="demo" type="hidden" class="btn btn-primary btn-sm"              role="button"onclick="myFunction()">@lang('executions.search')</button>

  @extends('recursos.scatterplot')

 @endsection

I want to take the dates from the datepicker and uses this dates in d3.js to show only a range date in my graph.


text:
Q: Using wbimport on sql workbench/j with presto driver so I am using workbench to import a 160k line text file into a table code is:
Wbimport
-usepgcopy
-type=text
-endrow=164841
-file='book1.csv'
-table=it.table1
-delimiter=,
-multiline=true

So I have tried this with a 3 line version of my 160k line file and it completed in a few seconds. This only seems to complete in auto commit mode, and when I try to run it on the full 160k line file it takes over 200h to complete any idea why - or alternatives.
I am using workbench build 125 and presto jdbc-0.216
Thanks

A: Most likely the reason is that the overall transaction gets to large and this imposes too big a load on wbimport and the jdbc connection. It would probably work much faster if you break this up into separation imports of e.g. 1000 records per import.
If you cut up the file first into multiple files and then import them one at a time, you are also avoiding the repeated read of the large file to find the right record.


text:
Q: VBA - Set Range Between Two Dates Using Search Function I'm trying to get my VBA code to search through a column for a user-inputted value (on a form) and set a range based on the values.
I need the code to scan DOWN through the column until it finds the value (which is a date) and then scan UP through the column to get the second part of the range. I need it to be like this because there might be multiple instances of the same date and they all need to be accounted for.
I've tried this:
StartRange = ws.Cells.Find(What:=StartDate, SearchOrder:=xlRows, _
    SearchDirection:=xlNext, LookIn:=xlValues)

EndRange = ws.Cells.Find(What:=EndDate, SearchOrder:=xlRows, _
    SearchDirection:=xlPrevious, LookIn:=xlValues)

But it's not working the way I had expected and is erroring. (Edit: the WS has been defined, so I know that's not the issue). I don't even know if I'm going about this the right way
I'm feeling defeated :(
Any help would be appreciated, Thanks in advance!
Edit:
I've yet to try any of the suggestions as I am away from my project at the moment, but I feel I need to clarify a few things.

*

*The dates will always be in chronological order, I have a script that organises them on sheet activation

*I need to be able to error handle dates that do not appear in the database, I also need the script to be able to "skip over" dates that don't exist. Ie, 1st 1st 1st, 3rd, 3rd, 5th. If my start and end dates were the 1st and 5th, the entire example would be the range.
Thanks for your help so far guys though, I appreciate it!
EDIT2:
I've tried a few answers and have added this in to my code, but it is now failing on a Range_Global fail.
Dim startrange, endrange, searchrange As Range
LookUpColumn = 2

With ws.Columns(LookUpColumn)
    Set startrange = .Find(What:=Me.R_Start.Value, _
      After:=ws.Cells(.Rows.count, LookUpColumn), _
      SearchOrder:=xlRows, _
      SearchDirection:=xlNext, LookIn:=xlValues)

    Set endrange = .Find(What:=Me.R_End.Value, _
      After:=ws.Cells(5, LookUpColumn), _
      SearchOrder:=xlRows, _
      SearchDirection:=xlPrevious, LookIn:=xlValues)

    searchrange = Range(startrange, endrange)

MsgBox searchrange.Address
End With

Any suggestions?

A: Using Find is the right way to do this type of thing, you just need to get a few details right.

*

*Use Set to assign range references.  Eg Set StartRange = ... (and make sure to Dim StartRange as Range).  Ditto EndRange and SearchRange

*Specify a After cell.  Note that by default this is the Top Left cell of the search range, and the search begins after this cell.  If your StartDate happens to be in cell A1 (and another cell) then leaving as default will return the wrong result

*Limit the search range to the column of interest.

*Dim all your variables.  Each variaqble needs its own As (and use Option Explicit)
End result
Dim startrange As Range, endrange As Range, searchrange As Range
Dim LookUpColumn as Long

LookUpColumn = 2
With ws.Columns(LookupColumn)
    ' Make sure lookup column data is type Date
    Set searchrange = .SpecialCells(xlCellTypeConstants)
    searchrange.Value = searchrange .Value
    Set searchrange = Nothing

    Set StartRange = .Find(What:=CDate(StartDate), _
      After:=.Cells(.Rows.Count, LookupColumn), _
      SearchOrder:=xlRows, _
      SearchDirection:=xlNext, LookIn:=xlValues)

    Set EndRange = .Find(What:=CDate(EndDate), _
      After:=.Cells(1, LookupColumn), _
      SearchOrder:=xlRows, _
      SearchDirection:=xlPrevious, LookIn:=xlValues)
End With

Set searchrange = Range(startrange, endrange)
MsgBox searchrange.Address

A: Let's start with this and see what needs to be fine tuned.
This code will look for a date (based on input) and find the position of that date in a column. Same with the "EndDate" and then creates a range on that column between the 2 positions.
Sub ARange()
Dim Sh As Worksheet: Set Sh = Sheets("Sheet1")
Dim i, j As Integer

LookupColumn = "A" 'Define the LookupColum / If you find using column index to be simpler then you need to switch the search from (range) to (cells)
StartDate_Value = Sh.Range("B2").Value 'Use whatever you need to define the input values
EndDate_Value = Sh.Range("C2").Value 'Use whatever you need to define the input values

For i = 1 To 30000
    If Sh.Range(LookupColumn & i).Value = EndDate_Value Then EndDate_Row = i
Next i

For j = EndDate_Row To 1 Step -1
    If Sh.Range(LookupColumn & j).Value = StartDate_Value Then StartDate_Row = j
Next j

Dim MyDateRange As Range: Set MyDateRange = Sh.Range(LookupColumn & StartDate_Row & ":" & LookupColumn & EndDate_Row)
MsgBox "MyDateRange = " & LookupColumn & StartDate_Row & ":" & LookupColumn & EndDate_Row
End Sub

Another approach should imply looking for the EndDate from bottom upwards (as in Excel's column values) and for the StartDate from top to bottom. like this:
For i = 30000 to 1 step -1
For j = 1 To 30000

And the 3rd (the charm):for the EndDate from top to bottom and for the StartDate from top to bottom. like this:
For i = 1 to 30000
For j = 1 To 30000

And the 4th (The One):
For i = 1 to 30000
For j = 30000 to 1 Step -1

On my home laptop the search on the 30.000 cells is instant (under 1s).
Give it a try and based on the feedback we can fine tune it.
On the Other hand, I might read your question as for looking To select not all values between the top / bottom position, but any cells with values of dates between the 2 input values neverminind the arrangement of the values within the list (column cells). i.e. If StartDate = 1.Jan.2013 and EndDate = 3.Jan.2013. The code should pick up 1,2 and 3 from the 30.000 list neverminind the position of these 3 dates (which in fact may be found thousands of times). If This is true, the solution may be simpler than the one above.

A: I don't like the concept of this date search for a couple of reasons..

*

*It makes the assumption that the dates will always be in order

*It makes the assumption that both the dates will exist in the list

Whilst these may be valid assumptions in this case, I'm sure there may be instances where this may not be the case...
I don't know the best way to do this but one alternative to consider is using the auto-filter
Something like:
 Sub FindDateRange()

Dim sht As Worksheet
Dim column As Long
Set sht = Sheet1

Dim rng As Range, inclusiveRange As Range
Dim startDate As Long, endDate As Long

column = 2

On Error GoTo Err

startDate = DateValue("02/10/2012")
endDate = DateValue("05/10/2012")

Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False

    sht.Cells(1, column).AutoFilter Field:=column, Criteria1:=">=" & startDate, Operator:=xlAnd _
            , Criteria2:="<=" & endDate

    Set rng = sht.Range(sht.Cells(2, column), sht.Cells(sht.Cells(sht.Rows.Count, column).End(xlUp).Row, column)).SpecialCells(xlCellTypeVisible)

    sht.AutoFilterMode = False

    If rng.Address = sht.Cells(1, column).Address Then

        MsgBox Format(startDate, "dd-mmm-yyyy") & " - " & Format(endDate, "dd-mmm-yyyy") _
        & vbCrLf & vbCrLf & "No instances of the date range exist"

    Else

    Set inclusiveRange = sht.Range(rng.Cells(1, 1), rng.Cells(rng.Count, 1))

        MsgBox Format(startDate, "dd-mmm-yyyy") & " - " & Format(endDate, "dd-mmm-yyyy") _
        & vbCrLf & vbCrLf & "the range is " & rng.Address & vbCrLf & vbCrLf & _
        "inclusive range is " & inclusiveRange.Address
    End If

continue:

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic

Exit Sub

Err:
    MsgBox Err.Description
    GoTo continue

End Sub


text:
Q: Display two visualizations that are based on two different dataframes in modularized shiny app In the modularized shiny app below I want to create one map which is created and one plot below the map. The 2 visualizations are based on 2 different dataframes though and I do not know exactly how display them both.
library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(leaflet)
library(dplyr)
library(plotly)
# Some data
data<-structure(list(scientificName = c("Turdus merula Linnaeus, 1758",
                                        "Passer domesticus (Linnaeus, 1758)", "Cantharellus cinereus (Pers.) Fr.",
                                        "Flammulina fennae Bas", "Mycena crocata (Schrad.) P.Kumm.",
                                        "Lepista luscina (Fr.) Singer", "Mycena permixta (Britzelm.) Sacc.",
                                        "Rhodophyllus byssisedus (Pers.) Quel.", "Rhodophyllus porphyrophaeus (Fr.) J.E.Lange",
                                        "Panaeolus rickenii Hora"), decimalLatitude = c(52.204429, 51.387818,
                                                                                52.176667, 50.066111, 49.179167, 49.419444, 52.3, 52.3, 49.419444,
                                                                                49.179167), decimalLongitude = c(21.189275, 19.62673, 19.088056,
                                                                                19.502778, 22.434722, 20.380556, 20.566667, 20.566667, 20.380556,
                                                                                22.434722)), row.names = c(1L, 2L, 32L, 35L, 37L, 38L, 39L, 40L,
                                                                                41L, 42L), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"
                                                                                ))
data$year<-c(1990,1989,2003,1990,1980,1990,1989,2003,1990,1980)
# Define the side panel UI and server
sideUI <- function(id) {
  ns <- NS(id)
  tagList(

    uiOutput(ns("ye")),
    uiOutput(ns("scient")),
    actionButton(ns("action"),"Submit")
  )

}

sideServer <- function(id) {
  moduleServer(
    id,
    function(input, output, session) {

      # define a reactive and return it
      react<-eventReactive(input$action,{

        omited <-subset(data, data$scientificName %in% isolate(input$sci))
      })

      output$ye<-renderUI({
        pickerInput(
          inputId = session$ns("yea"),
          label = "Year",
          choices = sort(unique(data$year),decreasing=F),
          selected = unique(data$year),
          multiple = T

        )
      })

      output$scient<-renderUI({
        data <-subset(data, data$year %in% input$yea)

        pickerInput(
          inputId = session$ns("sci"),
          label = "Scientific name",
          choices = unique(data$scientificName),
          selected = unique(data$scientificName)[1],

        )
      })

      return(react)
      counted<-reactive({data.frame(react() %>%
                                      group_by(year) %>%
                                      summarise(count=n()
                                      ))
      })
      return(counted)
    })
}
# In this case this server not needed but using uiOuput/renderUI in real case
# sideServer <- function(id) { moduleServer(id,function(input, output, session) { })}

# Define the UI and server functions for the map
mapUI <- function(id) {
  ns <- NS(id)
  tagList(
    leafletOutput(ns("map")),
    plotlyOutput(ns("plot"))
  )
}

mapServer <- function(id, city) {
  moduleServer(
    id,
    function(input, output, session) {
      output$map<-renderLeaflet({

        leaflet(data = city()) %>% addTiles() %>%
          addMarkers(~decimalLatitude, ~decimalLongitude, popup = ~as.character(scientificName), label = ~as.character(scientificName))
      })
    })
}
plotServer <- function(id, city) {
  moduleServer(
    id,
    function(input, output, session) {
      output$plot<-renderPlotly({

        fig <- plot_ly(data=city(), x = ~as.factor(year), y = ~count, type = 'scatter', mode = 'lines')

        fig%>% layout(title = paste("Count of",input$sci ,"through the years"),
                      xaxis = list(title = "Years",tickangle=45),
                      yaxis = list (title = "Count"))
      })
    })
}
# Build ui & server and then run
ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(sideUI("side")),
  dashboardBody(mapUI("mapUK"))
)
server <- function(input, output, session) {

  # use the reactive in another module
  city_input <- sideServer("side")
  mapServer("mapUK", city_input)
  plotServer("plotPl",city_input)

}
shinyApp(ui, server)

A: *

*You have plotlyOutput(ns("plot")) in different module than server where is output$plot<-renderPlotly({ (the latter is in plotServer while ui output is in mapUI). I decided to make new ui for plotServer, but you can also try to move elements from plotServer into mapServer.

*As you said, the problem is with returning multiple elements. But not just two dataframes, also some input. To return more than one element, you need to create list, say like this: return(list(element1 = _object_to_return1, element2 = _object_to_return2)).

*I said above "return some input", that's because here: fig%>% layout(title = paste("Count of",input$sci ,"through the years") you are using input, but input from different module. As you already know, you do not have direct access to objects from different modules and the same is with inputs. That means you need to return input as well, but input needs to be wrapped into reactive() function. In your case, when there is module with two returns function, it should be one and look like this: return(list(react = react, counted = counted, sci = reactive(input$sci))) .

*Now, because you have returned list, you need to access elements inside this list as normal elements from list, so when you pass arguments to function, it won't be react as previously, but city_input$react. You also need to add parameters to the server function - not just city, but also parameter for counted dataframe and input.

*In case it won't be obvious for you - to access input from other module (after passing as argument) you access it as a normal function, so below you can see that I use sci() instead of input$sci
Here is full code:
library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(leaflet)
library(dplyr)
library(plotly)
# Some data
data<-structure(list(scientificName = c("Turdus merula Linnaeus, 1758",
                                        "Passer domesticus (Linnaeus, 1758)", "Cantharellus cinereus (Pers.) Fr.",
                                        "Flammulina fennae Bas", "Mycena crocata (Schrad.) P.Kumm.",
                                        "Lepista luscina (Fr.) Singer", "Mycena permixta (Britzelm.) Sacc.",
                                        "Rhodophyllus byssisedus (Pers.) Quel.", "Rhodophyllus porphyrophaeus (Fr.) J.E.Lange",
                                        "Panaeolus rickenii Hora"), decimalLatitude = c(52.204429, 51.387818,
                                                                                52.176667, 50.066111, 49.179167, 49.419444, 52.3, 52.3, 49.419444,
                                                                                49.179167), decimalLongitude = c(21.189275, 19.62673, 19.088056,
                                                                                19.502778, 22.434722, 20.380556, 20.566667, 20.566667, 20.380556,
                                                                                22.434722)), row.names = c(1L, 2L, 32L, 35L, 37L, 38L, 39L, 40L,
                                                                                41L, 42L), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"
                                                                                ))
data$year<-c(1990,1989,2003,1990,1980,1990,1989,2003,1990,1980)
# Define the side panel UI and server
sideUI <- function(id) {
  ns <- NS(id)
  tagList(

    uiOutput(ns("ye")),
    uiOutput(ns("scient")),
    actionButton(ns("action"),"Submit")
  )

}

sideServer <- function(id) {
  moduleServer(
    id,
    function(input, output, session) {

      # define a reactive and return it
      react<-eventReactive(input$action,{

        omited <-subset(data, data$scientificName %in% isolate(input$sci))
      })

      output$ye<-renderUI({
        pickerInput(
          inputId = session$ns("yea"),
          label = "Year",
          choices = sort(unique(data$year),decreasing=F),
          selected = unique(data$year),
          multiple = T

        )
      })

      output$scient<-renderUI({
        data <-subset(data, data$year %in% input$yea)

        pickerInput(
          inputId = session$ns("sci"),
          label = "Scientific name",
          choices = unique(data$scientificName),
          selected = unique(data$scientificName)[1],

        )
      })

      counted<-reactive({react() %>%
                                      group_by(year) %>%
                                      summarise(count=n()
                                      )

      })
      return(list(react = react, counted = counted, sci = reactive(input$sci)))
    })
}
# In this case this server not needed but using uiOuput/renderUI in real case
# sideServer <- function(id) { moduleServer(id,function(input, output, session) { })}

# Define the UI and server functions for the map
mapUI <- function(id) {
  ns <- NS(id)
  tagList(
    leafletOutput(ns("map"))
  )
}

mapServer <- function(id, city) {
  moduleServer(
    id,
    function(input, output, session) {
      output$map<-renderLeaflet({

        leaflet(data = city()) %>% addTiles() %>%
          addMarkers(~decimalLatitude, ~decimalLongitude, popup = ~as.character(scientificName), label = ~as.character(scientificName))
      })
    })
}

plotUI <- function(id) {
  ns <- NS(id)

  tagList(
    plotlyOutput(ns("plot"))
  )
}

plotServer <- function(id, city, sci) {
  moduleServer(
    id,
    function(input, output, session) {
      output$plot<-renderPlotly({

        fig <- plot_ly(data=city(), x = ~as.factor(year), y = ~count, type = 'scatter', mode = 'markers+lines')

        fig%>% layout(title = paste("Count of", sci(),"through the years"),
                      xaxis = list(title = "Years",tickangle=45),
                      yaxis = list (title = "Count"))
      })
    })
}
# Build ui & server and then run
ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(sideUI("side")),
  dashboardBody(mapUI("mapUK"), plotUI("plotPl"))
)
server <- function(input, output, session) {

  # use the reactive in another module
  city_input <- sideServer("side")
  mapServer("mapUK", city_input$react)
  plotServer("plotPl", city_input$counted, sci = city_input$sci)

}
shinyApp(ui, server)

What I have changed and didn't describe above is that from this:
counted<-reactive({data.frame(react() %>%
                                      group_by(year) %>%
                                      summarise(count=n()
                                      ))
      })

I have removed data.frame() function. You don't need this, it will be data.frame even without this function.
I have also changed mode = 'lines' into mode = 'markers+lines', because I saw no data in plot. But then I realized it's because for each animal is only one year in data.frame (and just with lines you can't see line if there is only one point on plot). I understand that you posted just a part of data. That's of course fine.


text:
Q: cd to original location when recording session with "script" command I have script log.txt in my bash profile; that creates a new sub process and records my entire session to log.txt. When I press cmd+t to open a new terminal usually this will open one in the same directory that the command was called; however, the new script sub process always reverts to the home directory.
Is there a way to "pass" the current directory to this script command somehow?

A: It sounds like MacOS's Terminal has a feature where it extracts the current working directory from the process running in one tab (using /proc or similar) and uses it as the initial current working directory for a new tab.
In this case, the process running in the first tab is script — which never bothers to change its current working directory, so new tabs always come up with that directory. Only the current working directory of (some) child process of script is actually changing, but the Terminal application is paying no attention to that.
If this is correct, then there is no workaround short of changing either how the Terminal application works or changing how script works.

A: The current directory is simply:
CWD="$(pwd)" ;
echo "PWD === ${CWD}" ;

Alternatively you may also in-line pass this eg:
CWD="something" ./script log.txt

The contents of the script containing:
cat script
#!/bin/bash
if [ $CWD ] ; then echo "CWD Preset & == ${CWD}" ; else echo "CWD NOT SET... SETTING to: $(pwd)" ; CWD=$(pwd) ; fi ;

You can obviously export the above mentioned CWD variable as well in which case it ought to be accessible to any other sub-shell / process.
export CWD="$(pwd)" ;  # or the path of interest
# ... then post New Terminal / Session:
echo "CWD == ${CWD}" ;


text:
Q: Read and parse XML input via TCP I'm setting up something where I'll need to be able to setup a service that accepts input on a TCP port and then parses the XML provided and extracts the necessary data, then posts that to Google's universal analytics via HTTP GET.
What is the easiest thing to use for this?  Perl?  C?  Are there any libraries that you know of for those languages that would make this easier?
A little bit of background: I'm trying to export data from a POS which has a "Security DVR" output option for basic transaction info (X item added to invoice, $50 cash was paid, etc).  I'm outputting this info to this server that I'd need to setup, and then exporting that to Universal analytics.  This will allow me to see sales volumes in google analytics.

A:
What is the easiest thing to use for this? Perl? C?

Not many people are going to say that C is the easiest thing for this, although there are XML parsing libs for C.  I guess it depends how comfortable you are with it.
Dynamically typed, objected oriented such as perl -- or python, or ruby, or php -- are ideally suited to this and they'll be hoards of modules available for every aspect of the task (eg, TCP sockets, and you very definitely want to use one for parsing the XML).  So the question is really which of those you find easiest to use.


text:
Q: Retrieve columns from OUT REF_CURSOR using C# I'm new at Oracle, I would like to build a solution to get columns from a return REF_CURSOR, and there are some limitations on creating database objects on DB,
so I want to run the stored procedure and return the REF_CURSOR data in C# scripting.

A: Your back-end procedure could be something like this:
procedure my_proc(
    p_id in number,
    p_cursor out sys_refcursor
) is
begin
    open p_cursor for
       select  col1, col2, col3
       from my_table
       where id = p_id;
end my_proc;

And then in your C# script you declare the 2 parameter call, setting the second parameter as output (direction = ParameterDirection.Output) and type OracleDbType.RefCursor (remember adding name spaces 'Oracle.DataAccess.Client' and 'Oracle.DataAccess.Types' at the beginning of your object/class).
Don't forget close the data reader as well as your connection,  otherwise you'll have your DBA knocking at your door with red eyes and bloody fangs.


text:
Q: Firebase admin and user account I am building an Android app with firebase. Simple users would sign in and add data to the database. Users would be able to see only their own data. Then I need to have a single Admin account that sees all data in the firebase database. How should I go about it?

A: Did you secure your database in any way yet? If not, I recommend getting started with the documentation for Firebase security rules.
I typically secure my database as shown in the section on securing user data and then have a list of UIDs in the database for users with special permissions.
So with a JSON structure like this:
users
  Power3000Uid: { ... }
  PufUid: { ... }
admins
  Power3000Uid: true

And security rules like this:
{
  "rules": {
    "users": {
      "$uid": {
        ".read": "auth.uid == $uid || root.child('admins').child(auth.uid).exists()"
      }
    }
  }
}

In words the .read rules is: "you can read this data if you're the owner of it, or if you're an admin". In the sample above this means that you can read anyone's data, but I can only read my own.
Depending on your exact needs, you'll need to repeat the admin-clause in various places in the database, or (what I usually do) just have it once at a high level in your JSON tree.


text:
Q: GaxiosError is thrown when users tries to register on my web app My authentication web app seem to work fine when I deployed it on heroku. Basically, the app is supposed to send email verification to the user's email account, and Ive used both googleapis and nodemailer as my dependencies. It worked fine initially and I didn't touch my code after. Still, the following day when I tested it with users it failed to send an email verification to the user, and upon testing on my localhost, it threw this error:
GaxiosError(Request failed with status code ${translatedResponse.status}, opts, translatedResponse);

It seems to come from my node modules, but given that I have never touched or amended any of my code before it was working fine, I have no clue what caused this error suddenly.


text:
Q: Eclipse runs old code even after building the new one I started to study c++ and i choosen Eclipse IDE for it.
I need some basic instructions.
Even after i compile my code with ctrl+b Eclipse shows me the old "Hello World" program in console. If i look up the compiled .exe files in my projects "Release" folder i can ran my new program very well.
For some reason Eclipse does not refresh output console.
Any ideas?

A: Have you tried checking that there are not still multiple consoles open. On the console tab try clicking the Display Selected Console button, or pushing the red terminate button until it becomes greyed out and then running it again.

A: I saw at the output console's setting's that it is showing my project's Debug release.
So i searched for the compiled in my Debug folder and i saw it was the old .exe of my project.
After that i did the same thing within the Release folder that was the new code!
So all i did was changed the run configuration to Release, pic below.

And now it is working.

A: Just clean the project from menu...


text:
Q: Can a business application be developed / enhanced with more than one language? Please excuse my lack of knowledge in programming, but it is true that a business application, e.g. CRM, can be developed using one language (e.g., C++) and later enhanced using a different language (e.g., C#.NET)?
Can we use multiple languages when developing an application?

A: Of course it can. Many languages actually encourage this. It goes well beyond C++/C#. There are actually fairly good examples such as the Qt Clases for Python/Java whic use C, Spark/Hadoop when used with PySpark, and the interoperability of Scala and Java. Python itself is practically a living example of this interchange with CPython now used for the standard flavor and Jython (which interacts with Java). In the case of Java, the JNI actually makes it fairly simple to access C/C++ code. The C# equivalent would be the invoke command. There are some things to keep in mind though.

*

*Don't destroy the understandability or performance of a program because you simply understand something else more easily because, chances are, you will not be the only one who needs to be involved on the project.

*Is the addition logical. Does it add functionality beyond being just
easier to program. If the code is just going to require more skill to
read and change, then there is an issue. If there is a performance
upgrade, then it is useful.

*Can the main language be used to run the code. If so, it would be
easier to understand and use. The JNI is an example of how to run C
code in Java.

*Are there similar tools with APIs that can ease your programming that
are written in the native langauge or use the target language. This
always makes things easier to understand and the right tool is often
better maintained for that purpose.

A: Lots of iOS applications started out as Objective-C or possibly a mix of Objective-C and C++, and now get enhanced using Swift. So it's quite possible and not at all uncommon in a single application.

A: All .NET frameworks permit you to merge different languages when they are built using separate in code modules… Depending on which library you include in the framework (.net framework) fuji  some third party product (language) permit you to do this…  Using good configuration.

A: My straight forward answer would be: for sure.
I don't know exactly from where your concerns come, but if you think about web software development, you are in a place with potentially a bunch of languages working together.
There are many ways to think about your question, but it's very common (and sometimes desired) to use the "right language for the right problem". So it's perfectly normal to have an business application built on top of various minor parts, many times in various languages.

A: It's extremely common to work on a project with multiple programming languages. A very typical example is combine C++ with a more front-end friendly programming language.
For example, it'd be awful to code the front-end for a web application with C++. JavaScript would be a better langugage. While the computation algorithm can also be done in JavaScript, C++ offers better performance power and flexibilty.


text:
Q: SQL Stored procedure if (@variable = 0) doesn't work I've created a Stored procedure with some variables and a nested if statement.
When I call the Stored procedure from my program and check the returned dataset for the returned values, my dataset is empty while there should be records in it. After some testing I noticed when the statement if (@PoolID = 0) is tested and @PoolID is 0, it won't go trough the if statement... So whenever I set the variable poolid to 0 in my code I get the results from the else statement...
Anybody who knows what's going wrong?
Thx
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Pool_select]

@PartnerCode nvarchar(8),
@GebrID int,
@PoolID int,
@Bevoegdheid int

AS

IF (@PoolID = 0)
BEGIN
    IF (@Bevoegdheid < 3)
    BEGIN
        SELECT
        p.*,
        pr.poolrecht
        FROM racpPool p, racpPoolrecht pr
        WHERE
        p.poolid = pr.poolid and
        p.PartnerCode = @PartnerCode and
        pr.poolrecht > 0 and
        p.actief = 1 and
        pr.GebrID = @GebrID
    END
    ELSE
    BEGIN
        SELECT *
        FROM racpPool p
        WHERE standaardpool = 1
        and partnercode = @PartnerCode
    END
END
ELSE
BEGIN
    IF (@Bevoegdheid < 3)
    BEGIN
        SELECT
        p.*,
        pr.poolrecht
        FROM racpPool p, racpPoolrecht pr
        WHERE
        p.poolid = pr.poolid and
        p.PartnerCode = @PartnerCode and
        pr.poolrecht > 0 and
        p.actief = 1 and
        pr.GebrID = @GebrID and
        p.PoolID = @PoolID
    END
    ELSE IF (@Bevoegdheid >= 3)
    BEGIN
        SELECT *
        FROM racpPool p
        WHERE PoolID = @PoolID
    END
END

A: You could rewrite it as one single select of 4-part UNION ALL.
I also notice that your conditions are not comprehensive, not sure if that is intentional.
In the 2nd branch of @PoolID = 0 , the tests are specifically @Bevoegdheid < 3 and @Bevoegdheid >= 3 (instead of ELSE ) which will do nothing if @Bevoegdheid IS NULL
The optimizer will only run the branch that fits the criteria marked with  <<<
ALTER PROCEDURE [dbo].[Pool_select]
@PartnerCode nvarchar(8),
@GebrID int,
@PoolID int,
@Bevoegdheid int
-- WITH RECOMPILE -- << may need this

AS

    SELECT
    p.*,
    pr.poolrecht
    FROM racpPool p, racpPoolrecht pr
    WHERE
    p.poolid = pr.poolid and
    p.PartnerCode = @PartnerCode and
    pr.poolrecht > 0 and
    p.actief = 1 and
    pr.GebrID = @GebrID
    AND @PoolID = 0 and @Bevoegdheid < 3   --- <<<
UNION ALL
    SELECT *, NULL
    FROM racpPool p
    WHERE standaardpool = 1
    and partnercode = @PartnerCode
    AND @PoolID = 0 and IsNull(@Bevoegdheid,4) >= 3 --- <<<
UNION ALL
    SELECT
    p.*,
    pr.poolrecht
    FROM racpPool p, racpPoolrecht pr
    WHERE
    p.poolid = pr.poolid and
    p.PartnerCode = @PartnerCode and
    pr.poolrecht > 0 and
    p.actief = 1 and
    pr.GebrID = @GebrID and
    p.PoolID = @PoolID
    AND Isnull(@PoolID,-1) <> 0 AND @Bevoegdheid < 3   --- <<<
UNION ALL
    SELECT *, NULL
    FROM racpPool p
    WHERE PoolID = @PoolID
    AND Isnull(@PoolID,-1) <> 0 AND @Bevoegdheid >= 3  --- <<<