Ridge Regression in R where coefficients are penalized toward numbers other than zero

Question: Is it possible to penalize coefficients toward a number other than zero in a ridge regression in R?
For example, let's say I have dependent variable Y and independent variables X1,X2,X3, and X4. Because of the multicollinear nature of the ivs, ridge regression is appropriate. But say I'm fairly certain that the coefficient of X1 is near 5, X2 is near 1, X3 is near -1, and X4 is near -5.
Is there a ridge package and method in R where I can implement penalties on the coefficients of the ivs that penalize them toward those numbers instead of 0? I'd love to see an example in R with my example data, if possible. Thank you.
Comment: That's known as nonzero centered ridge regresqsion and can be achieved by row-augmenting your covariate matrix X with a diagonal matrix with sqrt(lambdas) along the diagonal and adding center * sqrt(lambdas) to your outcome variable, where center is the desired target values towards which your coefficients should be shrunk. See https://www.sciencedirect.com/science/article/abs/pii/S0047259X21001603 and references therein.
Comment: For a solution that also works with logistic regression or other generalized linear models, see [here](https://stats.stackexchange.com/questions/385606/logistic-regression-with-coefficients-penalized-to-other-numbers/385618#385618)
Answer: A simple way to do this is to subtract the "centering value" of the coefficient times its associated variable from the left-hand side.  To go with your example,
$Y = \beta_1X_1 + \beta_2X_2 + \beta_3X_3 + \beta_4X_4 + e$
Assume the coefficient values should be centered at (5,1,-1,-5) respectively.  Then:
$Y - 5X_1 -X_2 +X_3 +5X_4 = (\beta_1-5)X_1 + (\beta_2-1)X_2 + (\beta_3+1)X_3 + (\beta_4+5)X_4 + e$
and, redefining terms, you have:
$Y^* = \beta_1^*X_1 + \beta_2^*X_2 + \beta_3^*X_3 + \beta_4^*X_4 + e$
A standard ridge regression would shrink the $\beta_i^*$ towards 0, which is equivalent to shrinking the original $\beta_i$ towards the specified centering values.  to see this, consider a fully-shrunk $\beta_4^* = 0$, then $\beta_4+5 = 0$ and therefore $\beta_4 = -5$.  Shrinkage accomplished!

A slightly more formal demonstration follows. The required objective function in $\beta$ is
$$
(Y-X\beta)^T (Y-X\beta) + (\beta - \gamma)^T(\beta-\gamma)
$$
where $\gamma$ is the vector of centring values. In the first term make the substitution $
Y-X\beta=Y-X\gamma-X\beta+X\gamma=Y^*-X\beta^*$ (the errors for a given fit are of course unchanged by this reëxpression of the model), and in the second
$\beta-\gamma =\beta^*$; to obtain a zero-centered objective function in $\beta^*$:
$$
(Y^* - X\beta^*)^T (Y^* - X\beta^*) + \lambda{\beta^*}^T{\beta^*}^T
$$
Comment: @TomWenseleers - this reformulates the problem into a standard linear regression that can be solved using any ridge regression, Lasso, Elastic net, or other shrinkage routines with the centering being at the desired values.  So, the answer to "is it possible" is clearly meant to be "yes" and "is there a ridge package" is "yes, any ridge package will do" ... as I say in the text, "a standard ridge regression would..."
Comment: @TomWenseleers the part of the question that is asking how to write specific R code is nowadays off-topic. A question should have a focus on a statistical problem and coding examples can be part of explanations or the background of a problem but should not be the topic itself. Instructions how to write code can be found in many other places, like here: https://stats.meta.stackexchange.com/questions/793/internet-support-for-statistics-software
Comment: I think R code would be otiose for something so simple, especially as @TomWenseleers has already provided an illustration for the example given in the question. I've taken the liberty of adding some linear algebra as a footnote, but feel free of course to remove or edit it. (I know it's rather trivial, but perhaps it wasn't immediately clear to readers new to ridge regression that the two methods - yours & Tom's - give the same result.)
Comment: What if you want to do it with logistic regression?
Comment: But how does this solution allow for a given level of shrinkage towards a given centering value of the ridge regression? I don't see an lambda / regularisation parameter appear in here?
Comment: Or you are assuming that one has a regular ridge solver available, where you would specify a given regularisation level, and where you shrink to a given center essentially by using a given offset? I think the OP was also asking for some reproducible R code...
Comment: @jbowman OK thanks I see what you mean... You're just assuming you have an external ridge regression package already available...
Comment: @TomWenseleers - Yes... those were early days for me on the site, and now I'd write a more complete answer with R code  :)  Maybe I'll update later.
Comment: @jbowman No worries, was asking for some clarification after someone commented on my post here https://meta.stackexchange.com/questions/387575/examples-of-chatgpt-being-right-and-wrong-on-stack-exchange/390348#390348 where I tried to compare the quality of ChatGPT4 generated answers with some human answers. And where the question was whether your or the ChatGPT4 answer below was the best one in this case. What do you reckon? How would you rate each yourself? Yours and my ChatGPT4 based answer below?
Comment: @Scortchi-ReinstateMonica - Thanks!  ... for a 10-year-old Q&A, this sure is getting a lot of attention, indirectly thanks to ChatGPT.
Answer: That's known as nonzero centered ridge regression and can be achieved by row-augmenting your covariate matrix X with a diagonal matrix with sqrt(lambdas) along the diagonal and concatenating prior.mean * sqrt(lambdas) to your outcome variable, where prior.mean is the desired target values towards which your coefficients should be shrunk and lambdas is the vector with the desired L2 ridge penalty on your coefficients; and then performing an ordinary least-squares regression of the (row-augmented) target vector on the (row-augmented) matrix X. See https://www.sciencedirect.com/science/article/abs/pii/S0047259X21001603 and references therein. You can also compare with this post for the same recipe for a regular zero-centered ridge regression.
For your example:
First, generate some example data:
set.seed(123)

# Number of observations
n <- 100

# Generate some correlated variables
X1 <- rnorm(n, mean = 5)
X2 <- X1 + rnorm(n, mean = 1)
X3 <- X1 + rnorm(n, mean = -1)
X4 <- X1 + rnorm(n, mean = -5)

# Make a covariate matrix X
X <- cbind(X1, X2, X3, X4)

# Generate a response y
y <- 5*X1 + X2 - X3 - 5*X4 + rnorm(n)

# This is our center (the coefficients we believe are "true", ie the mean of our implicit Gaussian prior)
prior.mean <- c(5, 1, -1, -5)

Next, we can apply a non-zero centered ridge regression. Note that lambda is a regularization parameter and would typically be chosen via cross-validation:
# Regularization parameter
# note: you can use a vector of lambda values if you would like
# to penalize different coefficients to different extents
# (e.g. penalty on intercept is usually set to zero)
lambda <- 100

# Number of features
p <- ncol(X)

# Augment X
X_augmented <- rbind(X, diag(sqrt(lambda), p))

# Augment y
y_augmented <- c(y, prior.mean * sqrt(lambda))

# Solve nonzero centered ridge regression as this least squares problem
beta <- solve(t(X_augmented) %*% X_augmented, t(X_augmented) %*% y_augmented)

So in other words all we need to do to solve this nonzero centered least-square ridge regression is solve a least square problem but with some extra observations added. We can do this just using a regular linear model (lm), so no need even to use any fancy ridge regression package like ridge or glmnet :
lm(y_augmented ~ X_augmented)

For example if we would set lambda to zero we would then get the standard (zero intercept) least square result
         [,1]
X1  5.1977104
X2  0.8903286
X3 -1.0616111
X4 -5.1220296

but with a lambda of 100 we would get values shrunken more towards the center of your Gaussian prior (nonzero centered ridge regression is in a Bayesian sense equivalent to the MAP estimate with a nonzero-centered Gaussian prior, while standard ridge regression would be equivalent to using a zero-centered Gaussian prior).
         [,1]
X1  5.0477868
X2  0.9773907
X3 -1.0079250
X4 -5.0728437

Adjusting the response to shrink towards your prior mean comes down to the same thing:
y_star <- y - X %*% prior.mean
X_aug <- rbind(X, diag(sqrt(lambda), ncol(X)))
y_aug_star <- c(y_star, rep(0, ncol(X)))
beta_star <- solve(t(X_aug) %*% X_aug, t(X_aug) %*% y_aug_star)
beta <- beta_star + matrix(prior.mean, nrow = length(prior.mean), ncol = 1)

Some of the maths behind this: the objective function for standard (zero-centered) Ridge Regression is:
argmin(β) [(y - Xβ)ᵀ(y - Xβ) + λβᵀβ]
This corresponds to a zero-centered Gaussian prior for β.
To consider a non-zero centered Ridge Regression, we adjust the objective function to center at a given target γ:
argmin(β) [(y - Xβ)ᵀ(y - Xβ) + λ(β - γ)ᵀ(β - γ)]
Now, let's reformulate this as a least squares problem:
If we define z = [y; γ*sqrt(λ)] and W = [X; sqrt(λ)I], where I is the identity matrix, the problem becomes:
argmin(β) [(z - Wβ)ᵀ(z - Wβ)]
To see this, we can expand out the terms:
argmin(β) [(z - Wβ)ᵀ(z - Wβ)]
= argmin(β) [zᵀz - zᵀWβ - βᵀWᵀz + βᵀWᵀWβ]
= argmin(β) [(y - Xβ)ᵀ(y - Xβ) + γᵀγλ - 2γᵀβλ + βᵀβλ]
= argmin(β) [(y - Xβ)ᵀ(y - Xβ) + λ(β - γ)ᵀ(β - γ)]
Therefore, solving the least squares problem with z = [y; γ*sqrt(λ)] and W = [X; sqrt(λ)I] corresponds to solving the non-zero centered Ridge Regression problem. The regularization term now encourages the coefficients to be close to γ instead of zero.
In a Bayesian context, the standard Ridge regression minimizes the negative log posterior, which is equivalent to minimizing:
[(y - Xβ)ᵀ(y - Xβ) + λβᵀβ]
This can be viewed as the sum of the negative log likelihood [(y - Xβ)ᵀ(y - Xβ)] and the negative log prior λβᵀβ, where λβᵀβ corresponds to the log of a Gaussian distribution with mean zero and variance 1/λ.
If you move to a non-zero centered Ridge regression, you're effectively changing the prior to a Gaussian distribution that is centered around a non-zero mean. Specifically, for a center γ, the new objective function becomes:
[(y - Xβ)ᵀ(y - Xβ) + λ(β - γ)ᵀ(β - γ)]
Which is equivalent to minimizing the sum of the negative log likelihood [(y - Xβ)ᵀ(y - Xβ)] and the negative log prior λ(β - γ)ᵀ(β - γ). Here, λ(β - γ)ᵀ(β - γ) corresponds to the log of a Gaussian distribution with mean γ and variance 1/λ.
(Full disclosure: this is a ChatGPT4 based answer, but I verified everything for correctness, i.e. I tested the code & checked the maths)
Comment: None of the other answers gave working R code so I thought this was useful... And none made reference to nonzero centered ridge regression, which is what this technique is known as.
Comment: Please don't generate answers with chatGPT especially when there is already a perfectly sufficient answer. This answers is verbose and it could be made more intuitive by shortening it. I would suggest to fully write out the matrix equation from the example.
Comment: @SextusEmpiricus Also the question asked explicitly about "Ridge Regression in R" so working R code I think is quite essential here. The Bayesian approach suggested above would work, but I believe the OP was interested in a faster ML solution.
Comment: @SextusEmpiricus The fact that the OP did not flag any of the other answers as the correct one to me also suggests he wasn't happy with any of the other answers...
Comment: "weighted least squares"? - it's just ordinary least squares.
Comment: Yes that "weighted" did not belong there - edited now...
Comment: I don't think that ChatGPT's explanation in the screenshot holds water. Weighted least squares has the form $\hat \beta = (X^T W X)^{-1}X^T W y$, which is meaningfully different from the ChatGPT explanation. ChatGPT does use the word "loosely," but I don't see any real connection between the two problems.
Comment: Was the word "weighted" provided by you or chatgpt?
Comment: @Sycorax-OnStrike This is what it says to defend its wording - which I can kind of live with : https://www.dropbox.com/s/1xjbxeyzwjxfdvt/chatgpt%20nonzero%20centered%20ridge%20regression.png?dl=1
Comment: @Sycorax-OnStrike Yes of course what you show here is standard weighted LS regression, which this is not. ChatGPTs explanation is that one could still call problem above a weighted LS regression too, since in that particular problem one is augmenting the covariate matrix X and the outcome variable y with extra observations, and the observation weights of the original observations and the augmented observations could be taken to be 1 and lambda here. But yes, I wouldn't use the term "weighted" there no...
Answer: Ridge regression sets a normal prior centered at zero for each parameter. To penalize coefficients towards different values, just center the priors around your target instead of around 0. I think you can accomplish this using the bayesGLM function of the arm package with the following parameters:

prior.mean : set this to vector containing the values you want to use as the centers for your priors (the values you want to penalize "towards")
prior.df : set this to Inf to get normal priors. Possibly not necessary. There should be a way to control your prior variance, but it's not clear to me how this would be accomplished from looking at the documentation.

http://cran.r-project.org/web/packages/arm/arm.pdf
Comment: Hmm, I'm sure I'm missing something but I tried this and it gave me the same coefficients as a normal lm() regression
Comment: You would also still need to set the SD of the priors, which to mimick ridge regression (interpreted as the MAP solution of a Bayesian LM with Gaussian priors then) with a given lambda would still be a function of the noise and your data & the desired level of regularisation lambda. I think the OP was rather interested in a ML solution, in which case my answer is better & more convient I think (and computationally much faster)...


Is Sybase {ASE} uses "schema.table" or just "table"

Question: ALL,
The title pretty much says it all. I was looking here, but couldn't find any information about the schema.
Could someone please sched some light?
I know MS SQL Server uses "schema.name" to reference a table in a database, but for Sybase I'm not sure.
TIA!

EDIT:
I guess I should be more specific.
I know in MS SQL Server it is possible to modify the table owner, but you can still select it with "SELECT su.name FROM sysobjects so, sysusers su, sys.tables t, sys.schemas s WHERE so.uid = su.uid AND t.object_id = so.id AND t.schema_id = s.schema_id AND s.name = ? AND so.name = ?;"
Now with Sybase everywhere I look the query to retrieve the table owner does not reference schema name only the table name. Does this mean that the table owner is not changeable in Sybase? Or it is changeable, but then the schema will also be changed?
Can someone shed some light please?
Answer: In Sybase/SAP ASE, all tables have an owner; this owner is effectively the same thing as a schema.
That link you mention points to the sysobjects (system) table, which exists in every database.  sysobjects contains some high-level metadata for all objects (eg, tables, procs, triggers, views, etc) in the database.
Two columns of interest in the sysobjects table

name : name of the object (eg, name of a table, name of a proc)
uid : database user id of the object's owner

All system tables have an entry in sysobjects with uid = 1, which refers to the database owner (ie, user_name(1) = dbo).
In most environments it's typical for the database owner (dbo) to also own most other objects in the database (ie, most sysobjects rows have uid=1).
If an object is owned by someone other than the dbo, the sysobjects row will have uid = user_id('non_dbo_owner_name'); for example, if bob's database user id (uid) is 47, then any objects owned by bob will have sysobjects.uid = 47.

When you reference a table without an owner/schema name (eg, select * from tab1), ASE will first look for an object owned by you (ie, do you own a table named 'tab1') and if it doesn't find such a table then it looks for a table owned by the dbo (ie, does 'dbo.tab1' exist?).
When you reference a table with an owner/schema name attached, ASE will only look for the existence of that table.
If you don't own a table named 'tab1' then the following are equivalent:

select * from tab1
select * from dbo.tab1

In response to the updated question:
Sybase/SAP ASE does not support changing the owner of an object.
As for finding the owner(s)/schema(s) of a table, you've got a couple options:
select u.name as 'owner_name',
       o.name as 'table_name'
from   sysobjects o,
       sysusers u
where  o.uid  = u.uid
and    o.name = '<name_of_table>'
and    o.type = 'U'

-- or

select user_name(o.uid) as 'owner_name',
       o.name as 'table_name'
from   sysobjects o
where  o.name = '<name_of_table>'
and    o.type = 'U'

Comment: question updated with the context. Now my question is: where can I get the schema the table is contained in?
Comment: so in Sybase/SAP ASE "schema_name" = "table_owner_name" and you cannot change this, correct?
Comment: in PostgreSQL, I can do `SELECT table_catalog, table_schema, table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE' OR table_type = 'VIEW';`. How do I write it for Sybase/SAP ASE? It looks like sysdatabases is not connecting to sysobjects. Or does it?
Comment: 1) not sure why you're going against sysdatabases and 2) have you tried running the queries I've provided (above)?
Comment: it looks like for Sybase/ SAP ASE the database_name = catalog_name. And sysdatabases have a database_name. So, what I'm looking for is to get catalog_name, schema_name and table_name for for my DB. Unless I'm mistaken.
Comment: well, if you're sitting in the database (eg, you ran `use `), you can obtain the database name with `db_name()`
Comment: So catalog_name IS the same as database_name and I;m right here as well, right?
Comment: some googling appears to show that 'catalog name' == 'database name'
Answer: It works the same like in MS SQL Server. You can use schema.object.
If you use object then the object is searched:

first in our schema
then in dbo schema

You can also use the database.owner.object notation or database..object notation when owner is dbo or event server.database.owner.object notation when you connect an external ASE server.
Comment: question updated with more info. Could you clarify? Moreover if Sybase IS "schemaName.tableName", where can I get the schema name?


What's wrong with applying our intuition for the behavior of objects in low dimension to high dimension

Question: The following text is taken from the a book about linear programming that I'm reading:

A graphical illustration is useful for understanding the notions and procedures of linear programming, but as a computational method it is worthless. Sometimes it may even be misleading, since objects in high dimension may behave in a way quite different from what the intuition gained in the plane or in three-dimensional space suggests.

I don't know what the author is insinuating at by saying that the object's behavior is different from the intuition since my experience working with objects in higher dimension was always gained from lower dimension.
So, is there some concrete example illustrating this statement?
Comment: See the comments and answers for the mathoverflow questions [How to explain the concentration-of-measure phenomenon intuitively?](https://mathoverflow.net/q/210291/15780) and [Why are two "random" vectors in $\mathbb R^n$ approximately orthogonal for large $n$?](https://mathoverflow.net/q/248466/15780), AND the blog post [The Surprising Behavior of Data in Higher Dimensions](https://towardsdatascience.com/the-surprising-behavior-of-data-in-higher-dimensions-1c49bca9bbee), AND [this 17 June 2005 sci.math post](https://groups.google.com/g/sci.math/c/F1_GTvZBEE8/m/DPmjLU3ZxvAJ).
Comment: You mention programming, so in this context it is mandatory to mention [curse of dimensionality](https://en.m.wikipedia.org/wiki/Curse_of_dimensionality). Which is a consequence of a counterintuitive fact that in higher dimensions volume tends to accumulate around axis.
Comment: No one, except the author, knows what he was insinuating. Read on and feel free to disagree.
Comment: @freakish, could you elaborate on why curse of dimensionality is a consequence of that counterintuitive fact? Also, I think you meant volume tends to accumulate around the *corners* not axis, as one of the very helpful links that Dave wrote above says this.
Answer: You are missing what the Author is trying to convey.
(1) A graphical illustration is useful for understanding (by humans) the notions and procedures of linear programming, but as a computational method (by computers) it is worthless.
(2) Sometimes it may (not "will") even be misleading, since objects in high dimension may (not "will") behave in a way quite different from what the intuition gained in the plane or in three-dimensional space suggests.
Nobody except the Author can tell what thoughts led to that claim.
I will try to give Examples for these from my thoughts.

EXAMPLES :
(1A) There are Pairs of Curves which seem to intersect once , when viewed with DESMOS or Wolfram. When analysed with Calculus or other tools , it is revealed that there are 3 intersections.

It might even turn out that there is some very tiny sinusoidal nature at the central intersection , giving even more intersections.
Such things will not be visible with graphing methods.
We still know that there is at least 1 intersection , when we view the graphing output. Hence it is useful to know.
It is worthless when we try to get the actual intersection value.
(1B) To make the graph , the functions were evaluated at hundreds or even thousands of Points. It is computationally wasteful , giving us not much insight into the nature.
Instead , if we had used some calculus or other techniques , we might have got closed form values for the Intersection Points , with much less computational effort.
More-over , we will know much more , like number of Solutions , whether we have tangents , what if Parameters to the functions were varied , what is the range of the Intersection Points , etc
We have to give input to various numerical algorithms. These inputs are generally in symbolic or numeric form , not in graphical form. Eg When we want to get Extrema values or Intersection Points , then we give the Equations of lines / circles / functions. It is worthless to give Images of lines , circles & functions.
(2A) Consider 1D line.
Let us make some arrow from $1$ to $2$. Can we reverse the arrow , without leaving that Domain ? NO
Let the arrow be in 2D Plane from $(1,0)$ to $(2,0)$. Can we reverse the arrow , without leaving that Domain ? YES
We can rotate the arrow around and then shift it.
Intuition in 1D is wrong in 2D.
(2B) Consider a Point $x_1$ in 1D moving from $0$ to $3$.
Does this Point $x_1$ have to go through $2$ ? YES
Consider a Point $x_2$ in 2D moving from $(0,0)$ to $(3,0)$.
Does this Point $x_2$ have to go through $(2,0)$ ? NO
It can move up , then right , then down. It can avoid $(2,0)$.
(2C) Update our intuition : Does this Point $x_2$ have to go through the circle $x^2+y^2=1$ ? YES
Moving up in Dimensions , we have to update out intuition suitably.
(3) Consider the Purple Curve enclosing a hole in the region with 2 holes in 2D.

Can we make "Continuous Deformations" such that the Purple Curve contains 2 holes ? NO
Suppose that the region was 3D.

Can we make "Continuous Deformations" such that the Purple Curve contains 2 holes ? YES !!

There are many Examples where our Intuition helps us when we move to higher Dimensions.
Yet , there are many other Examples where our Intuition fails us when we move to higher Dimensions.
Best we can do is to update our Intuition along the way.
SUMMARY :
1D 2D 3D Images & Illustrations & graphs may help us , though these might not help in computations. Occasionally , these might mislead too , when we encounter some new Situation in higher Dimensions.

DISCLAIMER :
This Question is Opinion Based & there can be no "comprehensive" closed form answer.


Dependence of Error: Does it matter for data-driven models?

Question: Linear regression assumes that the errors of the response variable are independent of each other.
Lets assume that a data-driven model like a random forest or multi-layer perceptron is trained/formed with some data and the resulting error of the response variable is not independent with each other.
Does this matter in any way? What can be concluded from such behavior?
Answer: Ordinary Least Squares (OLS) assumes independent, identically distributed (i.i.d.) errors.  Generalized Least Squares (GLS) https://en.wikipedia.org/wiki/Generalized_least_squares , only requires the errors to be Multivariate Normal, but with any covariance (correlation) matrix.
Any departure from i.i.d. matters.
If you have a good basis (I don't mean Linear Algebra basis) for the error correlation matrix, you can use it as input to GLS.
Comment: Who exactly is the credit to mankind and statistical knowledge who down voted this answer?


How to pick a row randomly based on a number of tickets you have

Question: I have this table called my_users
my_id | name | raffle_tickets
1     | Bob  | 3
2     | Sam  | 59
3     | Bill | 0
4     | Jane | 10
5     | Mike | 12

As you can see Sam has 59 tickets so he has the highest chance of winning.
Chance of winning:

Sam = 59/74
Bob = 3/74
Jane = 10/74
Bill = 0/74
Mike = 12/74

PS: 74 is the number of total tickets in the table (just so you know I didn't randomly pick 74)
Based on this, how can I randomly pick a winner, but ensure those who have more raffles tickets have a higher chance of being randomly picked? Then the winner which is picked, has 1 ticket deducted from their total tickets
UPDATE my_users
SET raffle_tickets = raffle_tickets - 1
WHERE my_id = --- Then I get stuck here...

Server version: 5.7.30
Comment: @Akina Updated my post
Comment: 74? Are you sure?
Answer: For MySQL 8+
WITH
cte1 AS ( SELECT name, SUM(raffle_tickets) OVER (ORDER BY my_id) cum_sum
          FROM my_users ),
cte2 AS ( SELECT SUM(raffle_tickets) * RAND() random_sum
          FROM my_users )
SELECT name
FROM cte1
CROSS JOIN cte2
WHERE cum_sum >= random_sum
ORDER BY cum_sum LIMIT 1;

For 5+
SELECT cte1.name
FROM ( SELECT t2.my_id id, t2.name, SUM(t1.raffle_tickets) cum_sum
       FROM my_users t1
       JOIN my_users t2 ON t1.my_id <= t2.my_id
       WHERE t1.raffle_tickets > 0
       GROUP BY t2.my_id, t2.name ) cte1
CROSS JOIN ( SELECT RAND() * SUM(raffle_tickets) random_sum
             FROM my_users ) cte2
WHERE cte1.cum_sum >= cte2.random_sum
ORDER BY cte1.cum_sum LIMIT 1;

fiddle
Comment: I don't have 8+. I don't understand what CTE's are
Comment: @Jackie Query for 5+ version added.
Answer: You want a weighted pull from a random sample.  For this purpose, variables are probably the most efficient solution:
select u.*
from (select u.*, (@t := @t + raffle_tickets) as running_tickets
      from my_users u cross join
           (select @t := 0, @r := rand()) params
      where raffle_tickets > 0
     ) u
where @r >= (running_tickets - raffle_tickets) / @t and
      @r < (running_tickets / @t);

What this does is calculate the running sum of tickets and then divide by the number of tickets to get a number between 0 and 1.  For example this might produce:
my_id   name    raffle_tickets  running_tickets       running_tickets / @t
1       Bob          3                3               0.03571428571428571
2       Sam         59               62               0.7380952380952381
4       Jane        10               72               0.8571428571428571
5       Mike        12               84               1

The ordering of the original rows doesn't matter -- which is why there is no ordering in the subquery.
The ratio is then used with rand() to select a particular row.
Note that in the outer query, @t is the total number of tickets.
Here is a db<>fiddle.
Comment: Run fails on Mysql 5.7
Comment: @Jackie . . . It works fine in MySQL 5.7.  db<>fiddle is broken for MySQL 5.7.  I changed it to MySQL 5.6.
Comment: Why does the running tickets keep changing?
Comment: @Jackie . . . That is just a cumulative sum.  The ordering doesn't matter.
Comment: Are you sure this is right? Because sam doesn't show up as often as he should. Its almost like there is no weight to each row. I ran it 5 times and sam came up twice, and everyone else came up the other times
Comment: @jackie . . . I'm pretty sure it is correct.  Sam should appear in slightly more than half the results, and 2 out of 5 is a very reasonable result.  You would need to run it dozens or hundreds of times to get a reasonable distribution.


Add / Remove HTML element from page in directive

Question: I have a directive that shows or hides an HTML element [StackBlitz][1] :

{{user.name}}

And the Authorize directive is:
export class AuthorizeDirective implements OnInit {

  id: number;

  @Input() set authorize(id: number) {
    this.id = id;
  }

  constructor(private authService: AuthService, private element: ElementRef, private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) { }

  ngOnInit() {

    this.authorizationService.authorize(this.id).subscribe(result => {
      if (result == true)
        this.viewContainer.createEmbeddedView(this.templateRef)
      else
        this.viewContainer.clear();
    });

  }

}

As expected this adds the DIV to the page when result is true.
But when authorize method updates and returns a new value and result is true the DIV is added again.
When the value returned by authorize is updated I would like to:
if (value == false)
  // Remove DIV if exists in page
if (value == true)
  // Add DIV if does not exist in page

How can I do this?
Comment: `this.viewContainer.clear()`?
Comment: Seems to me your best bet is to maintain state in your directive, then compare the value of the subscribable to your state.
Answer: You want to use distinctUntilChanged() so that the observable does not emit duplicate values.
    this.authorizationService.authorize(this.id).pipe(
       distinctUntilChanged()
    ).subscribe(result => {
      if (result == true)
        this.viewContainer.createEmbeddedView(this.templateRef)
      else
        this.viewContainer.clear();
    });


Como abrir o MainPage.axml de um Xamarin Project no modo Designer?

Question: Então, recentemente baixei o Visual Studio 2017 e me deparei com o Aplicativo Multiplataforma (Xamarim.Forms ou Nativo), quando crio-o é gerado 4 projetos. O App1; App1.Droid; App1.IOS; App1.UWP (Universal Windows Plataform). Não entendo muito bem de Xamarin, mas imagino que o que eu fizer no projeto App1 será compilado para todas as outras plataformas, no entanto gostaria de abrir o MainPage.axml e o App.axml no modo designer para poder editar visualmente, mas só consigo fazer isso com o MainPage.axml e App.axml do projeto para UWP. Gostaria de saber como abro os arquivos do projeto principal.
Answer: Respondendo a sua dúvida/citação:
Sim, resumindo, em Xamarin.Forms você escreve o layout (View) das suas telas e a lógica da aplicação apenas uma vez (no seu caso, dentro do App1) e o layout nativo para as outras plataformas é gerado (compilado) automaticamente. É possível também alterar individualmente o layout e modificar o comportamento individual de cada plataforma caso queira algo mais específico.
Agora vamos a resposta para a sua pergunta:
Não há ainda um Designer disponível para as páginas XAML do Xamarin Forms. Você deve fazer tudo na "mão". Para ver o resultado você deve executar o aplicativo no emulador desejado ou no seu celular.
Essa informação pode ser encontrada na página dos conceitos básicos do Xamarin.Forms XAML: Xamarin.Forms XAML
Traduzindo o que está escrito lá:

Não há ainda um editor visual para o XAML gerado nas aplicações Xamarin.Forms, então todo o XAML deve ser escrito a mão.
Answer: App.xaml ("design") e App.cs (code behind) é apenas um arquivo digamos 'de partida' em projetos Xamarin-Forms.
O arquivo (App.xaml) não contem (diretamente) nada relacionado a parte de UI, digo diretamente porque nele pode conter configurações de estilos de design, cor da fonte por exemplo, etc. Resumindo essa view não tem a função de interagir com o usuário.
Uma das funções do arquivo (App.cs) é definir a página inicial do aplicativo dentre outras, para mais detalhes consulte: App Class
Modo design ainda não existe o que torna o desenvolvimento cansativo já que para verificar alteração na UI é necessário rodar aplicação, porém, conheço duas ferramentas que tornam essa tarefa menos dolorosa:

Xamarin.Forms Previewer Opção View > Other Windows > Xamarin.Forms Previewer

Gorilla Player Acho mais completo pois tem melhor suporte no reconhecimento do Xaml. É mais complicado para configurar (necessário instalar apk) mas vale a pena.
Baixar Versão para VS 2017

Fontes:
https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/application-class/
https://developer.xamarin.com/guides/xamarin-forms/xaml/xaml-previewer/
https://elbruno.com/2016/01/28/xamarin-live-preview-of-xaml-in-xamarinforms-using-gorillaplayer-in-visualstudio/
Comment: Ainda não testei o Xamarin Previewer, mas tenho ouvido falar que só funcionou no MS Build.
Comment: Instalei recentemente o VS 2017 e funcionou, porém ainda deixa a desejar, por exemplo, coloquei uma imagem de fundo e não reconheceu. Já no Gorilla Player funcionou perfeito.


MySQL find duplicate rows in UNION table

Question: How can I find duplicate email on below query?
SELECT b_email AS email FROM user WHERE status = 3 AND b_email != ''
UNION (SELECT c_email AS email FROM user WHERE status = 3 AND c_email != '')
UNION (SELECT user_email AS email FROM user WHERE status = 3 AND user_email != '')
UNION (SELECT user_email AS email FROM sub_user WHERE status = 3 AND user_email != '')
UNION (SELECT su_email AS email FROM sub_user WHERE status = 3 AND su_email != '')
ORDER BY email ASC

Thanks.
Answer: Your query results won't have duplicates because UNION removes duplicates. To preserve the duplicates, use UNION ALL instead:
SELECT b_email AS email FROM user WHERE status = 3 AND b_email != ''
UNION ALL SELECT c_email AS email FROM user WHERE status = 3 AND c_email != ''
...

To figure out which email addresses are duplicated you could do the following:

Change your query to return a list of all email addresses, including duplicates (this means use UNION ALL instead of UNION)
Wrap it with an outer query that counts by email address
Limit the outer query results to email addresses that have a count of two or more

Here's how to do it (note this assumes your posted query works):
SELECT email, COUNT(*)
FROM (
  SELECT b_email AS email FROM user WHERE status = 3 AND b_email != ''
  UNION ALL SELECT c_email AS email FROM user WHERE status = 3 AND c_email != ''
  UNION ALL SELECT user_email AS email FROM user WHERE status = 3 AND user_email != ''
  UNION ALL SELECT user_email AS email FROM sub_user WHERE status = 3 AND user_email != ''
  UNION ALL SELECT su_email AS email FROM sub_user WHERE status = 3 AND su_email != ''
) EmailGlom
GROUP BY email
HAVING COUNT(*) > 1

Your results will be every email address that shows up more than once in the inner query.


Uploading Json to django model database results in Key Error

Question: I have a custom manage.py command which I am using to upload a json file (a list of dictionaries) to my model. It appears to upload two records fine, but then throws a key error:
KeyError: 'headline'

My code is as follows:
class Command(BaseCommand):

def handle(self,*args,**options):
  filename = '/DoJ_Data_01-12-18.json'
  newpath = str(Path(home))+filename
  with open(newpath) as json_file:
    data = json.load(json_file)
    for d in data:

      q = doj(headline=d['headline'],topics=d['topics'],text=d['text'],url=d['url'],date=d['date'])
      q.save()

As far as I can tell the json is valid. What am I missing?
Comment: This was the correct approach. Using dict.get(key) worked.
Answer: So based on the comment by Red Cricket, the problem was solved using d.get['headline']. There appears to have been dictionaries without the headline key.


Erro no findOne do Mongoose

Question: estou recebendo Error: Invalid argument to findOne(): 'texto pesquisado' ao executar o findOne do Mongoose:
const User = mongoose.model('users', mySchema);
const query - 'texto pesquisado';

User.findOne(query, function(err, data) {
    if (err) return console.log('ERROR: ', err);
    return console.log('DATA: ', data);
});

Não estou encontrando o motivo desse erro, pois os argumentos da função estão aparentemente corretos. Alguém sabe o que pode estar ocorrendo?
Answer: O findOne espera um documento/objeto como parâmetro, não somente uma String como você passou. Verifica no exemplo abaixo:
const User = mongoose.model('users', mySchema);
const query = 'texto pesquisado';

User.findOne({nomecoluna: query}, function(err, data) {
    if (err) return console.log('ERROR: ', err);
    return console.log('DATA: ', data);
});

Você pode encontrar mais exemplos na documentação do mongoose
mongoosejs.com
Comment: Não entendi qual a relação de sua resposta com o erro que estou recebendo...
Comment: Error: Invalid argument to findOne(): 'texto pesquisado' ao executar o  findOne do Mongoose:

Você só ta passando o valor que quer buscar no documento
const query - 'texto pesquisado'; que ainda está errado
const query = 'texto pesquisado'; esse é o certo

Aqui também você errou
User.findOne(query, function(err, data) {}
você só passou como argumento a const query sem informa o nome da colula a buscar a informação da const query
O certo seria
User.findOne({nomecoluna: query}, function(err, data) {}

({nomecoluna: query} e assim que você passa argumento ! .
Comment: ah sim... agora percebi meu erro. Eu peguei um trecho de código com `find()` e apenas substitui pelo `findOne()` sem perceber que no `findOne()` é passado um objeto com `nameField: value` em lugar de apenas a string a ser pesquisada. Obrigado!

Erro no findOne do Mongoose


$F[t]$ has undecidable positive existential theory in the language $\{+, \cdot , 0, 1, t\}$

Question: Consider the ring $F[t, t^{-1}]$ (the polynomials in $t$ and $t^{-1}$ with coefficients in the field $F$).
Theorem 1.

Assume that the characteristic of $F$ is zero. Then the existential theory of $F[t, t^{-1}]$ in the language $\{+, \cdot , 0, 1, t\}$ is unecidable.

Theorem 2.

Assume that $F$ has characteristic $p>2$. Then the existential theory of $F[t, t^{-1}]$ is undecidable.

We have that even the positive existential theory of $F[t, t^{-1}]$ is undecidable.
Now we give a Lemma that, together with the preceding results, allows us to conclude the undecidability of the positive existential theory of $F[t]$ in the language $\{+, \cdot , 0, 1, t\}$.
Lemma.

If the characteristic of $F$ is other than $2$, then the solutions of $$X^2-(t^2-1)Y^2=1$$ with $X$ and $Y$ in $F[t]$ are given by $$(X, Y)=(\pm x_n, y_n)$$ where $$x_n+\sqrt{t^2-1}y_n=(t+\sqrt{t^2-1})^n$$ fr $n$ in $\mathbb{Z}$.

Theorem 3.

If the characteristic of $F$ is other than $2$, then $F[t]$ has undecidable positive existential theory in the language $\{+, \cdot , 0, 1, t\}$.

Proof.
Write $u=t+\sqrt{t^2-1}$.
Then $u^{-1}=t-\sqrt{t^2-1}$ and $F[u, u^{-1}]=F[t, \sqrt{t^2-1}]$.
We interpret the positive existential theory of $F[u, u^{-1}]$ in $F[t]$ in the following way:
an element $x$ of $F[u, u^{-1}]$ is represented as a pair $x=(a, b)$ with $a, b$ in $F[t]$ being the components of $x$ with repsect to the base $\{u, u^{-1}\}$ considering $F[u, u^{-1}]$ as a module over $F[t]$; addition and multiplication of elements of $F[u, u^{-1}]$ is defined accordingly.
So, we see that the positive existential theory of $F[u, u^{-1}]$ is interpretable in $F[t]$ with only one problem: we do not have constants for $u$ and $u^{-1}$ but only for $\frac{u+u^{-1}}{2}=t$.
So, the positive existential theory of $F[t]$ is undecidable provided that the theory of $F[u, u^{-1}]$ is undecidable in the language $\{0, 1, u+u^{-1}/2, +, \cdot\}$.
It is only a matter of routine checking to see that our undecidability result for $F[u, u^{-1}]$ holds true in this language as well: simply substitute $v=u-t$, write all equations involved in the form $fv=g$, where $f$ and $g$ have coefficients in $F[t]$ (the quantity $v^2$, wherever it appears, is replaced by $t^2-1$ which is in $F[t]$) and substitute the equations of this last form by the corresponding equations $f^2(t^2-1)=g^2$.
Of course, it is necessary to check that the new solutions that come onto the scene through the squaring do not do any harm to the stated equivalences.
Hence, the theorem follows.

$$$$
How do we use the Lemma at the proof of Theorem $3$ ? How is it useful?
$$$$
EDIT:
That's how I understood the whole proof of Theorem $3$ :
We know that the existential theory of $F[u, u^{-1}]$ in the language $\{+, \cdot , 0, 1, u\}$ is undecidable.
We want to reduce the positive existential theory of $F[u, u^{-1}]$ in the language $\{+, \cdot , 0, 1, u\}$ to the positive existential theory of $F[t]$ in the language $\{+, \cdot , 0, 1, t\}$ to show that this theory is also undecidable.
To do that we do the following:
We suppose that the positive existential theory of $F[t]$ in the language $\{+, \cdot , 0, 1, t\}$ is decidable.
We set $u=t+\sqrt{t^2-1}$. So, we have that $u^{-1}=t-\sqrt{t^2-1}$.
So, we have $F[u, u^{-1}]=F[t, \sqrt{t^2-1}]$. So, $F[u, u^{-1}]$ is an extension of $F[t]$.
Each element $x$ of $F[u, u^{-1}]$ can be written as followed: $x=a+b\sqrt{t^2-1}$, where $a,b \in F[t]$.
So, the mapping of the reduction is $x \mapsto (a,b)$.
$+ \ \ : \ \  $ $$x_1+x_2=a_1+b_1\sqrt{t^2-1}+a_2+b_2\sqrt{t^2-1}=(a_1+a_2)+(b_1+b_2)\sqrt{t^2-1} \mapsto (a_1+a_2, b_1+b_2)$$
$\cdot  \ \ : \ \  $ $$x_1\cdot x_2=(a_1+b_1\sqrt{t^2-1})(a_2+b_2\sqrt{t^2-1})=a_1 \cdot a_2+a_1 \cdot b_2 \sqrt{t^2-1}+a_2 \cdot b_1\sqrt{t^2-1}+b_1 \cdot b_2 (t^2-1)=(a_1 \cdot a_2+b_1 \cdot b_2 (t^2-1))+(a_1 \cdot b_2+a_2 \cdot b_1)\sqrt{t^2-1} \mapsto (a_1 \cdot a_2+b_1 \cdot b_2 (t^2-1), a_1 \cdot b_2+a_2 \cdot b_1)$$
$0  \ \ : \ \  $ $$0=0+0 \sqrt{t^2-1} \mapsto (0,0)$$
$1 \ \  :  \ \ $ $$1=1+0 \sqrt{t^2-1} \mapsto (1,0)$$
$u \ \ : \ \  $ $u \mapsto u-t=:v$. We write all the equations in the form $fv=g$ where $f,g \in F[t]$ and squaring these equations we get $f^2v^2=g^2 \Rightarrow f^2(t^2-1)=g^2$, so all these equations are in $F[t]$, where $t=(u+u^{-1})/2$.
So we can convert the algorithm that answers to positive existential questions of $F[t]$ to an algorithm that answers to existential questions of $F[u, u^{-1}]$.
Since the second theory is undecidable, we get aa contradiction. So the positive existential theory of $F[t]$ is undecidable.
$$$$
Is this correct?
Comment: to me none of this make any sense
Comment: As explained in another post by the OP http://math.stackexchange.com/questions/1380768/algorithm-to-answer-existential-questions-reduction/1385515#1385515  she is trying to understand a paper by Pheidas on Extensions of Hilbert's tenth problem http://www.jstor.org/stable/2275396?seq=1#page_scan_tab_contents
Comment: @mercio: PS: you can definitely be forgiven for not being aware of the context as the OP didn't choose to tell us.
Answer: You are, I believe, asking about a proof in the paper Extensions of Hilbert's Tenth Problem by Thanases Phaedas. You've asked three questions about this. The background is that Phaedas has proved that the existential theory of $F[u, u^{-1}]$ is undecidable (he actually wrote $t$ rather than $u$ when he proved, but he has now switched to $u$). He is trying to get stronger result by reducing decidability in the polynomial ring $F[t]$ to decidability in the ring of Laurent polynomials $F[u, u^{-1}]$. The approach is to extend $F[t]$ to $F[t, s\mathrel{|} s^2 = t^2 - 1]$ (but Phaedas doesn't quite put it like that). Then one observes that $F[t, s]$ is isomorphic to $F[u, u^{-1}]$ under an isomorphism that associates $t$ with $(u + u^{-1})/2$ and $s$ with $(u - u^{-1})/2$.
Your first question is:

an element $x$ of $F[u, u^{-1}]$ is represented as a pair $x=(a, b)$ with $a, b$ in $F[t]$ being the components of $x$ with repsect to the base $\{u, u^{-1}\}$ considering $F[u, u^{-1}]$ as a module over $F[t]$

Does this mean that we write any element $x$ of $F[u, u^{-1}]$ in the form $x=au+bu^{-1}$ ?

It means that every $x \in F[u, u^{-1}]$ can be written uniquely as $x = au+bu^{-1}$ for $a, b \in F[t]$. However, I believe this is false. $F[t, s]$ is a free module of rank $2$ over $F[t]$, a suitable base being $\{1, s\}$ (which Pheidas would write as $\{1, \sqrt{t^2 - 1}\}$). What this means is that every element $x \in F[u, u^{-1}]$ can be written uniquely in the form $a + bs$ with $a, b \in $F[t]$.  I believe this is just a (very significant) typo.
Your second question is:

We have that each element of $F[u, u^{-1}]$ can be represented as an element of $F[t]$, besides $u$ and $u^{-1}$, becasuse the language does not consist of a square root. Is this correct?

What we have is that each element of $F[u, u^{-1}]$ can be represented uniquely as a pair of elements $a, b$ of $F[t]$ with $(a, b)$ representing $a + bs$ (following my correction to Pheidas's statement about the basis above).
Your final question is:

$\ldots$ simply substitute $v=u-t$, write all equations involved in the form $fv=g$, where $f$ and $g$ have coefficients in $F[t]$ (the quantity $v^2$, wherever it appears, is replaced by $t^2-1$ which is in $F[t]$) $\ldots$

Why can we write all the equations in the form $fv=g$, where $f$ and $g$ have coefficients in $F[t]$ ?

$F[u, u^{-1}]$ is generated over $F$ as a ring by $t$ and $v$, hence any equation in $F[u, u^{-1}]$ can be written as $p(t, v) = 0$ where $p$ is a polynomial with coefficients in $F$, but $v^2 = t^2-1$, so we can arrange for $p$ to have the form $vf(t) - g(t)$ for $f, g \in F[t]$. and then $p(r, t) = 0$ is equivalent to $fv = g$.
Comment: See https://en.wikipedia.org/wiki/Module_(mathematics) for the definition of a module over a ring (or, and much better, read an introductory book on ring theory or attend a course). Whenever $R$ is a subring of a ring $S$, $S$ automatically becomes a module over $R$ in a standard way. Here $F[t]$ is a subring of $F[u, u^{-1}]$.
Comment: You say that the approach of the reduction is to extend $F[t]$ to $F[t,s\mid s^2=t^2-1]$ and at the beginning of the proof we take $u=t+\sqrt{t^2-1}$. Why do we take this extension? Which the reason that we take this $u$ ? $$$$ What does it mean that "$F[t,s]$ is a free module of rank $2$ over $F[t]$" ?
Comment: I have tried to expand my answer a bit to help with these comments. To say a bit more out the motivation: if you play around with the elements $t = (u + u^(-1})/2$ and $s = (u + u^{-1})/2$ in the ring of Laurent polynomial $F[u, u^{-1}]$, you find they have the pleasant property that $s^2 = t^2 -1$ and that they generate $F[u, u^{-1}]$ in a very simple way (as a free $F[t]$ module of rank 2). This makes it natural to see if everything one needed to express in the language of $F[u, u^{-1}]$ in the first undecidability result can be recast in the language of $F[t]$.
Comment: Why do the elements $t$ and $s$ generate $F[u, u^{-1}]$ ? $$$$ At which point of the proof do we use the Lemma? $$$$ I still don't understand the part: "So, we see that the positive existential theory of $F[u, u^{-1}]$ is interpretable in $F[t]$ with only one problem: we do not have constants for $u$ and $u^{-1}$ but only for $\frac{u+u^{-1}}{2}=t$.

So, the positive existential theory of $F[t]$ is undecidable provided that the theory of $F[u, u^{-1}]$ is undecidable in the language $\{0, 1, u+u^{-1}/2, +, \cdot\}$." Could you explain it to me?
Comment: We want to map the elements of $F[u, u^{-1}]$ into the elements of $F[t]$, right?

There is no mapping of the elements $u=t+\sqrt{t^2-1}$ and $u^{-1}=t-\sqrt{t^2-1}$ into an element of $F[t]$, because the square root is not contained at the language so $t+\sqrt{t^2-1}$ and $t-\sqrt{t^2-1}$ are not elements of $F[t]$.

Have I understood it correct so far?

Why do we have to look then at the language $\{0, 1, u+u^{-1}/2, +, \cdot\}$ and not at the original language $\{+, \cdot , 0, 1, t\}$ ? Could you explain it to me?
Comment: But the base is $\{1, \sqrt{t^2-1}\}$, so isn't the representation of $u$, $(t, 1) \in F[t]$ and the representation of $u^{-1}$, $(t, -1) \in F[t]$ ? So there is a mapping from $u$ and $u^{-1}$ into an element of $F[t]$. Or is this wrong? I got stuck right now...
Comment: We want to map statements about $F[u, u^{-1}]$ into equivalent statements about $F[t]$. The way this is done is by showing that $F[u, u^{-1}]$ can be viewed as a free $F[t]$-module of rank $2$. This is like mapping statements about complex numbers into equivalent statements about *pairs* of real numbers.
Comment: What does the expression "free $F[t]$-module of rank $2$" mean? $$$$ So, $F[u, u^{-1}]$ represents the complex numbers and $F[t]$ represents the pairs of real numbers? Or have I understood wrong your last sentence?
Comment: Mary: no, in my analogy $F[u, u^{-1}]$ is analogous to $\mathbb{C}$ and $F[t]$ is analogous to $\mathbb{R}$. In the language of $\mathbb{C}$ you can make the (true) statement that every number is a square: $\forall z \exists w\cdot w^2 = z$. This translates into the following statement about real numbers $\forall x \forall y\exists u \exists v \cdot (x = u^2 - v^2 \land y = 2uv)$.
Comment: Oh, I see... But why do we have to look at the language $\{0, 1, u+u^{-1}/2, +, \cdot \}$ and not at the language $\{+, \cdot , 0, 1, t\}$ ?
Comment: What the paper is doing is translating a statement from the language with $u$ and $u^{-1}$ into the language with just $t$, so that an undecidable sentence in the former language gives an undecidable sentence in the latter.
Comment: I think I understood it now...
Comment: I have also a question about the last part: $$$$ "$F[u, u^{-1}]$ is generated over $F$ as a ring by $t$ and $v$, hence any equation in $F[u, u^{-1}]$ can be written as $p(t, v) = 0$ where $p$ is a polynomial with coefficients in $F$, but $v^2 = t^2-1$, so we can arrange for $p$ to have the form $vf(t) - g(t)$ for $f, g \in F[t]$. and then $p(r, t) = 0$ is equivalent to $fv = g$." $$$$ Why, when we know that $F[u, u^{-1}]$ is generated over $F$ by $t$ and $v$, we conclude that any equation in $F[u, u^{-1}]$ can be written as $p(t, v) = 0$ where $p$ is a polynomial with coefficients in $F$ ?
Comment: The equation will have the form $a = b$ where $a$ and $b$ can be written as polynomials in $t$ and $v$, say $a = q(t, v)$ and $b = r(t, v)$ and then $a = b$ is equivalent to $a - b = 0$ which is equivalent to $p(t, v) = 0$ where $p(t, v)$ is the polynomial $q(t, v) = r(t,v)$.
Comment: I see... And why can we arrange for $p$ to have the form $vf(t) - g(t)$ for $f, g \in F[t]$ when we have that $v^2 = t^2-1$ ?
Comment: Because the equation $v^2 = t^2 - 1$ allows us to replace higher power of $v$ by terms of lower degree in $v$. [As an aside: what is your interest in this paper by Phaedas?]
Comment: I haven't really understood it... Could you explain it further to me? $$$$ I chose for my master thesis the topic of undecidable and decidable problems that are related to differntial equations and the prof gave me this paper to read...
Comment: Do you mean for example the following? $v^5+t=v(v^2)^2+t=v(t^2-1)^2+t$
Comment: But how do we conclude, when we write the equations in that form, that $F[u, u^{-1}]$ is undecidable also in the language $\{0, 1, u+u^{-1}/2, +, \cdot \}$ ?
Comment: I read it again and that's what I understood:

The mapping of the reduction is $u \mapsto u-t =:v$.

We write all the equations in the form $fv=g$ where $f,g \in F[t]$ and when we square these equations we get $f^2v^2=g^2 \Rightarrow f^2(t^2-1)=g^2$, so all the equations are in $F[t]$, where $t=(u+u^{-1})/2$.

Is this correct?
Comment: @MaryStar: I think you are on roughly the right lines now.
Comment: I added at my initial post how I understand the whole proof of Theorem $3$... Could you take a look at EDIT$5$ and tell me if it is correct?
Comment: What does it mean that "$F[u,u^{−1}]$ is a module over $F[t]$" ?
Comment: Could you clarify to me at which point of the proof we use the Lemma?
Comment: I have read the proof several times but I still haven't understood where the Lemma helps us... Do you have an idea?


How to shift a normal distribution to be centered at mean 0?

Question: I'm not a statistician and this is my first post on stackexchange, so I apologize if I'm not following guidelines.
My situation is that I have a prognosticator who projects sales revenue for 30 different products in my company and I have 3 years worth of data. My goal is to determine what his predictions would look like over 1000 years.
First, I normalized the difference between his predictions and actual results to percentages of the predicted guess, since different products have different projections.
So I'm assuming that the difference between his predictions and actual results look like a normal distribution.
Right now, I'm getting a mean of 2% and standard deviation of 13%.
My question is that I want to see what the normal distribution looks like around a mean of 0. I know that right now, that on average he tends to over predict by 2%, but I'm assuming that due to the small sample size that he could just as like be under predicting by 2%. So I'd like to take the same data and have a mean of 0 and know how I'm supposed to change the standard deviation.
For example, if I shift the mean to 0, would the standard deviation stay 13%? I assume the standard deviation should move up to account for the fact that if we're moving the mean to 0 that we're in essence saying that his predictions are more accurate and therefore the standard deviation would need to be increased to take this into consideration.
Does that make sense? Thx in advance.
Comment: You can change the mean to $0$ simply by subtracting the sample mean from all the sample values to create a new set of "centered sample" (meaning that the mean of the centered samples is $0$. The centered samples enjoy the same standard deviation as the original samples.
Answer: The standard deviation is calculated by using the empirical mean as the best estimate for the true mean. If you for some reason know the true mean you can calculate a better estimate of the standard deviation as $$\sigma=\sqrt{(1/N)\sum (X-\mu)^2}$$
This can give a higher standard deviation as you mention. But it can also be lower since the unbiased (default) estimate of the standard deviation is
$$\sigma=\sqrt{[1/(N-1)]\sum (X-\mu_{emp})^2}$$
You notice here the $1/(N-1)$ is different from the $1/N$: this is to take account of the downward bias added when using a estimated mean value. The empirical mean is the value that minimizes the sum, so by using the empirlcal mean without the correction the standard error measurement will be biased.
Comment: Using $N-1$ rather than $N$  gives an unbiased estimator of the variance, but the square root of that isn't an unbiased estimator of the SD. The remaining bias is often ignored, but it exists.


JSON error using Struts2

Question: When I start my jsp I use a javascript function to charge in session a user. The javascript function use JSON with a struts2 action. This is the code:
JSP:

   ...

Javascript:
function usarAJAXCargarCookie() {
   var userCookie = getCookie('userCookieSL');
   $.getJSON('ajaxCookie', {
      userCookie: userCookie
   }, function (jsonResponse) {
   });
}

struts.xml
<action name="ajaxCookie" class="Acciones.HomeFavoritos" method="ajaxCookie">
   <result type="json">
      <param name="excludeNullProperties">true</param>
      <param name="noCache">true</param>
   </result>
</action>

HomeFavoritos.java
@SkipValidation
public String ajaxCookie() throws Exception{
    if(sesion==null){
        sesion=ActionContext.getContext().getSession();
    }
    if(sesion.get("usuarioLogueado") == null || sesion.get("usuarioLogueado").equals("")){
        cargarUsuarioNoLogueado(sesion, userCookie);
    } else {
        cargarUsuarioLogueado(sesion);
    }
    return SUCCESS;
}

And I receive this error:
Grave:   Exception occurred during processing request: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: java.lang.reflect.InvocationTargetException
org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: java.lang.reflect.InvocationTargetException
    at org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:246)
    at org.apache.struts2.json.JSONWriter.processCustom(JSONWriter.java:178)
    at org.apache.struts2.json.JSONWriter.process(JSONWriter.java:168)
    at org.apache.struts2.json.JSONWriter.value(JSONWriter.java:134)
    at org.apache.struts2.json.JSONWriter.write(JSONWriter.java:102)
    at org.apache.struts2.json.JSONUtil.serialize(JSONUtil.java:116)
    at org.apache.struts2.json.JSONResult.createJSONString(JSONResult.java:197)
    at org.apache.struts2.json.JSONResult.execute(JSONResult.java:171)
    at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:371)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:275)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)

Comment: This is unclear what are you trying to return as json response.
Answer: InvocationTargetException is just a wrap around the real exception, that you're not showing us.
It will probably be a serialization exception, so consider using a root object as described here, instead of serializing the whole action.
Also try using english names in the code, and please, NEVER write package names with something different from lowercase (Acciones.HomeFavoritos...)

JSON error using Struts2


Explain me like I'm 5 - RewriteRules, please

Question: I try to understand how to manage subdomains in Apache (mod_rewrite module).
On this website:
http://htaccess.madewithlove.be/
This link below:
http://www.sub.tst.com/foo/bar.php

Under this rule:
RewriteRule (.*)bar(.*)$ $1oxo$2 [PT]

Returns:
✔ The new url is http://www.sub.tst.com/foo/oxo.php

But under following rule (or any other similar):
RewriteRule (.*)tst(.*)$ $1oxo$2 [PT]

It returns an error:
✖ This rule was not met.

I want to redirect links with subdomains to proper subfolders (to tst.com/sub/foo/bar link - if it exists), so I think I just have to cut www.sub.tst.com/foo/bar.php into 2 chunks, where 'sub' and '/foo/bar.php' I put after 'tst.com' (and remove '.php' extension from the end of it), but so far regex is not working on rewrite rules as I expect (and as I test it on php).
What is wrong? How to get it right? How to test it, before I use it on my website?
Answer: The search pattern uses standard regular expressions.  So in your case, the parenthesis constitutes a regex group. The first one matched will take the place of $1, and so on.  Remember also that regex are greedy. That is they will match as much as they can.
The reason your RewriteRule doesn't match your example, is because the PATTERN is only checked against "[...] the part of the URL after the hostname and port".
To accomplish what you want, you might want to use a combination of RewriteCond with RewriteRule.  So basically use RewriteCond to determine if a subdomain matches, then rewrite the domain part entirely.  Example:
RewriteCond %{HTTP_HOST} ^www.sub.tst.com [NC]
RewriteRule ^(.*)$ http://tst.com/sub/$1 [L]

In this case, the RewriteCond works as an if statement for the following RewriteRule.
It's not pretty, but it might do the work for you.

Updated: based on comments from cooba and olaf.
You can accomplish what you need with the following rules
RewriteCond %{HTTP_HOST} !www.tst.com [NC]
RewriteCond %{HTTP_HOST} ^(www.)*(([^.]*).)tst.com [NC]
RewriteRule ^(.*)$ http://tst.com/%3/$1 [L]

Start from the 2nd RewriteCond.  Here, the first part of of the regex ^(www.) is needed to find cases where the domain contains www or not (www.sub.tst.com or sub.tst.com).
The second part of the regex (([^.]*)\.) matches the subdomain.  The part we want is the inside group (the one without the .).  When the regex is evaluated, that inner group takes position 3.  To access that value in the RewriteRule, you use %.
Now, the 1st RewriteCond is needed to guard about rewriting www.tst.com into tst.com/www/.
Comment: @cooba You can capture part of the domain, e.g. `www.(.+?).tst.com` and then use it in the substitution `http://tst.com/%1/$1`. Notice the percent `%` vs dollar `$` sign.
Comment: If I use the same pattern for http://sub.tst.com/foo/bar link - than "This condition is not met". There are so many cases and subfolders, so do I have to create always a separate rule for each one of them?
Comment: @OlafDietsche Your regex is still catching only one case: [https://regex101.com/r/xZ6uK1/1](https://regex101.com/r/xZ6uK1/1). Why you use single dot '.' instead of '\.'? Do you know any other place where I could ask about RewriteRules?
Comment: @cooba Most of your samples are irrelevant, because `HTTP_HOST` is just the domain part, nothing else. It doesn't include `http`, `/`, or any other part of the request. To learn about mod_rewrite, you can just follow jzer7's link. But in this case, it's more about the regular expression.
Comment: Using `.` instead of `\.` was just laziness.
Comment: Thank you @olafDietsche, that tip about `%1` was great.
Comment: @jzer7 On my website last rules are creating deeper cascading loop (from: /foo/bar.php - towards: /foo/foo/foo/bar.php...) and it's opening index.php file - instead of bar.php file. What could be wrong? Is there any non site-affecting way to test htaccess file custom modifications?


Indexing file paths or URIs in Lucene

Question: Some of the documents I store in Lucene have fields that contain file paths or URIs. I'd like users to be able to retrieve these documents if their query terms contain a path or URI segment.
For example, if the path is
C:\home\user\research\whitepapers\analysis\detail.txt

I'd like the user to be able to find it by queriying for path:whitepapers.
Likewise, if the URI is
http://www.stackoverflow.com/questions/ask

A query containing uri:questions would retrieve it.
Do I need to use a special analyzer for these fields, or will StandardAnaylzer do the job? Will I need to do any pre-processing of these fields? (To replace the forward slashes or backslashes with spaces, for example?)
Suggestions welcome!
Answer: You can use StandardAnalyzer.
I tested this, by adding the following function to Lucene's TestStandardAnalyzer.java:
public void testBackslashes() throws Exception {
  assertAnalyzesTo(a, "C:\\home\\user\\research\\whitepapers\\analysis\\detail.txt", new String[]{"c","home", "user", "research","whitepapers", "analysis", "detail.txt"});
  assertAnalyzesTo(a, "http://www.stackoverflow.com/questions/ask", new String[]{"http", "www.stackoverflow.com","questions","ask"});

}
This unit test passed using Lucene 2.9.1. You may want to try it with your specific Lucene distribution. I guess it does what you want, while keeping domain names and file names unbroken. Did I mention that I like unit tests?
Comment: Thanks! Using the StandardAnalyzer to index path segments also works in Lucene.Net 2.4.0.
Comment: Do you know of an out-of-the-box Lucene Analyzer that would break the domain name apart at the "dots" or separate the filename from its extension?
Comment: Maybe you can use LetterTokenizer  http://lucene.apache.org/java/2_2_0/api/org/apache/lucene/analysis/LetterTokenizer.html chained with some filter. LetterTokenizer divides text at non-letters.

Indexing file paths or URIs in Lucene


Running Powershell script from task scheduler when the name of the folder where script is kept has spaces

Question: I have a Powershell script (on Windows Server 2008 R2) which runs successfully from console.
When I run it from Task Scheduler it does not enter the script and task completes with a status of 0x1.
The account running the script is an administrator.
Comment: Can you also show the Action?
Comment: Yes. I know why you want to see it it because the problem is there itself. The name of the folder where script is kept has spaces. Therefore, when I chose program/script , the task scheduler would take up apostrophes ("  "). After a long struggle I got to know the solution. It is pasted in the answer section.
Answer: The folder where the script was present was
D:\Some Folder\script.ps1
The folder name had spaces. So when I added the action in the task scheduler to run a program/script , the scheduler itself would put apostrophes (" ") and the action would look something like below:-

After long struggle I found out that the apostrophes were causing the task scheduler not to run the script.
To fix this , there are two solutions :-

Change the folder name to something without spaces
Pass the script as argument. This can be done by changing the below:-

program /script : Powershell.exe
the argument : -file "D:\Your folder name with space\your_script.ps1"
Below is the grab from my task scheduler.

Hope this helps everyone who faces such problem .


Find the volume generated by revolving the given region around $y$ axis.

Question: Find the volume of solid generated by revolving the described region about $y$ axis
The region enclosed by the line $y =x$, $y =-x/2$ and $x =2$
So, this is how I setup the integral
Volume  = $\displaystyle 2\pi \int_{0}^{2}(2-x) (3x/2) dx$
When I calculate this the answer comes out to be $4\pi$
However, the answer given to me is $8\pi$
Can anyone please check and tell me what is wrong with my solution ?
Thank you.
Answer: If you draw the figure in the $xy$ plane, you have a triangle with a vertex at the origin. Then, using cylindrical shells with radius $x$ and height $3x/2$, your integral is $$V=2\pi\int_0^2x\frac32 x dx=8\pi$$


Can I alter the order that points in an Maps Overlay are drawn on the Map

Question: I have an Maps Overlay which contains multiple points, each with its own numbered marker.  The points are in the overlay in the order I would like them to be drawn (ie from Marker 0 to 10 - with 10 being the latest point). When the map is displayed it appears that points are drawn in the order of increasing Latitude. This means than in my case the marker for point 7 may be drawn on top of the marker for point 10. Is there any way of controlling the order in which the markers will be laid out on the map?
Comment: Might I suggest taking your answer (starting from "Updated! I found it..."), removing it from the question and adding it as an answer?  This way people can see that the question actually has been answered quite easily and can also vote the question and the answer up separately.
Comment: Scott, thanks, I have done this now - I couldn't answer my own question when I originally raised it as I didn't have enough Reputation & then I forgot all about it :(
Comment: Cool, thanks for doing it now!
Answer: I found it - I have added the following code and it seems to work. This forces the items to be drawn in the same order as they are in the Overlay and not in order of increasing Latitude.
Interestingly, if you choose a different order (e.g. reversed) then the map will display as you ask it with earlier entries overlaying later ones. i.e. point 7 will be drawn on top of point 10 if they both have the same map coordinates. However when you tap on a what is displayed as point 7, the onTap method will give you the index for point 10 (presumably because it was drawn 10th in the sequence) which may cause you some confusion. It is then up to you to remember the sequence you asked points to be displayed and work out which entry is actually on top.
<code>    @Override
protected int getIndexToDraw(int drawingOrder) {
    // Log.d("getIndexToDraw", "drawing order: " + drawingOrder);  //just my debug
    return drawingOrder; // forces order to follow overlay item sequence
    // return super.getIndexToDraw(drawingOrder); // default code - ie Latitude order
}
</code>


Como pegar o valor de uma ListBox a partir do índice selecionado de outra ListBox?

Question: Estou tentando pegar o valor de uma ListBox a partir do índice selecionado de outra ListBox, porém não funciona. O que tenho até o presente momento:
for (int i = 0; i < 10; i++)
{
    Lst_ListBoxA.Add(2 * (3 * i) * 4);
    Lst_ListBoxB.Add(2 * (3 / i) * 4);
}
private void Lst_ListBoxB_SelectedIndexChanged(object sender, EventArgs e)
{
    //Aqui, o usuário seleciona o segundo índice (1).
    string Valor = Lst_ListBoxA.GetItemText(Lst_ListBoxB.SelectedIndex);
    MessageBox.Show(valor);
}

O que está sendo retornado, ou mostrado na MessageBox, é o índice selecionado da Lst_ListBoxB, 1, e não o valor do índice correspondente da Lst_ListBoxA, 24, qual seria o modo correto de fazê-lo?
Comment: Editei as tags, `winforms`.
Comment: WebForms ou Windows Forms?
Answer: Você deve estar procurando por algo assim:
private void Form1_Load(object sender, EventArgs e)
{
   Lst_ListBoxA.Items.Add("Item 1A");
   Lst_ListBoxA.Items.Add("Item 1B");
   Lst_ListBoxA.Items.Add("Item 1C");

   Lst_ListBoxB.Items.Add("Item 2A");
   Lst_ListBoxB.Items.Add("Item 2B");
   Lst_ListBoxB.Items.Add("Item 2C");
}

private void Lst_ListBoxB_SelectedIndexChanged(object sender, EventArgs e)
{
   int i = Lst_ListBoxB.SelectedIndex;
   string Valor = Lst_ListBoxA.Items[i].ToString();
   MessageBox.Show(Valor);
}

Isso deverá funcionar para você.
Comment: Então é possível tratar qualquer objeto que tenha uma coleção de itens (ComboBox, ListBox, ListView...) como se fosse um array?
Answer: Pelo evento SelectedIndexChanged, você consegue pegar o Indice do ListBox.
private void Form1_Load(object sender, EventArgs e)
{
        listBox1.Items.Add("aluno 1");
        listBox1.Items.Add("aluno 2");
        listBox1.Items.Add("aluno 3");

        listBox2.Items.Add("aluno 1");
        listBox2.Items.Add("aluno 2");
        listBox2.Items.Add("aluno 3");
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
        int i = listBox1.SelectedIndex; //pegando o index do item selecionado
        listBox2.SelectedIndex = i; //posicionando o outro listbox
        MessageBox.Show(listBox2.Text); //mostrando o valor que ele tá!
}

Nesse exemplo carregando os listbox funciona assim.
Referencia

ListBox.SelectedIndexChanged Event
Comment: Eu não entendi muito bem a última linha... Vou colocar mais dados na pergunta.
Comment: @Patrick, é essa forma usualmente pelo evento! clico ele já posiciona e mostra o valor!


How to write a unit test in vitest that expects an error

Question: I want to mock an object method that throws an error but the test is always failing with these errors.
I can't post the image yet but please check the link. It shows the test failing.
throw new Error
Here's my code below:
workload.js
const workload = {
    job: [
        {workload_1: 'workload 1'}
    ],
    createWorkloadJSON: async function(workload){
        await fsp.appendFile('./workload.json',JSON.stringify(workload))
        if(fs.existsSync('./workload.json')) return true
        else throw new Error('workload.json creating failed.')
    }
}

workload.test.js
describe('workload', ()=>{
    afterEach(()=>{
        vi.restoreAllMocks()
    })

     it('throws an error when workload.json is not found', async ()=>{
            const spy = vi.spyOn(workload, 'createWorkloadJSON').mockImplementation(async()=>{
                throw new Error('workload.json creating failed.')
            })
            expect(await workload.createWorkloadJSON()).toThrow(new Error('workload.json creating failed.'))
            expect(spy).toHaveBeenCalled()
        })
    })

Answer: In general you'd use expect(() => yourFunctionCall()).toThrowError() to test for an exception being thrown. (In the OP's case, there was also an async function where the reject had to be captured too.)
Example from the docs:
import { expect, test } from 'vitest'

function getFruitStock(type) {
  if (type === 'pineapples')
    throw new DiabetesError('Pineapples are not good for people with diabetes')

  // Do some other stuff
}

test('throws on pineapples', () => {
  // Test that the error message says "diabetes" somewhere: these are equivalent
  expect(() => getFruitStock('pineapples')).toThrowError(/diabetes/)
  expect(() => getFruitStock('pineapples')).toThrowError('diabetes')

  // Test the exact error message
  expect(() => getFruitStock('pineapples')).toThrowError(
    /^Pineapples are not good for people with diabetes$/,
  )
})

https://vitest.dev/api/expect.html#tothrowerror
Answer: Throwing in the test scope will throw in the test. Generally you need to pass a function instead, otherwise it will run in place. In Vitest you can use https://vitest.dev/api/#rejects to skip some boilerplate.
Comment: Thanks! That worked.
I never occurred to me that it was because of its asynchronous nature and writing test for rejected asynchronous code was different

It still looks weird that now I have to `await` the `expect()` instead of the function being tested when an async function is being rejected but you'd go the normal way of writing test when a async function is resolved.
`await expect(workload.createWorkloadJSON()).rejects.toThrow(new Error('workload.json creation failed.'))`


Can Drupal be used for hierarchical multi-site?

Question: Can you use Drupal to make a site hierarchy?
The main reason would be managing permissions and general connections between sub sites, like the following one:

                       Site 1
        Site 2         Site 3         Site 4 …
    Site 5   Site 6                   Site 7 …
Comment: Granted, this is a low quality question, but I think we can coax the OP into revising it into a better question. Please try that before simply downvoting.
Comment: You're answer pretty much covered the whole subject, top to bottom. I added some details to the question, but I was interested in mainly that is it capable of doing so, or is it not. WP can only do every subsite top-level, looking for an alternative which can do it sub-level.
Answer: This is a very vague question in that it doesn't give any semblance of the relation between the sites, or how they link to each other.
There are at least 3 different ways to make a unified site using multiple domains/subdomains using drupal:
1) Organic Group/Taxonomy/User based subdomains.
Each Group, Primary Taxonomy, or User gets their own subdomain, and their content is listed there.  Cross domain login issues are relatively mild, and just a matter of fixing the cookie domain as .domain.name, where the subdomains would be group.domain.name or user.domain.name or term.domain.name.
2) Domain Access based domains
This is more an "affiliated network of sites" concept.  Content is assigned to a specific site, and can be shared among all sites, or specific only to one. You link sites together using modules like Views as you can select content in any way you please, and give each site an individual look, or maintain a more consistent network theme.
  This can be implemented either as domains or subdomains, so cross-domain login issues are possible here, and can be difficult to mitigate effectively if you're trying to give an integrated feel.  SSO is one possible way to solve the issue, but other tweaks, such as pulling the login id across domain boundaries is also possible.  (This takes a little bit of technical wizardry)
3) Drupal sites based on a single install
All the sites share a code base, but each has their own database.  Automated links between the sites would need to be done through communication channels like RSS or RPC, or else maintained manually. As the user databases are separate, there are no common logins across sites.  SSO is probably a must in this case.
What solution fits your specific needs is not apparent from the question you're asking here, so please narrow the scope of your question by providing details as to what you mean by "site hierarchy".  What specifically makes otherwise unrelated host names (or domain names) into a hierarchy?


need VHDL equivalent of c-language "strtok" and "strcmp" functions that can operator on vhdl string type

Question: I'm trying to write a stimulus reader for vhdl testbench.  it needs to read a text command and two text operands delimited by whitespaces in a text file.
entity tb is
end entity;

architecture sim is tb of
begin

process
    variable L        : line;
    file     STIMFILE : test is in "stim.txt";
    variable s1       : string;
    variable s2       : string;
    variable s3       : string;
begin

    while not endfile(STIMFILE) loop
        readline(STIMFILE, L);

        s1 := strtok(L, "\n\t ");
        s2 := strtok(0, "\n\t ");
        s3 := strtok(0, "\n\t ");

        if (strcmp(s1, "ADDXYZ") = '1') then
            report "ADDXYZ " & s2 & " " & s3;
        end if;
    end loop;

end process;

end architecture;

How would I do this in VHDL?
so far i have a function for strcmp:
FUNCTION strcmp(s1: STRING; s2: STRING)    --string compare
    RETURN BOOLEAN IS
  BEGIN
    IF(s1'LENGTH /= s2'LENGTH) THEN
      RETURN FALSE;
    ELSE
      FOR i IN s1'RANGE LOOP
        IF(s1(i) /= s2(i)) THEN
          RETURN FALSE;
        END IF;
      END LOOP;
      RETURN TRUE;
    END IF;
  END;   --function strcmp

Comment: Your strcmp looks eerily like an overload for the equality operator implicitly declared for a type (here in std.standard, see IEEE Std 1076-2008 9.2.3 Relational operators, 16.3 Package STANDARD) You could use an alias instead. `alias strcmp is std.standard."=" [string, string return boolean];` You can then use strcmp as a function call using positional association e.g. `strcmp("string1", "string2")` (named association cannot be used for parameters of a predefined operator, 9.2 Operators, 9.2.1 General).
Comment: The -1987 standard shared 60 percent of it's text with the Ada83 LRM. Writing programs in VHDL for verification wasn't a goal. Abstract types based on enumeration with positional value are fine for formal proofs. VHDL was originally a library allowing Ada to be used as a programming language incidentally compatible with VHDL's strong typing and capable of sharing packages. HW and verification uses imperfectly overlapping subsets of HDLs of which none scale well in the face of Moore's Law or design complexity.
Comment: similar idea... https://rosettacode.org/wiki/Tokenize_a_string#Ada
Comment: I had to rewrite it anyways because it doesn't recognize zero-terminated strings in a fixed sized string buffer.  if only vhdl had direct mapping of c language functions to hdl functions like system verilog DPI.  As far as i know, it only supports the old FLI/PLI like interfaces with all the strange accesser functions to poke at the simulation data structure in memory.
Answer: library ieee;
use ieee.std_logic_1164.all;
use std.textio.all;

package pkg_fancy_strings is

    -- Max Line length to tokenize
    constant STRTOK_MAX : natural := 200;

    procedure line2string(L: inout line; S: out string);

    function is_space (c:character) return boolean;
    function is_nul   (c:character) return boolean;

    -- structure to maintain state between strtok calls
    type strtok_t is
    record
        str   : string(1 to STRTOK_MAX);  --input string
        pos   : natural;                  --input string iterator position
        more  : boolean;                  --call strtok_next until more equals false stop
        tok   : string(1 to STRTOK_MAX);  --token string value
        len   : natural;                  --token string length
        valid : boolean;                  --token string valid
        error : natural;                  --token string had an error, ex: truncation
    end record;

    -- return string of length n padded with nul if less than n originally
    function strpad(n: natural; x: string; rm_comment: boolean) return string;

    -- Initialize strtok structure with unparsed string
    function strtok_init(s : string) return strtok_t;

    -- tokenize string in strtok buffer
    function strtok_next(t: strtok_t) return strtok_t;

    -- compare strings
    function strcmpi(s1: string; s2: string)  return boolean;

    -- convert string into integer
    function str2integer(s: string) return integer;

end package;

package body pkg_fancy_strings is

    function is_space(c:character) return boolean is
    begin
        if (c = ' ') then
            return true;
        end if;

        if (c <= character'val(13)) then
           return true;
        end if;

        return false;
    end function;

    function is_nul(c:character) return boolean is
    begin
        if (c = character'val(0)) then
            return true;
        end if;

        return false;
    end function;

    procedure line2string(L: inout line; S: out string) is
        variable good  :boolean;
        variable ch    :character;
        variable str   :string(1 to STRTOK_MAX);
        variable i     :integer := 1;
        variable len   :integer := 0;
    begin

        -- Zero Line Buffer
        for i in 1 to str'length loop
            str(i) := character'val(0);
        end loop;

        len := 1;
        loop

            read(L, ch, good);
            if (good = false) then
                exit;
            end if;

            str(len) := ch;
            len      := len + 1;

            if (is_nul(ch)) then
               exit;
            end if;

            if (len > str'length-1) then
                exit;
            end if;

        end loop;

        S := str;

    end procedure;

    -- return string of length n padded with nul if less than n originally
    function strpad(n: natural; x: string; rm_comment: boolean)
        return string is
        variable r:    string(1 to n);
        variable stop: natural;
    begin
        for i in 1 to n loop
            r(i) := character'val(0);
        end loop;

        stop := x'length;
        if (stop >= n) then
          stop := n-1;
        end if;

        for i in 1 to stop loop
            -- ignore everything on line after '#'
            if (x(i) = '#') then
               exit;
            end if;
            r(i) := x(i);
        end loop;

        return r;
    end function;

    -- Initialize strtok structure with unparsed string
    function strtok_init(
        s : string
    ) return strtok_t is
        variable t  :strtok_t;
        variable i  :natural;
        variable ch :character;
    begin

        t.str   := strpad(STRTOK_MAX, s, true);
        t.pos   := 1;
        t.more  := true;
        t.valid := false;  --tok string not valid yet
        t.error := 0;
        return t;

    end function;

    -- tokenize string in strtok buffer
    function strtok_next(
        t: strtok_t
    ) return strtok_t is
        variable ch   :character := character'val(0);
        variable i    :natural   := 0;
        variable r    :strtok_t;

    begin
        r := t;

        -- Zero t.tok
        r.len := 0;
        for i in 1 to r.tok'length loop
            r.tok(i) := character'val(0);
        end loop;

        -- Eat Spaces
        loop
            if (r.pos > r.str'length-1) then
                r.valid    := false;
                r.more     := false;
                return r;
            end if;

            ch := r.str(r.pos);

            if (is_nul(ch) = true) then
                r.valid    := false;
                r.more     := false;
                return r;
            end if;

            if (is_space(ch) = false) then
               exit;
            else
               r.pos    := r.pos + 1;
            end if;
        end loop;

        -- Save Token
        i    := 1;
        loop
              if (i > r.tok'length-1) then
                r.valid    := true;
                r.more     := true;
                r.error    := 1;
                return r;
            end if;

            if ((r.pos > r.str'length) or is_nul(r.str(r.pos))) then
                r.valid    := (r.tok'length /= 0);
                r.more     := false;
                r.error    := 0;
                return r;
            end if;

            ch := r.str(r.pos);
            if (is_space(ch)) then
                r.valid    := true;
                r.more     := true;
                r.error    := 0;
                return r;
            else
               r.tok(i) := ch;
               r.len    := i;
               i        := i + 1;
               r.pos    := r.pos + 1;
            end if;
        end loop;

        -- shouldn't get here
        r.error    := 2;
        r.valid    := false;
        r.more     := false;
        return r;

    end function;

    --string compare
    function strcmpi(s1: string; s2: string)
        return boolean is
        variable max: natural := 0;
        variable end_s1:boolean;
        variable end_s2:boolean;
        variable nul_s1:boolean;
        variable nul_s2:boolean;
    begin
        if (s1'length >= s2'length) then  max := s1'length; else max := s2'length; end if;

        for i in 1 to max loop
            end_s1 := (i > s1'length);
            end_s2 := (i > s2'length);

            if (end_s1 and end_s2) then return true; end if;

            if (end_s1) then
                nul_s2 := (s2(i) = character'val(0));
                if (nul_s2) then return true; end if;
            end if;

            if (end_s2) then
                nul_s1 := (s1(i) = character'val(0));
                if (nul_s1) then return true; end if;
            end if;

            nul_s1 := (s1(i) = character'val(0));
            nul_s2 := (s2(i) = character'val(0));

            if (nul_s1 and nul_s2) then return true; end if;

            if(s1(i) /= s2(i)) then
              return false;
            end if;

        end loop;

        return true;
    end function;

    -- read next whitespace delimited string
    --     return string is terminated with null's
    procedure read_string(L: inout Line; s: out string(1 to 80);
                 good: out boolean) is
        variable c     :character;
        variable r     :string(1 to 80);
        variable i     :natural;
    begin
        r := (others => character'val(0));
        s := (others => character'val(0));

        -- Skip WhiteSpace
        loop
            read(L, c, good);
            report "c:" & character'image(c);
            if (good = False) then
                good := False;
                return;
            elsif ((c = ' ') or (c <= character'val(13)) ) then
                next;
            end if;
            exit;
        end loop;

        -- Read Until Non-Whitespace
        i    := 1;
        r(i) := c;
        i    := i+1;
        loop
            read(L, c, good);
            if (good = false) then
                s    := r;
                good := True;
                return;
            elsif ((c = ' ') or (c <= character'val(13)) ) then
                s := r;
                good := True;
                return;
            else
                r(i) := c;
                i    := i + 1;
            end if;
        end loop;

    end procedure;

end package body;

-- EXAMPLE OF FANCY STRINGS USAGE:
--
--    use work.pkg_fancy_strings.all;
--
--    entity tb is
--    end entity;
--
--    architecture rtl of tb is
--    begin
--        process
--          file      stim_in        :text open read_mode is "testcase1.txt";
--          variable  L              :line;
--          variable  sbuf           :string(1 to STRTOK_MAX);
--          variable  slen           :natural;
--          variable  t              :strtok_t;
--        begin
--            t := strtok_init("   mary had a little #lamb");
--            while(t.more) loop
--                t := strtok_next(t);
--                if (t.valid) then
--                    report ">>" & t.tok(1 to t.len) & "<<";
--                end if;
--            end loop;
--
--            report "done." severity failure;
--        end process;
--    end architecture;
--

Comment: Please explain your source code and/or add an origin and/or add copyright notes.
Comment: you are free to use it how ever you want...it only about 20 minutes to write this code from scratch...


In a software project, how would you differentiate a Component from a Module?

Question: In a software, how would you differentiate a Component from a Module?
Answer: I would say that the answer depends on who you ask.
I think of the difference as being one of granularity and role. A software component to my understanding is a self-contained entity with a well-defined (and preferrably stable) interface that interacts with the remaining parts of a system, and which has significant meaning from a system architecture point of view. An example would be a data access abstraction layer.
A module to me would rather be a deployable source code bundle containing code which shares a common purpose, but doesn't perform any significant role in the system (which means replacing it would not require changes to the system's overall architecture). An example would be a JSON serializer in a web service.
Answer: Generally speaking,

a component is a relatively finely
grained grouping of elements that
serve a particular service in the
solution.
a module is courser    grained and
acts as a grouping of one    or more
related services provided by    the
software.

A module will tend to make use of many componenents to provide its services whereas a component will likely to be constructed from a handful of classes and other components.
In any case its subjective and depends on the scale of the application.  For a small application there is likely to be a single program (a module) and a number of components.  In medium sized application there could be several modules and many components.  In a large application you might want to introduce the term sub-system which is even more courser grained than a module !
Comment: Interesting - in my experience the definitions are exactly the opposite.  Software development standards tend to use "module testing" interchangeably with "unit testing", for example.
Answer: Modules are the capabilities of giving the software new functionality.
Components are elements
Answer: Components are generally regarded as self-contained, pluggable items that follow some sort of software interface specification.  A good example is GUI items such as enhanced textboxes and dropdowns.  Basically anything that is not a complete program, but which can be plugged into another program to enhance its functionality.
The word Module has fallen out of favor in the past few years.  Module is a more generic term, but some languages have it as a keyword, i.e. Modula 2.  VB.NET has a Module keyword, but that is just an ordinary class with static members, and my understanding is that most VB programmers prefer to use the Class keyword.
Answer: Components are defined at software system level (as seen/thought at runtime). They are the elements of a executing system and together compose a larger system. These components/elements interact among themselves using connectors(interfaces). Imagine black boxes communicating among themselves, no care is given to their implementation/source code.
Module is defined at the programming language level (say, set of 5 classes comprise a module providing some functionality). They are defined at source code level as per the functionality provided by that collection of code. (example: persistence classes in your application responsible for interacting with the database).
Note that, module is also a type of component (going by categorisation and shares a "is-a" association with component).
Reference: Len Bass, Software arch. in practice and Dr. Timothy Lethbridge lecture
Answer: component: black-box module.
But there isn't any significant difference, really. Don't try to look for deep meaning here.
Answer: A component is a just another name for module, they are the same thing. Usually component is the term that you can find in a software engineering book whereas module has a more widespread usage.
Comment: That is not correct. Component and module are not exactly the same thing. Although, often incorrectly used interchangeably.


Laplace transformation problem

Question: There is a timely unchanged continuous function :
$$H(s)=\frac{s-1}{s+1}$$
At the entry of the system exists a $x(t)$ which Laplace's transformation is:
$$X(s)=\frac{(5s^2 - 15s + 7)}{(s-2)^3(s-1)}$$
Which is the impulse response?and which is the exit signal of the system?
Could someone show me the answers and elaborate me,on how this goes cause I have some clues but I am lacking i some aspects,Thanks in advance.
Comment: Welcome to math.SE! Please consider taking the time to read the [faq] to familiarise yourself with some of our common practices. In addition, [this page](http://meta.math.stackexchange.com/q/5020/8348) should give you a start at learning how to typeset mathematics here so that your posts say what you want them to, and also look good. As this question appears to be homework, please consider reading [this page](http://meta.math.stackexchange.com/q/1803/8348) for information about asking _effective_ homework-related questions. Cheers!
Comment: Check the edit. Are these the functions in consideration?
Comment: Thank you very much both for the help. @ Mhenni Benghorbal :thanks  nice edit,@ Daniel R : thanks for the links !!!
Comment: @Phil_Charly: You are welcome.
Comment: Do you want to find the inverse Laplace of the two functions?
Answer: Here is how you advance. Use partial fraction to get
$$H(s)=1-\frac{2}{1+s}$$
Taking the inverse Laplace gives
$$h(t)=\delta(t)-2e^{-t},$$
where $\delta(t)$ is the Dirac function. Note that, the Laplace transform of the functions $\delta(t)$ and $e^{-t}$ are $1$ and $\frac{1}{s+1}$. For the second one use partial fraction
$$X(s)= \frac{17}{\left( s-2 \right)^2} - \frac{17}{ \left( s-2 \right)} +\frac{17}{
 \left( s-1 \right)}-\frac{27}{ \left( s-2 \right)^3} .$$
Now, try to finish the problem.

Laplace transformation problem


Can I add method to a custom class of an HTMLElement

Question: My question is similar to this:
How to add my own methods to HTMLElement object?
Since the answer is 'NO', I'm wondering if I can add a method to the class instead of the HTMLElement itself, like:
<SELECT class="sel_region">

If possible, how to achieve it?
Comment: how would you invoke this function?
Comment: This is how I invoke it:

    $('.sel_region').doSomething();

Just don't know how to define it.
Answer: $('.sel_region') isn't a class. Assuming you're using jQuery, it's a collection of all the elements on the page that have the sel_region class. If you would like to be able to add a method to jQuery, this is the link for you:
http://api.jquery.com/jquery.fn.extend/
You could do something like:
jQuery.fn.extend({
  doSomething: function() {
    return this.each(function() {
      // Do something to the matching elements, which will be `this`
   });
});

$('.one-class').doSomething();
$('.another-class').doSomething();

Comment: @abacusit You're welcome. If you're satisfied with this answer click the tick next to it to accept it.
Answer: You, of course, could do this. You should loop all existing htmlElement instances with current class
$(".sel_region").each(function(index, element) {
  element.prototype.yourFunction = function() { console.log("exists!"); };
});

You should call this loop on Dom load


Dask meta for map_partitions dataframe

Question: I am trying to to use map_partitions with a custom function in Dask which I want to return a dataframe with a couple columns, but when I supply the metadata I receive the following error:
Exception: AttributeError("'DataFrame' object has no attribute 'name'")
If I specify meta as a series it works fine, but if I pass meta an empty dataframe I receive the above.
def mytest(self, df):
        return df['Bedrooms']

meta = ('Bedrooms', 'i8') #This works
meta = pd.DataFrame({'Bedrooms': pd.Series(dtype='i8')}) #This doesn't

bedrooms = df.map_partitions(self.mytest, weather_file_location, year, meta=meta)

The series solution was just for testing as I really need to work with a dataframe with multiple columns. I am not sure if I am just not creating the empty dataframe correctly or if there is another way to pass meta for a dataframe?
Comment: Hi and welcome on SO. It will be great if you can have a look at [how-to-ask](/help/how-to-ask) and then try to produce a [mcve](/help/mcve).
Answer: Doing some additional testing the problem seems to be passing a single column does not work, but multiple columns does.
meta = pd.DataFrame({'Bedrooms': pd.Series(dtype='i8', 'Lights': pd.Series(dtype='i8')})

Comment: I believe that a single column will come back as a Series, not a DataFrame.
Comment: Thanks! Yes that seems to be the case.

Dask meta for map_partitions dataframe