How to filter a view based on tags applied to

Question: I'm working on an old (2009) Drupal 6 site that uses a custom module to add a field to the content creation pages for certain node types. That field lists a sub-set of the users of a certain user type.
Some of those users are now being free-tagged on the site. I'd like to be able to create a view that lists only the nodes that refer to users that have a specific tag.
If that sounds a bit complicated, here's an example. Imagine a D6 site that works as an intranet for a doctor's surgery. Each doctor has a user account on the site, as does each patient. A custom module lets patients be allocated to doctors. After every appointment, the doctor fills in a report. That report is a node type, and includes a field created by a custom module that allows the doctor to select the patient who had the appointment, from a list of all of the patients who are allocated to that doctor.
Now, imagine that each patient's account could be free-tagged, and tags such as "male", "female", "diabetic", "pregnant", etc. were added to the patients' user accounts. How would I go about building a view that would display all of the reports given to patients who are tagged as "pregnant"?
Answer: So, shortly after posting this question I worked out how to do it.
When I built this site I included the facility to create a Views relationship that points at the "referred to" user (the "patient" in the above example). So, I created this relationship in the view that I built. I then created another relationship that was itself based on the first relationship but pointing at the node created by the Content Profile module.
Then, I created a filter based on the second relationship, that filtered based on the taxonomy term I'd created (i.e., the "diabetic", "pregnant" stuff above). That did the trick.


How to set custom url for facebook like button

Question: I have added Facebook like button on my web app.
Here the code on my html

I looked through stackoverflow and found that i can catch curent url for html by this code
string path = HttpContext.Current.Request.Url.AbsoluteUri;

And now I want to set this like button for my path value.
Smth like this

But it doesn't work.
I looked through stackover but didn't find any answers )
Answer: Try this
string path = HttpContext.Current.Request.Url.AbsoluteUri;

Comment: Thanks )
But I've understood how to do this ) I 've used '@'
Comment: i think if you using MVC3 or MVc4 , you can do that syntax ,


Simple powershell script using Get-ChildItem fails

Question: So I have a process that looks for specific files like below:
<code>@(Get-ChildItem -Path \\$Server\c$\temp\* where-object { $_.CreationTime.Date -match "2016" })
</code>
This worked just fine until I wanted to try and split my output up. I learned about "$OFS=" "" and wanted to use that (global powershell variable?) and changed it to $OFS="`r`n"..
Now when I run the command above, I receive an error:

Get-ChildItem : A positional parameter cannot be found that accepts argument ' $_.CreationTime.Date -match "2016" '.

I tried resetting it with $OFS=" " and that doesn't seem to help. I can't figure out what I've done to ruin my simple script. Sorry for the very noob question but I've been searching this for ages and cannot come up with an answer. Everything I find online seems to state that my powershell command should work
Answer: Your powershell command can't work. Get-ChildItem and Where-Object are different Cmdlets, try to pipe (|) the output from Get-ChildItem to Where-Object
<code>@(Get-ChildItem -Path \\$Server\c$\temp\* | where-object { $_.CreationTime.Date -match "2016" })
</code>
Comment: `$_.CreationTime.Year -eq 2016` avoids the conversion to string and the use of regex, and uhh .. the possibility for false positive matches should the script still be running after the year 20160 ;)
Comment: @TessellatingHeckler You beat me for the very same comment. (except the year 20160 :-)


Pairwise comparisons for a regression with sandwich estimates (in R)

Question: The question in short
I run a regression in R and made a boxplot of the response variable with grouping by one of the predictor variables. On this boxplot I'd like to add some information about the statistical model. What information (and how to display it (it is not an issue of programming)) would you suggest me to provide?

The developed question
I have several predictors: two categorical, non-ordinal predictors and one continuous predictor (below coded in R)
set.seed(81)
pred1 = rep(c('Car', 'Bike', 'Train', 'Airplane'), 6)
pred2 = rep(c('High', 'Low', 'Middle'), 8)
pred3 = rnorm(24)
resp = c(rnorm(12, sd = 1), rnorm(12, sd = 5))

resp is the response variable. I ran a regression with sandwich estimates:
require(sandwich)
require(lmtest)

m = aov(resp ~ pred1 + pred2)
coeftest(m, sandwich)

t test of coefficients:

            Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.49642    0.73911 -0.6716  0.51034
pred1Bike    1.55917    1.16568  1.3376  0.19769
pred1Car     1.23873    1.24080  0.9983  0.33135
pred1Train   2.50882    0.91468  2.7428  0.01338 *
pred2Low     0.11613    1.00540  0.1155  0.90932
pred2Middle  0.51476    0.90924  0.5661  0.57829
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

And I boxplotted the groups for pred1:
require(ggplot2)
ggplot(data.frame(pred1, resp), aes(x=pred1, y=resp)) + geom_boxplot()

On this plot I'd like to add some letters in order to indicate the groups which are statistically similar (p.value < 0.05) as discussed here. Something like this:
ggplot(data.frame(pred1, resp), aes(x=pred1, y=resp)) + geom_boxplot() + annotate('text', x=1:4, y=6, label=c('a','b','a','b'), size = 8, color='red')

My question is:
How can I find these p.values for the pairwise comparisons with my robust regression? I can do what follows where m is a simple aov model:
TukeyHSD(m)

But the following doesn't work:
TukeyHSD(coeftest(m, sandwich))

I might missunderstand what these pairwise comparisons are, and what the results I currently have mean! Please let me know if you feel this! The aim of my question is for me to understand what is the best way to display the results of my statistical model on a boxplot.
Note: the variables pred2 and pred3 are used to withdraw some part of variance that I don't want to be accounted to the effect of pred1 (as pred1, pred2and pred3 are correlated in my case). Therefore, I guess it is better not to run simple pairwise t-test in order to get the p.values I'd like to add at the top of each boxplot.
Comment: You cite code that "doesn't work". It's best not to complicate your question with such details if they don't matter, and in any case not to post questions about code here as they are off-topic for CV. The one answer to date regards you as asking for code. Wanting both general ideas and specific code is understandable, but you are sending a mixed message.
Comment: Please let me know if my question doesn't make much sense!
Comment: This seems confused. You talk about robust regression, but apply analysis of variance. Asking for sandwich standard errors is not everyone's idea of "robust regression". You have box plots and want to enhance them. But boxplots show medians and selected quantiles and are at best indirectly related to analysis of variance. I know that some advise this combination, but I don't understand why. I'd plot raw data in a real problem with any plot showing detail in the data (e.g. stripplots). You do seem to lurch between asking a general question and soliciting R advice.
Comment: @NickCox Thanks for your comment! Using the function `aov()` or `lm()` does not change anything as I later read the results with `coeftest()`. My question is not an issue with R programming. I am not asking for code lines. I'd like to have advice concerning how I should highlight with a graph (boxplot or other) the differences found on for the variable `pred1`. I thought about a boxplot but didn't know how I could add significant values (not a programming issue!) given that I have n-1 p.values for n groups.
Answer: One solution is actually given as an example in the book on the multcomp package, section 4.6:
Bretz, F., Hothorn, T., & Westfall, P. H. (2011). Multiple comparisons using R. Boca Raton, FL: CRC Press.
One only needs to slightly adapt your code (everything needs to be in one data.frame instead of floating around):
require(multcomp)
require(sandwich)

set.seed(81)
pred3 = rnorm(24)
df <- data.frame(pred1 = rep(c('Car', 'Bike', 'Train', 'Airplane'), 6), pred2 = rep(c('High', 'Low', 'Middle'), 8)
, resp = c(rnorm(12, sd = 1), rnorm(12, sd = 5)))

m <- aov(resp ~ pred1 + pred2, df)

tukey <- glht(m, linfct = mcp(pred1 = "Tukey") , vcov = sandwich)

summary(tukey, test = adjusted())

##          Simultaneous Tests for General Linear Hypotheses
##
## Multiple Comparisons of Means: Tukey Contrasts
##
##
## Fit: aov(formula = resp ~ pred1 + pred2, data = df)
##
## Linear Hypotheses:
##                       Estimate Std. Error t value Pr(>|t|)
## Bike - Airplane == 0     1.559      1.166    1.34    0.547
## Car - Airplane == 0      1.239      1.241    1.00    0.748
## Train - Airplane == 0    2.509      0.915    2.74    0.058 .
## Car - Bike == 0         -0.320      1.422   -0.23    0.996
## Train - Bike == 0        0.950      1.149    0.83    0.838
## Train - Car == 0         1.270      1.225    1.04    0.726
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## (Adjusted p values reported -- single-step method)

Note that glht as default uses the single-step method as adjustment for alpha-error accumulation. If you want something else, you need to feed it to adjusted()
For example, using the Bonferroni-Holm correction (which I tend to use as I don't understand what single-step actually does):
summary(tukey, test = adjusted("holm"))

If you want no alpha error correction, which I do not recommend, this is also possible:
summary(tukey , test = adjusted("none"))


Squeezing the juice from a large data set

Question: I may soon have temporary access to a large and interesting data set, where the data is sensitive and raises privacy and confidentiality concerns. Number of records in the low hundred thousands, number of variables in the mid-hundreds. I need to describe what I will do with the data, and provide assurances that I will not release anything that could identify any individual.
I have some particular questions that I want to answer, but boy, I sure wish I could take the data home and play with it for a year or three.
So I have been trying to figure out if there is some way to summarize the data that obscures all the observations and shrinks it a lot, but nonetheless lets me pose it new questions.
The best thing I have been able so come up with is to take all the variables, and their squares and logs (and a couple of lags of each, if they'll let me at them) and then, what? Regress each on all the rest, and take home the coefficients? Take the first four or five own & cross moments? Run all the 3-variable regressions? (My background is in economics, so I think every statistical question is a regression).
I am mainly a policy guy, and more a consumer of statistics then a generator of new statistical knowledge. I have not found a literature on this question, and don't know if one exists. But it seems to me that the opportunity to bring home, not just answers to my current focal questions, but also a summary rich enough that I could hand it to a colleague with a different question and s/he could answer it from the summary, is an opportunity I should seize if at all possible.
Comment: You might also want to talk to a lawyer about what constitutes as anonymised  data. A team of data-analysts and private detectives could in theory identify people uniquely based on very little data. If you want to remove enough data such that less than 1% of people could be identified by such a team, you need to remove a lot of data. My suggestion would be to explicitly propose how you anonymize the data and have them agree to that method. That saves you trouble if the method turns out to be imperfect
Comment: I would say your approach is backwards.  Don't take a data set and wonder what it says. Figure out what you want to know and then figure out how to get it from the data set.
Answer: Since you haven't described the exact fields which are privacy sensitive (which will be removed before you're allowed to "take home" the data), I'm assuming these would be fields such as names, addresses, phone nos, income or expenditure details, employers, etc.
If you'd prefer to fit a regression on interesting fields, then I would suggest storing the relative importance of independent variables is more useful than storing the coefficients as-is.
I suggest you could try these steps to generate additional "features" from this data:

Use last names to find concentration of demographic groups within the population, although keeping in mind it doesn't lead to your work being used for racial profiling (we all have to be sensitive about these things when working on data).
Use addresses to get the approximate geospatial location of each individual, and generate features indicating concentration of these. You could first perform suitable clustering to get members and center points of clusters, and then round off the geospatial coordinates so that they are at a more coarse level sufficient to only identify an individual's city/town/county and not their exact home location. If location is an important consideration, the other details such as climate of the location and topography may also be relevant details to include.
If income/expenditure is part of the dataset, then generate parameters for them such as identifying most suitable probability distribution an income fits, then mapping each records to get how many std. dev. it is away form mean (if normally distributed), etc. Also cluster it and add cluster centers and distance to center.
If employers are listed, then determine the nature of employer such as govt. sector, industry type, size, geographic location. All these details about a firm are available publicly.
If dates are part of the dataset, then you could identify the season and part of financial year, etc. from the date and retain those as new features.
If the data is time series, then you could determine auto-correlation, or, perform some causality tests based on your hypothesis.

You can think along these lines and check with the owners of the data to find out which features they would permit you to take away.
Answer: If you have all categorical data then you can make a table like this
<code>var1 var2 var3 N
0    0    0     2
1    0    0    10
1    1    0    15
1    1    1     2
0    1    0     0
0    1    1    10
0    0    1     7
</code>
This will allow you to exactly reconstruct the data for those three variables. You probably won't be able to make such a table for all variables in your dataset and you may have to coarsen some of the categories so you won't end up with too small frequencies which would violate confidentiality.
If you have all continuous data and are interested in linear models then a table of all the variances and bivariate covariances plus a table of the means is enough to estimate any linear model, including structural equation models.


nth root - sequence convergence proof

Question: I apologise for the ambiguous title. I found selecting an appropriate title difficult using only text.
If $0\leq \alpha \leq \beta$, define $\{a_n\}$ by $a_n = \sqrt[n]{\alpha ^n+\beta ^n}$. Prove that $\{a_n\}$ converges to $\beta$.
I'm quite lost on this one; any help getting started is appreciated.
Answer: $$\beta = \sqrt[n]{\beta ^n} \leq \sqrt[n]{\alpha ^n+\beta ^n}\leq \sqrt[n]{\beta^n+\beta ^n} = \sqrt[n]{2\beta ^n}= \sqrt[n]{2}\cdot \beta\xrightarrow{n\to\infty} \beta$$
Using the squeeze theorem, we get $\lim_{n\to\infty}\sqrt[n]{\alpha ^n+\beta ^n} = \beta$
Answer: write it as $$\beta\sqrt[n]{\left(\frac{\alpha}{\beta}\right)^n+1}$$
Answer: $\begin{array}
\ \lim_{n \to \infty} \sqrt[n]{\alpha^n+\beta^n} &=\lim_{n \to \infty} \beta \sqrt[n]{\left( \frac{\alpha}{\beta} \right) ^n +1} \\
&=\bigg( \lim_{n \to \infty} \beta \bigg) \cdot \bigg( \lim_{n \to \infty} \sqrt[n]{ \frac{\alpha^n}{\beta^n} +1} \bigg)\\
\end{array}$
Now apply the fact that $0 \leq \alpha \leq \beta$. What happens to $\frac{\alpha^n}{\beta^n}$ as $n\to\infty$?

nth root - sequence convergence proof


How to convert videos to ogg and mp4 and store in the database

Question: How can I convert a video to ogg and mp4 and automatically store it in the database?
E.g., if a user uploads an mp4 video, it will have to convert the video to ogg as well and store it in the database.
Can't find anything about this!
Thanks in advance!
Answer: Haven't tried this yet, but maybe it works ;)
This
Answer: Right now i don't think any automatic tool is there to convert ogg or any other format.
You can convert the mp4 to ogg format by using any free software or converter to do this job.
You can use Miro video converter
http://www.mirovideoconverter.com/
and BTW it's FREE and also very good for mobile device encoding.


How to enforce a constraint that a decision variable can only take 1 of $k$ integer values?

Question: How would you enforce the constraint that $x$, a decision variable, can only take values -3, 7, or 19?
I think I probably need to introduce a binary variable here but not sure where to start. Thanks.
Answer: Let $w,x,y,z \in \mathbb{Z}$ such that:
$x,y,z \in \{0,1\}$
$x+y+z=1$
$w=-3x+7y+19z$
Then $w$ will be exactly one out of $-3,7,19$.


Vector subspace of functions where $f'(x) = 2f(x)$

Question: I'm given $V = \{f(x) : R \rightarrow R : f'(x) = 2f(x), \forall x \in R\}$.
I know how to do the proof about closure in regards to addition. But I'm not sure how to write the proof regarding multiplication by scalar.
$(\lambda f')(x) = \lambda 2f(x)$
$\lambda 2f(x) = \lambda [2f(x)]$
This way?
Answer: $(\lambda\cdot f)' = \lambda \cdot f' = \lambda \cdot (2f) = 2 \cdot (\lambda\cdot f) \Rightarrow \lambda \cdot f \in V$
Comment: I was close, so I have to remember to look back at the eight axioms of vector spaces.
Comment: @0kelvin No, not the $8$ axioms of vector spaces, but the $3$ conditions for a subspace of a vector space.
Comment: @MarcvanLeeuwen I was referring to the fact that I have to look at the proofs, not to check for all 8 axioms one by one. I can see that I was missing the associativity and comutativity properties.


Prove: $n-1$ linearly independent equations define a one dimensional vector space in $\mathbb{R}^n$

Question: Prove: $n-1$ linearly independent equations define a one dimensional vector space in $\mathbb{R}^n$ .
Basically, I want to prove that given a set of  $n-1$ linearly independent equations in $\mathbb{R}^n$ and a set of points that adhere to those equations, that the set of points all have to be in the same one dimensional vector space in $\mathbb{R}^n$.
I want to solve this algebraically, and I think there just has to be a way to do this with the rank-nullity theorem but I can't really figure it out.
Any help would be appreciated.
Answer: Pretty lightly, $n-1$ linearly independent equations means the solution is a strict $x_1, x_2, x_3, ..., x_{n-1}$ values that solve the system, leaving $x_n$ as the free variable which has no affect on the solution..., defining the solution on a one-dimensional vector space.
In other words, expressing your system of equations in an augmented matrix of $Ax = \vec{b}$ means that the null space is $1$ dimensional (all linearly independent, except for $x_n$). Reducing this matrix will yield leading coefficients on $x_1, ..., x_2, x_3, x_3, x_{n-1}$ and define a 1 dimensional vector space solution after parametrized. The rank of the matrix is strictly $n-1$, so you'll be left with $1$ free variable that won't affect your solution. Using the rank-nullity theorem, then $im(A)$ has some solution set $x_1, x_2, ..., Ax = b$ and adding any linear combination of the remaining null space will not affect the solution...since $An = 0, n \in \text{null}(A)$.
Note that this is only true if indeed the system of equations is solvable...
Comment: Thanks for your answer. I just wanted to follow up: If I define a point in $\mathbb{R}^n$ by $n$ equations, is there a way to explain the fact that if 2 points share $n-1$ linearly independent equations, then they are both in the same one dimensional vector space?
Comment: I'm a bit confused from your question from "if 2 points share $n-1$ linearly independent equations". Do you mean if there are 2 points that satisfy the linear system, then they are both in the same one dimensional vector space?
Comment: Yeah. I don't see how you can use the nullity theorem to prove that directly.
Comment: ...If they're not in the same one dimensional vector space...then the first point will be in some one dimensional space that satisfies $Ax = b$ and the second one will be in another one dimensional space that satisfies $Ax' = b$...so any linear combination of the two solutions,  $\frac{1}{2}x + \frac{1}{2}x'$ is also a solution...which is two dimensional, x from the first space, x' from the second space..and this is a contradiction since we only required $1$ dimensional and asserted that there were $n - 1$ linear independent equations.
Comment: Thanks a lot for your help !


Rendering a Block Region in My Custom Theme

Question: I am having my custom theme. In the theme.info i have a region latest defined
regions[latest] = Latest

How do i print that region in my theme? Is the below code correct?
<?php print render($latest);?>

I tried dragging the Recent Posts block to this, but nothing appears. What am i doing wrong?
Answer: clear your theme cache to see your custom regions working: http://drupal.org/node/337176
Also see this link to review if something more is missing in your process: How-to create custom regions in a theme?


Syntax Error in Insert to statement for Delphi 10.2 Tokyo

Question: I need help with my coding, I have tried changing variables and displaying the SQL and I still can not see the error
Thank you.
Here is my code:
qryCustomerInformation.SQL.Add('/*The SQL query string from below*/');
showmessage(qryCustomerInformation.SQL.Text);
qryCustomerInformation.ExecSQL;

Here is my query string:
INSERT INTO BasicInformation (
    Passwords,
    CustomerID,
    Names,
    Surname,
    Age,
    IdentitiyNumber,
    Address,
    CardNumber,
    CSV,
    Expirey,
    Image,
    PhoneNumber
) VALUES (
    ''' + CustomerPassword +
    ''',''' + CustomerId +
    ''',''' + CustomerName +
    ''',''' + CustomerSurname +
    ''',''' + CustomerAge +
    ''',''' + CustomerIdNumber +
    ''',''' + CustomerAddress +
    ''',''' + CustomerCardNumber +
    ''',''' + CustomerCSV +
    ''',''' + CustomerExpirey +
    ''',''' + CustomerImage +
    ''',''' + CurstomerPhoneNumber
+ ''')

Comment: Gah. Use parameters. Avoid quoting issues and defend from SQL injection.
Comment: If any of the variables have a single quotation mark in them, you're going to retrieve a syntax error if you have not escaped the variables and it will break your query string. Due to the fact that you've provided very little information on this, it is hard to tell what your issue is.
Comment: A screenshot like the one you have provided is absolutely no use for getting help here.  Please copy/paste the text of your Sql into into your question.  Meanwhile, -1
Comment: Using parameters also makes dealing with date/time types much easier. Be lazy, make your own life easier, use params. That's what they are there for.
Answer: Part of the reason that you are having problems is that your SQL is syntactically
unnecessarily complicated.  Assuming CustomerPassword, etc are all string variables,
you can simplify your Sql as follows:
var InsertSql : String;

begin
  [...]
  InsertSql :=
  'INSERT INTO BasicInformation ('
   + '    Passwords, '
   + '    CustomerID, '
   + '    Names, '
   + '    Surname, '
   + '    Age, '
   + '    IdentitiyNumber, '
   + '    Address, '
   + '    CardNumber, '
   + '    CSV, '
   + '    Expirey, '
   + '    Image, '
   + '    PhoneNumber'
   + ')'
   + ' VALUES ('
   + QuotedStr(CustomerPassword) + ', '
   [... etc]
   + QuotedStr(CurstomerPhoneNumber) + ')'
   ;

   qryCustomerInformation.SQL.Add(InsertSql);

I have added the InsertSql local variable to avoid constructing the Sql within
the call to qryCustomerInformation.SQL.Add(), because that frequently results in errors itself.
The code above uses QuotedStr around the values of the string variables.  It not only supplies the necessaryu surrounding quotes but also correctl handles the case where the variable's value includes embedded single-quote marks.
However, as David Heffernan says, it is better to use a parameterised query,
for which you need to add a parameter to qryCustomerInformation for each value
in the Values clause, and modify the InsertSql so that it refers to each of them
instead of the original string value, like so
   + ' VALUES ('
   + ':CustomerPassword, '
   etc.

qryCustomerInformation will automatically substitute the parameter values for the labels prceded by colons.
Btw, your code contains a number of spellings which look suspicious to me:
Expirey
CustomerExpirey
CurstomerPhoneNumber
Comment: Martyn Although I also strongly agree that he should switch to parameters to prevent SQL injections, in your first solution you are forgetting to quote the values. You should replace CustomerPassword by QuotedStr(CustomerPassword), and repeat that for every other value.
Comment: Indeed.  Thanks very much for spotting @MarcGuillot!


xcode 8 PHPhotoLibrary.requestAuthorization causing crash

Question: My app keeps crashing when running in the simulator everytime I try to request authorization for the photo library.  I am using the following code in my appDelegate in didFinishLaunchingWithOptions:
if PHPhotoLibrary.authorizationStatus() != PHAuthorizationStatus.authorized {
     PHPhotoLibrary.requestAuthorization({ (status: PHAuthorizationStatus) in

     })
}

Using xcode 8 beta with swift 3.0.
Answer: In my testing, iOS 10 doesn't like to output useful error messages unless you're running on an actual device. In this particular case, you probably haven't provided the key NSPhotoLibraryUsageDescription in your Info.plist file, and that value must be provided before requesting authorization.
Comment: Do those steps you said, then enter some text in the box to the right: "We need to read your photos so that we can grok some glerbs." This will be shown to the user to explain why you want access, and it's standard procedure in iOS. [I'm writing a book on iOS 10 right now](https://gumroad.com/l/ios10) and the first chapter covers exactly this procedure.
Comment: Thanks for your reply. I haven't spent too much time modifying my plist file.  Is it as simple as pressing the plus and manually typing NSPhotoLibraryUsageDescription and selecting the type to String?.  Also will this cause issues going forward?  I thought that that property was a system property and could not be modified within an app other than by system alert acceptance.
Comment: That's great.  Works perfectly.  Thanks very much for your help.
Comment: Meanwhile I compile this, I would like to say thank you because I know this will solve my issue as well. Edit:  It did!
Comment: Any way to localize the value?
Answer: Have to allow access to photos on device. Add below key and string to your info.plist. The autocomplete in the property list view is "Privacy - Photo Library Usage Description". Or just open your info.plist in source code view and add the following:
<key>NSPhotoLibraryUsageDescription</key>
<string>We need access to your photos.</string>


drupal 6 to 7 site upgrade using drush_sup - how to download compatible drupal 7 modules

Question: I used drush_sup to upgrade my drupal 6 to 7 site. everything went smooth except the drupal 7 modules were not downloaded to the upgraded website.
During the upgrade process it did list the installed D6 modules, and the recommended D7 counterparts. I'm not sure what caused it to skip downloading it or maybe it just doesn't?
Thanks, any help appreciated.
Answer: I would run through the site upgrade process with the --prompt-all flag set to see if anything strange appears.
drush drush_sup will upgrade core and find good candidates for contrib modules, I think it'll even accept dev releases, but with a warning.
You could also pass in --auto to the command which will just do the defaults.
Source: http://drupalcode.org/project/drush_sup.git/blob/refs/heads/7.x-2.x:/README.txt


While loop in C - read untiL sentinel variations

Question: I am learning C and I would like to know if there is any difference or one way is better than the other between these two while loop variations. Should I use one instead of the other? Maybe one of those variations is wrong?
<code> while(car_num<=car_limit)
    {
     car_num = ceil(car_num*(1+rate));
     year++;
    }
</code>
OR
<code>while(TRUE)  { if(car_num>car_limit)
                break;
     car_num = ceil(car_num*(1+rate));
     year++; }
</code>
Thank you.
Answer: The first one is better because easier to understand. In general, avoid while(true).


Why isn't $\frac{\mathrm{d} }{\mathrm{d} x} \ln(x)$ specified as $\frac{1}{x},x>0$?

Question: As I understand, $\begin{eqnarray} \frac{\mathrm{d}}{\mathrm{d}x}\ln(x)\end{eqnarray} $ is generally specified as $\begin{eqnarray} \frac{1}{x} \end{eqnarray}$.  Would it be more appropriate to state it as $\begin{eqnarray} \frac{1}{x}, x>0\end{eqnarray}$ since $\ln(x)$ is undefined for $x\leq0$?  If not, why not?  In addition, what does this imply about the indefinite integral of or the definite integral with negative limits of integration of $\begin{eqnarray} \frac{1}{x} \end{eqnarray}$?
Thank you!
Comment: If $0 \lt a \le b$ then by symmetry $\int_{-b}^{-a} \frac{1}{x} \mathrm{d}x = -\int_{a}^{b} \frac{1}{x} \mathrm{d}x = \log_e(a)-\log_e(b)$
Answer: Whenever we write something like $\ln(x)$, we are implicitly asserting that $x$ is restricted to those $x$s for which the expression makes sense.
When we write $$\frac{d}{dx}\ln(x) = \frac{1}{x}$$ we are then implicitly and automatically saying that $x$ is positive for the equation to make sense. As for integrals, that's why $$\int\frac{1}{x}\,dx = \ln|x|+C,$$
with the absolute values: note that
$$\frac{d}{dx}\ln(-x) = \frac{1}{-x}(-x)' = \frac{1}{x}$$
as well by the Chain Rule, so that
$$\frac{d}{dx}\ln|x| = \frac{1}{x}.$$
For a definite integral to make sense, you usually need the function defined on the entire interval of integration (at least, for the usual Riemann integrals), so $\int_a^b\frac{1}{x}\,dx$ cannot have $a\lt 0 \lt b$ and make sense. Either $0\lt a\lt b$ or $a\lt b\lt 0$.
You can try to do an integral $\int_a^b \frac{1}{x}\,dx$ with $a\lt 0\lt b$ as an improper integral, but you will find that the integral does not converge; neither do $\int_0^b\frac{1}{x}\,dx$ nor $\int_a^0\frac{1}{x}\,dx$.
Answer: Another answer.  Some strange people use complex numbers, not just real numbers.  For them, log(x) makes sense other than for $x>0$.  And for them its derivative is $1/x$.  More importantly: for them, $\int (1/x)\,dx = \log(|x|)+C$ is WRONG!
Comment: Yes: mathematicians are strange people.


Combinatorics-how many ways to sort books on a shelf

Question: There are 2n+1 identical books to be put in a bookcase with three shelves. In how many ways can this be done if each pair of shelves together contains more books than the other shelf?
x1 = number of books on shelf 1,
x2 = number of books on shelf 2,
x3 = number of books on shelf 3
I have the following inequalities:
a+b > c
a+b+c > 2c (don't understand where this one comes from)
2n+1 > 2c
c < n+ (1/2)
c is an integer, so c =< n. Same for a, and b.
=> a+b+c = 2n+1, where 0 =< a, b, c =< n
At this point, I don't know how to finish the computation of the number of integral solutions. The answer is (n+1) choose (2).
I would have thought that r = 2n+1, and k = 3, so the answer would have been: (2n+3) choose (2).
Comment: $a+b+c\gt 2c$ comes from adding $c$ to each side of $a+b \gt c$
Answer: "each pair of shelves together contains more books than the other shelf" is equivalent to "each shelf holds less than half the books" (at most $n$ books). Let $\{s_i\}_{i=1}^3$ be the number of books on each shelf. For each choice of $s_1$ and $s_2$ so that $s_1+s_2<n+1$, we would need $s_3>n$.  For each $s_1+s_2\ge n+1$, we have $s_3=2n+1-(s_1+s_2)\le n$.  Thus, we need to count the number of $s_1,s_2\le n$ so that $s_1+s_2\ge n+1$. For $s_1=1$, there is $1$ choice for $s_2$ (i.e. $n$).  For $s_1=2$, there are $2$ choices (i.e. $n$ and $n-1$). This continues up to $s_1=n$, where there are $n$ choices for $s_2$.  Therefore, the number of arrangements is $1+2+\dots+n=\binom{n+1}{2}$.
Comment: So the answer is not n+1 choose 2?
Comment: @Gbean $\binom{n+1}{2}$ stands for $n+1$ choose 2. See binomial coefficient wikipedia [article](http://en.wikipedia.org/wiki/Binomial_coefficient).
Answer: A more natural and shorter approach that uses only the lower bounds for the equation
$$a+b+c = 2n+1$$
is next:
You can count all of the solutions to the equation when there is no restriction and then, using the subtraction principle, remove those solutions when there's a shelf with more than $n$ books on it(this would mean that the other two shelves have $\leq n$ books on them).
The equation when there are more than $n$ books on shelf $a$ is
$$a + b + c = 2n + 1, \\a \geq n + 1,\: b \geq 0,\: c \geq 0\: .$$
The number of solutions to this equation is $\dbinom{n + 2}{2}$.
But, one must notice that this number only counts the situation when there are more books on shelf $a$, in order to account for the other shelves the number should be multiplied by 3.
The final solution is
$$\dbinom{2n+3}{2} - 3\dbinom{n + 2}{2} = \dbinom{n + 1}{2}$$
Answer: a+b+c>2c comes from multiplying the previous inequality by 2.
There are (n+1)choose(2) combinations of a,b because 0<=a,b<=n. For each of these possibilities there is exactly one 0<=c<=n such that a+b+c=2n+1.
Comment: Suppose $a=0$ and $b=0$, what would $c$ be?
Comment: Does that mean that c = 2n+1?
Comment: @Gbean: it would need to be, but that is too big for $c$.
Comment: How is it too big for c?
Comment: @Gbean: "each pair of shelves together contains more books than the other shelf". If $c=2n+1$ and $a=0$ and $b=0$ we have $a+b\le c$ instead of $a+b>c$ as the problem requires.


display flex breaking mulitline text box

Question: I had been working on this for some days and reading information about display flex, but I'm still having an issue that I can't fix. I have 3 boxes and they have % width and some px separating each others, something like this
[[first box] [second box] [third box]]

so, to do this I used the nth-of-type(3n+2) in order to get all the middle elements and addind the px separation to both sides
each box has two divs, an image(to the left) and a text, but, when the text has at least two lines, the box get missaligned
[[first box] [second box]
                          [third box]]

and that's not good. So, playing with the styles if I remove the display:flex and the box were aligned, but the text now is not vertical aligned to the middle -.-

.general-cont {
  width: 100%;
  text-align: center;
}

.each-cont {
  width: 32.5%;
  display: inline-block;
  margin-top: 6px;
}

.each-cont:nth-of-type(3n+2) {
  margin-left: 10px;
  margin-right: 10px;
}

.img-cont {
  float: left;
  height: 48px;
  display: flex;
  align-items: center;
}

.text-cont {
  height: 48px;
  overflow: hidden;
  align-items: center;
  text-align: left;
  display: flex;
}

        123

        456

        ABC

        DEF

        QWE

        ASD

Comment: Razia thanks for that resourc @DaniP yeah, I cleaned the code and now is working fine! thanks
Comment: Please check this link:-https://css-tricks.com/snippets/css/a-guide-to-flexbox/
Comment: You have inline-block elements with margins and inside floated elements and inside flex elements ... that is a little messy go with just flexbox
Answer: You're code is a bit of everything. You shouldn't be combining widths, floats etc when you're using flex. Here's a quick example using your code:
.general-cont {
  display: flex;
  flex-direction: row;
  flex-flow: center;
  align-items: stretch;
}

.each-cont {
  background: #eee;
  margin: 0 10px;
  padding: 10px;
}

.img-cont {
  display: block;
}

http://codepen.io/paulcredmond/pen/rrRvkk
I would advise reading the guide on CSS tricks: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
Comment: Thanks for the answer, I cleaned my code and used display: flex + flex-wrap: wrap at parent and then style as usual and works!
Comment: Great! Sometimes with CSS it's best to keep things as simple as possible :)


Covering Space of Circle

Question: It is easy to see that
$p:\mathbb{R} \rightarrow S^1: p(t)=(\cos t, \sin t)$ is a covering map of $S^1$
(Indeed take a point $x_0$ in $S^1$, take $U=S^1\setminus \{-x_0\}$ as an open neighborhood and then $p^{-1}(U)=\cup_{n \in Z} J_n$ where $J_n=\{t\in\mathbb{R} : t_0-n-1/2<t<t+0+n+1/2\}$. $p$ then maps $J_n$ homeomorphically onto $U$.)
I can't see why we can't take a similar $p:(a,b) \to S^1$. For example, Massey states that if we take the open interval $(0,10)$ onto the circle, then some points in $S^1$ fail to have an elementary neighborhood.
Comment: Think about what the preimage of a neighborhood of p(a) looks like.
Comment: You appear to be confusing covering maps with local homeomorphisms. They are not the same. http://en.wikipedia.org/wiki/Local_homeomorphism
Comment: @George: this is exactly what Massey is showing - that they are not the same
Comment: Does Massey really say "a similar map" or rather "the same map"?
Comment: @Agusti - Neither - that was all me
Answer: Look at a preimage of a small neighborhood $U$ of $p(10)$. It will have one component which doesn't map homeomorphically onto $U$.

Covering Space of Circle


Extend generic type in abstract class property definition

Question: We have multiple pages with data grids, sharing basic functionality -> paging, sorting, export. In order to simplify them and speed up the development, I want to create the BaseGrid abstract component, which will provide the above mentioned functionality.
Now, in order to handle export, we have checkbox in every row. To avoid using SelectionModels (like from Angular CDK) or any other helper arrays, I want to extend data grid DTO with simple boolean property isSelected. Then we can handle selection just with [(ngModel)] and three short functions.
Is there a way to do so in Abstract Class when specifying the type of the data property?
// Whatever kind of DataDTO the BaseGrid gets, I want to extend it with isSelected property
interface DATA_EXPORT_EXTENDER {
  isSelected: boolean;
}

@Directive()
export abstract class BaseGridComponent<T> implements OnDestroy {
  // Grid DTO provided as a Generic
  data: Array<DATA_EXPORT_EXTENDER extends T> = [];
  /*
    SHOWS FOLLOWING ERROR:

    Parsing error: '?' expected.eslint
    Public property 'data' of exported class has or is using private name ''.ts(4031)
    interface DATA_EXPORT_EXTENDER
  */
}

I wasn't expecting this to work and of course, it's not working. But is there actually a way to do something like that? I had to resort to data: Array<any> = [];, othwerwise while looping, data.isSelected throws an error: does not exists on type T.
Answer: How about using the intersection operator (&) ?
// Whatever kind of DataDTO the BaseGrid gets, I want to extend it with isSelected property
interface DATA_EXPORT_EXTENDER {
  isSelected?: boolean; // changed here
}

@Directive()
export abstract class BaseGridComponent<T> implements OnDestroy {
  // Grid DTO provided as a Generic
  data: Array<DATA_EXPORT_EXTENDER & T> = [];    // changed here
  // or
  // data: Array<{ isSelected?: boolean; } & T> = [];
}

Also shouldn't the data be accessed as.
this.data[0].isSelected

Comment: Thanks, I wasn't aware of such approach. And I fixed the typo, should be `data.isSelected`. It's used while looping the array


How to read Cook's distance plots?

Question: Does anyone know how to work out whether points 7, 16 and 29 are influential points or not?
I read somewhere that because Cook's distance is lower than 1, they are not. Am, I right?
Comment: One might argue that it increases "Type III" errors as well, which (generically and informally) are errors related to inapplicability of the underlying probability model.
Comment: There are various opinions.  Some of them relate to the number of observations or to the number of parameters.  These are sketched at http://en.wikipedia.org/wiki/Cook%27s_distance#Detecting_highly_influential_observations.
Comment: @whuber Thanks. This is always a grey area when performing data exploration for me. Data point 16 above massively influences model outcomes, thus increasing Type I errors.
Comment: @whuber yes, very true!
Answer: Some texts tell you that points for which Cook's distance is higher than 1 are to be considered as influential. Other texts give you a threshold of $4/N$ or $4/(N - k - 1)$, where $N$ is the number of observations and $k$ the number of explanatory variables. In your case the latter formula should yield a threshold around 0.1 .
John Fox (1), in his booklet on regression diagnostics is rather cautious when it comes to giving numerical thresholds. He advises the use of graphics and to examine in closer details the points with "values of D that are substantially larger than the rest". According to Fox, thresholds should just be used to enhance graphical displays.
In your case the observations 7 and 16 could be considered as influential. Well, I would at least have a closer look at them. The observation 29 is not substantially different from a couple of other observations.

(1) Fox, John. (1991). Regression Diagnostics: An Introduction. Sage Publications.
Comment: +1 Clear summary.  I would add that influential cases are not usually a problem when their removal from the dataset would leave the parameter estimates essentially unchanged: the ones we worry about are those whose presence really *does* change the results.
Comment: @lejohn Very appreciative of your response. Whuber is right excellent clarity in your answer. This is very informative. Might I suggest you highlight Fox's and your opinions in the wikipedia page!
Answer: +1 to both @lejohn and @whuber.  I wanted to expand a little on @whuber's comment.  Cook's distance can be contrasted with dfbeta.  Cook's distance refers to how far, on average, predicted y-values will move if the observation in question is dropped from the data set.  dfbeta refers to how much a parameter estimate changes if the observation in question is dropped from the data set.  Note that with $k$ covariates, there will be $k+1$ dfbetas (the intercept, $\beta_0$, and 1 $\beta$ for each covariate).  Cook's distance is presumably more important to you if you are doing predictive modeling, whereas dfbeta is more important in explanatory modeling.
There is one other point worth making here.  In observational research, it is often difficult to sample uniformly across the predictor space, and you might have just a few points in a given area.  Such points can diverge from the rest.  Having a few, distinct cases can be discomfiting, but merit considerable thought before being relegated outliers.  There may legitimately be an interaction amongst the predictors, or the system may shift to behave differently when predictor values become extreme.  In addition, they may be able to help you untangle the effects of colinear predictors.  Influential points could be a blessing in disguise.
Comment: +1 "Cook's distance is presumably more important to you if you are doing predictive modeling, whereas dfbeta is more important in explanatory modeling": this is very useful advice.
Comment: Gung great answer! But can you possibly elaborate on why you think: *"Cook's distance is presumably more important to you if you are doing **predictive modeling**, whereas dfbeta is more important in **explanatory modeling**."*? I thought to do predictive work, having robust coeffiecients is very important, no?
Comment: Hi - interesting discussion. But couldn't it be rational to integrate a dummy-variable to measure the effect from for example observation 16?
Comment: @Pantera I removed 16 and compared the pre & post ommission models
Comment: Hi - if you remove observations, you should make sure that you have "good" argument to do it, for example that the observation is wrongly measured. If we throw out observation because they just make some statistical trouble, then we're close to data-mining.
Comment: Seems reasonable, @rnorouzian, but predictive modeling is about getting predicted values ($\hat{y}$s). So if the coefficients weren't robust, but it didn't have an appreciable impact on the predicted values, it wouldn't matter. In practice, both will have similar information, but will be framed in terms of what you care about.
Comment: @rnorouzian, it isn't really appropriate to have these conversations in comments under an answer.  I didn't say "with an appreciable impact", I said without, & I said "if". Note the last sentence of my prior comment.

How to read Cook's distance plots?


HTML email Android Outlook app text having weird justification issues

Question: I have one set of text in my html email that Outlook on Android does not like and sets the justification to justify even with text-align:left !important;. Every other client I've tested seems to work just fine.
sorry for the censorship

                              Session #:

                              1234

                              Session Title:

                              Session title is long and is weirdly justified.

                              Room:

                              123

                              Date and Time:

                                            Tue, Feb 00, 2017 at 11:15 AM – 12:15 PM

Answer: The justification can be part of the CSS in the header for the mobile version.
I can think of two things that could be affecting this:

CSS in the header targeting specific paragraphs or defined as global.
word spacing can also affect the spacing.

Since i cant see the full code its hard to tell where is happening.
Cheers


Can you list all direct search methods to estimate parameters?

Question: Direct search methods (also called derivative-free) are function minimization techniques that do not rely on a function's gradient to find the minimum. More importantly, they can be used to solve non-smooth optimization problems, which can be then used in parameter estimation (e.g., xxx).
As nearly every statistician will recognize, the most commonly used method is the Nelder-Mead, 1965 (see here for a description).
The optim function in R implements the Nelder-Mead method.
Here, I'd like to create a complete list (with strengths and defects) of other approaches and how to use them. Can you help?
Comment: Typically, shopping-list questions are frowned upon, so I wouldn't be surprised if this gets closed.
Answer: I'll recommend the survey paper
Tamara G. Kolda, Robert Michael Lewis, and Virginia Torczon.  Optimization by direct search: new perspectives on some classical and modern methods
and this book:
Andrew R. Conn, Katya Scheinberg, and Luis N. Vicente.  Introduction to Derivative-Free Optimization
Comment: Nelder-Mead simplex method, as derivative-free, was adviced somewhere[do't have link] as preferable in comparison with GrigSearchCV... didn't try it yet... but thanks for the link
Answer: Hyperparameter search uses a very wide variety of optimization methods. In my opinion, Nelder-Mead is often a poor choice because hyperparameter response surfaces are usually not smooth with tons of local optima. In my experience, Nelder-Mead almost always gets stuck in poor local optima (in the context of optimizing hyperparameters for machine learning methods, so ymmv).
Common methods include:

Nelder-Mead
particle swarm optimization
genetic algorithms
harmonic search
racing algorithms
EGO
Bayesian optimization
...

Many of the metaheuristic methods mentioned above are offered in Optunity, while several other packages offer Bayesian optimization (e.g. Hyperopt, SMAC and BayesOpt).


Reading special characters from .txt file - PHP

Question: I'm trying to output the content of a .txt file on a webpage using php/AJAX, which works fine for .txt files with no special characters in it. But when the .txt file contains characters such as accents on letters - è, for example, the AJAX request for the contents of the file returns null.
I think the problem originates from copying and pasting the content of the .txt file from a word document, as per a test I ran.
If you copy, for example, an apostrophe from a word document and paste it into a .txt via notepad, it appears differently to how it would if the apostrophe was typed directly into the notepad .txt file.
My client currently uploads .txt files to a certain folder on his server, and creates his content by copying and pasting from word. Is there a way around this, so that these 'copied and pasted' special characters can be read?
Example of formatting difference:
copied from word - Dave's
typed directly - Dave's
You see the difference in the apostrophe?
Comment: are you saving the file in notepad as UTF8 or ANSI ?
Comment: You'll want to look for solutions to "straightening quotes" in either your php or your javascript.
Answer: Can do htmlspecialchars() on the variable that contains the text file before echoing?
That should convert any special characters into HTML entities and should be view able on a webpage.
Answer: ok))
  1. do not use notepad, ever
  2. save all the files with the utf8 encoding

that's it, problem solved
Answer: These are called Smart Quotes. You can change them in Word options by following the guide located here. This would be the best option as it defines your intended output at the source. If this is not an option, i.e. there are thousands of Word files at a time, then post-processing is the way to go. This can be accomplished by looking up the HTML Entity for the characters and using a find-and-replace function. I suggest using PHP to open the text file using the str_replace() function to find and replace all occurrences of unwanted/undisplayable characters, which themselves could be defined in array or the like.


Where is root directory in Drupal Acquia Desktop?

Question: With other systems it's www or htdocs, but what about with Acquia Desktop?
Answer: Acquia desktop allows you to use any folder you wish as your root folder hence your site could be on the desktop, or documents. Use the import new site option in the settings tab to point to where drupal folder is located
Answer: It depends on your system; on Macs, it's in home/Sites/acquia-drupal.
To see where the files are for a site:

Open dev desktop.
Click settings.
Click the Sites tab.
Highlight the site you want to check and click Edit.
The site path will be displayed.
Comment: Thanks guys, for other newbies out there I made a screen capture.     http://www.vincentmoving.com/aquia-path.html


VBA error 1004 and source file become read only

Question: I am trying to read two pages ("SYN" and "STR") of an excel file into two different arrays.
the code is very simple, and it works just fine if i only need one page :
Sub recap()
Dim wb As Workbook
Dim fpath As String
fpath = Application.ActiveProject.Path & "\Suivi d'études.xlsm"
'(this is the file I want to read in the same folder)

Set wb = Workbooks.Open(fpath, True, False)

Dim rng1 As Range
Dim i, j As Integer

i = wb.Worksheets("STR").UsedRange.Rows.Count
j = wb.Worksheets("STR").Columns.Count

Set rng1 = wb.Worksheets("STR").Range(Cells(1, 1), Cells(i, j))

Dim data2(), data1() As Variant
data1() = rng1

wb.Close

Debug.Print (data1(10, 10))

End Sub

it works just fine.
Then I intergrated the seconde page.
Sub recap()

Dim wb As Workbook   'Need Microsoft Excel 16.0 Object Library
Dim fpath As String
fpath = Application.ActiveProject.Path & "\Suivi d'études.xlsm"

Set wb = Workbooks.Open(fpath, True, False)

Dim rng1, rng2 As Range
Dim i, j, a, b As Integer

a = wb.Worksheets("SYN").UsedRange.Rows.Count
b = wb.Worksheets("SYN").Columns.Count

i = wb.Worksheets("STR").UsedRange.Rows.Count
j = wb.Worksheets("STR").Columns.Count

Set rng1 = wb.Worksheets("SYN").Range(Cells(1, 1), Cells(a, b))
Set rng2 = wb.Worksheets("STR").Range(Cells(1, 1), Cells(i, j))

Dim data2(), data1() As Variant
data1() = rng1
data2() = rng2
wb.Close
Debug.Print (data2(10, 10))
End Sub

Not only it gaves me 1004 error on the range setting line: set rng1 = blablabla, but also since the code is not fully executed, the input excel file is still "open" in the code, it became a read-only file.
So my questions are:
1. which could cause this error, why can't they read the seconde page in an array?
2. how to force the input file to "close" if wb.close was not executed?
Comment: you need to qualify your `Cells` references too using your `wb` object, as they are referring to the `ActiveSheet` without a qualifier. Your first example must work because your `wb` is the `ActiveSheet` - those should be qualified too or they too will be prone to error.
Comment: Welcome to SO. You need to define your variables properly. When you do `Dim rng1, rng2 As Range`, only `rng2` is being defined as `Range`. Variable `rng1` is being defined as `Variant`, so Excel thinks you are trying to take into an array when you do `Set rng1 = wb.Worksheets("SYN").Range(Cells(1, 1), Cells(a, b))` and `Set` is not for variables, only for objects. Try `Dim rng1 as Range, rng2 As Range`
Comment: As braX said you need to use explicit references to the `cells` like so `wb.Worksheets("SYN").cells()`. Also when you declare multiple variables in a single line you have to do it like `Dim rng1 as Range, rng2 As Range`, otherwise only the last one is declared correctly and the rest are declared as variants.
Comment: Thanks guys.   oh, god, I've been using the wrong way to define my variables since one year. @FoxfireAndBurnsAndBurns.
Comment: @ShengweiLi Nice! I'll post it as answer then
Answer: The problem here is how you define your variables. In your first code you did:
Dim rng1 As Range
'
'
'
Set rng1 = wb.Worksheets("STR").Range(Cells(1, 1), Cells(i, j))

Because rng1 has been created as a Range Object, yes, you need to set it up with Set.
In your second code you did:
Dim rng1, rng2 As Range
'
'
'
'
Set rng1 = wb.Worksheets("SYN").Range(Cells(1, 1), Cells(a, b))
Set rng2 = wb.Worksheets("STR").Range(Cells(1, 1), Cells(i, j))

Notice that only rng2 is being defined as a Range Object. Variable rng1 is being defined as Variant, the default option in VBA when you don't specify a type.
So VBA thinks rng1 is a Variant and then later on you do:
Set rng1 = wb.Worksheets("SYN").Range(Cells(1, 1), Cells(a, b))

And that raises an error because Set must be used only with objects.
VBA, because rng1 has been defined as Variant, was expecting a line like:
rng1 = wb.Worksheets("SYN").Range(Cells(1, 1), Cells(a, b))
This means you are taking all those values in that range into a bidimensional array named rng1. You don't want to do this, but this explains why VBA raises that error.
The solution is really easy. Just define always what type of variables/objects you are using.
Line Dim rng1 as Range, rng2 As Range should fix your problem. Always declare properly all your variables.
Hope this helps.


How can I view data after fetching the data on the console log in api?

Question: I'm starting to learn reactjs and I want to view the data on the table after I input text on the input fields and show the data on a console log. How can I show all the data input to the page?

onAdd(employee_name, employee_age, employee_salary){
  console.log(employee_name, employee_age, employee_salary);}

I expect to show the data input in the input fields in the page. Thank you
Comment: Could you share your code, perhaps where this function is, as well as the location you want this information displayed?
Comment: here is the code:
`

 this.nameInput = nameInput} />
             this.ageInput = ageInput} />
             this.salaryInput = salaryInput} />
            Add

`
I try to make a add function that displays on the page but I can get the data on the console log after I input text on the input fields
Comment: I try this get method so that I can fetch the data showed in the console log but I don't know to have an getEmployee function. Can someone help me? Thank you.
`onAdd(employee_name, employee_age, employee_salary){

    const employees = this.getEmployees();
    employees.push({
      employee_name,
      employee_age,
      employee_salary
    });
    this.setState({employees});
  }`
Answer: This should work:
import React, { Component } from 'react';

class EmployeeInput extends Component {
  state = {
    employee_name: '',
    employee_age: '',
    employee_salary: '',
  };
  handleChange = e => {
    const { name, value } = e.target;
    this.setState({ [name]: value });
  };
  render() {
    return (
      <form>

            employee_name
            <input name="employee_name" type="text" onChange={this.handleChange} />

          Value: {this.state.employee_name}

            employee_age
            <input name="employee_age" type="text" onChange={this.handleChange} />

          Value: {this.state.employee_age}

            employee_salary
            <input name="employee_salary" type="text" onChange={this.handleChange} />
            Value: {this.state.employee_salary}

      </form>
    );
  }
}

Here's a running example: https://stackblitz.com/edit/react-jl2skw?file=index.js
Comment: how can I post the data in the page that I input in the text field and not in showing only in the console log?
Comment: can the text that typed in the input field cannot delete when text are typed, and add the typed text in the page? Thank you
Comment: I'm sorry. I do not understand your question.
Comment: can the text that are typed in the input field cannot be deleted after you type it? Also it multiplies the data base on what you type in the input field.


IAM role to access services of another AWS account

Question: For security reasons, we have a dev, QA, and a prod AWS account. We are using IAM roles for instances. This is working correctly per account basis.
Now the recruitment here is we want to access multiple aws services {such as S3, SQS, SNS, EC2,etc.} on one of EC2 instance of QA account from Dev aws account.
We have created STS policy and role allowing Trusted entities as another AWS account, but somehow not able to attach this role to EC2 instance.
Example STS policy:
{
"Version": "2012-10-17",
"Statement": {
    "Effect": "Allow",
    "Action": "sts:AssumeRole",
    "Resource": "arn:aws:iam::546161XXXXXX:role/AdminAccessToAnotherAccount"
   }
}

AdminAccessToAnotherAccount: This aws policy on another account with admin access.
This role is not listed while attaching to the ec2 instance.
Comment: Could you please Edit your question and clarify what you have configured? Indicate what you have created and in which account you created it. For example, "a Role in the QA account configured with a Trust Policy", and show the policy.
Comment: @JohnRotenstein I think part of the confusion may be an assumption that if account B allows account A to assume this role, then this role (in account B) would be usable as an instance role in account A... which is not exactly how I believe it's intended to work... the instance role would need to be a native role in account A, which would be used by code on the instance to call `AssumeRole` in STS and access account B's resources with the credentials that returns... I'm not aware of a shortcut.
Comment: Is the above Trust Relationship in the remote account / current account? The problem is that you need to have `ec2.amazonaws.com` also in your trust relationship for the role to be attached to the EC2 instance.
Comment: Trust Relationship is in the current account. Tried this as well but no success.

` {
    "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "Service": "ec2.amazonaws.com"},
      "Action": "sts:AssumeRole",
      "Resource":
    "arn:aws:iam::413985601798:role/AccessAndorraSandbox"
    }
     ]
    }`
Comment: @JohnRotenstein This role we have created in QA account. *AdminAccessToAnotherAccount* This policy is in DEV account. We are trying to access *AdminAccessToAnotherAccount* policy by creating STS in QA account.
Answer: It appears that your situation is:

You have an EC2 instance in Account-1
An IAM Role ("Role-1") is assigned to the EC2 instance
You want to access resources in Account-2 from the EC2 instance

The following steps can enable this:

Create an IAM Role in Account-2 ("Role-2") with the permissions you want the instance to receive
Add a Trust policy to Role-2, trusting Role-1
Confirm that Role-1 has permission to call AssumeRole on Role-2
From the EC2 instance using Role-1, call AssumeRole on Role-2
It will return a set of credentials (Access Key, Secret Key, Token)
Use those credentials to access services in Account-2 (via aws configure --profile foo or an API call).

If use aws configure, you will also need to manually edit the ~/.aws/credentials file to add the aws_session_token to the profile, since it is not requested by the CLI command.

Examples:

Using Temporary Security Credentials to Request Access to AWS Resources
Cross-Account Access Control with Amazon STS for DynamoDB
Comment: The output I get after the described procedure is:
An error occurred (InvalidAccessKeyId) when calling the ListBuckets operation: The AWS Access Key Id you provided does not exist in our records.
AssumeRole worked fine but returned credentials cannot be used within defined profile (securityToken is discarded this way)..
Comment: This is not a question - Im saying it simply wont work, because credentials from AssumeRole without SecurityToken are not going to work.
This answer would be correct in case the last step would be to update additionally "aws_session_token".


Conditional independence and Conditional Expectation given two random variables

Question: The first question I have is: For conditionally independent (given $Z$), random variables $X$ and $Y$, does $\mathbb E [X | Y,Z] = \mathbb E [X | Z]$?
And I also wanted to know if when $X$ is independent of $Y$ and $X$ is independent of $Z$, does $\mathbb E [X | Y,Z] = \mathbb E [X]$? What about if $Y$ and $Z$ were also independent (so all $3$ random variables are pairwise independent)?
For the first question, I know that if $\sigma(Y)$ was independent of the smallest sigma algebra containing $\sigma(X)$ and $\sigma(Z)$ then it would be true, but conditional independence doesn't imply this. I still think it is true but not sure how to show or prove it. I showed it using the expectation equation with probability densities and that $p(x|y,z) = \frac{p(xy|z)}{p(y|z)}$. But I am not sure if this is the correct.
\begin{equation}
\mathbb E [X | Y,Z] = \int x p(x|y,z)dx = \int x\frac{p(xy|z)}{p(y|z)}dx \\\text{  using conditional independence } = \int x\frac{p(x|z)p(y|z)}{p(y|z)}dx = \int x p(x|z)dx = \mathbb E [X | Z]
\end{equation}
For the second question, I don't believe it is true since the smallest sigma algebra containing $\sigma(Y)$ and $\sigma(Z)$ contains more information than each of them alone. And I'm not sure about the expression when $Y$ and $Z$ are also independent.
Thanks in advance for the help!
Answer: Hint to 2nd question: Whenever I think about pairwise independence, the first thing I check is the famous example:

$X, Y$ are i.i.d. Bernoulli variables with $P(X=1) = P(X=0) = 1/2$.
$Z = 1$ if $X = Y$, otherwise $Z=0$.

As is well known, these $3$ are pairwise independent but not mutually independent - any two of them determine the third.
Answer: For your first question, have you tried to prove this if $X$ has densities $p(x | y, z)$ and $p(x | z)$? In this case you can write $\mathbb E [ X | Y, Z] = \int x p(x | Y, Z) dx$ and proceed from there.


Riemann-Stieltjes integral with respect to functions equal almost everywhere

Question: Let $f, g$ be Lebesgue integrable, real-valued functions on $[0, 1]$ with bounded variation, and let $\phi : [0, 1] \to \mathbb R$ be continuous. Assuming that $f = g$ almost everywhere, does one have $$\int_0^1 \phi \mathrm{d}f = \int_0^1 \phi \mathrm{d}g$$
?
Comment: I'd like to guess yes, but I would need to think about the proof. Have you attempted one?
Comment: You don't need $\phi$ to be continuously differentiable to apply integration by parts for Riemann-Stieltjes integrals.
Comment: I was thinking about taking a $\mathcal C^1$-smooth $\phi$ and using integration by parts, however that raises the problem of the boundary values of $f$ and $g$:

$\int_0^1 \phi d f = f(1)\phi(1) - f(0)\phi(0) - \int_0^1 f \phi'$
Answer: Any continuous function $\phi$ is RS-integrable with respect to any functions $f,g$ with bounded variation. This implies that $f,g$ are RS-integrable with respect to $\phi$ (integration by parts for RS integrals) and
$$\int_0^1\phi\,df- \int_0^1 \phi \, dg = \phi(1)[f(1)-g(1)]-\phi(0)[f(0)-g(0)] - \left[\int_0^1 f \, d\phi -\int_0^1 g \, d\phi \right] $$
Suppose $f(x) = g(x)$ for all $x \in [0,1)$ and $f(1) \neq g(1)$, then it is straightforward to show using RS-sums that when $ \phi$ is continuous, we have
$$\int_0^1 f \, d\phi =\int_0^1 g \, d\phi $$
Hence, if $\phi(1) \neq 0$, it follows that
$$\int_0^1\phi\,df- \int_0^1 \phi \, dg = \phi(1)[f(1)-g(1)]\neq 0$$


What exactly does _malloc do in assembly?

Question: public main
main proc near
push    ebp
mov     ebp, esp
and     esp, 0FFFFFFF0h
sub     esp, 30h
mov     dword ptr [esp], 8 ; size
call    _malloc
mov     [esp+2Ch], eax
mov     dword ptr [esp+4], 4
mov     eax, [esp+2Ch]
mov     [esp], eax
call    __start

The code above represents a portion of a large project I am working on. I am trying to reverse this code into C equivalent but I am having difficulty understanding how malloc works.
I am figuring 8 bytes would be the size of the memory being allocated; however, I am not sure about this line.
mov      eax, [esp+2ch]

What does malloc do to eax?
Furthermore would this be equivalent C code?
int main(void)
{
int *ptr1;
ptr1 = (int *)malloc(sizeof(8));
*ptr1 = 4;
__start(*ptr1);

Answer: The function malloc() will allocate a block of memory that is size bytes large. If the requested memory can be allocated a pointer is returned to the beginning of the memory block.
Note: the content of the received block of memory is not initialized.
Syntax of malloc():
void *malloc ( size_t size );
Parameters:
Size of the memory block in bytes.
Return value:
If the request is successful then a pointer to the memory block is returned.
If the function failed to allocate the requested block of memory, a NULL is returned, NULL may also be returned by a successful call to malloc() with a size of zero.
As stated in this CS 301 lecture by Dr. Lawlor:

Calling Malloc from Assembly Language
It's a pretty straightforward function: pass the number of BYTES you
  want as the only parameter, in rdi.  "call malloc."  You'll get back a
  pointer to the allocated bytes returned in rax.  To clean up the space
  afterwards, copy the pointer over to rdi, and "call free" (I'm leaving
  off the free below, because you need the stack to do that properly).
Here's a complete example of assembly memory access.  I call malloc to
  get 40 bytes of space.  malloc returns the starting address of this
  space in rax (the 64-bit version of eax).  That is, the rax register
  is acting like a pointer.  I can then read and write from the
  pointed-to memory using the usual assembly bracket syntax:
mov edi, 40; malloc's first (and only) parameter: number of bytes to allocate
extern malloc
call malloc
; on return, rax points to our newly-allocated memory
mov ecx,7; set up a constant
mov [rax],ecx; write it into memory
mov edx,[rax]; read it back from memory
mov eax,edx; copy into return value register
ret

Rather than copy via the ecx register, you can specify you want a
  32-bit memory write and read using "DWORD" in front of the brackets,
  like this:
mov edi, 40; malloc's first (and only) parameter: number of bytes to allocate
extern malloc
call malloc
; on return, rax points to our newly-allocated memory
mov DWORD [rax],7; write constant into memory
mov eax,DWORD [rax]; read it back from memory
ret

for malloc in assembly language..see this link malloc
Comment: x84_64 and x86 have different calling conventions on various OSes, so this answer is only tangentially related. For example, in the OP's situation, the arguments are clearly passed on the stack, and not in a register.
Comment: Why are you talking about x86_64?
Answer: I'd like to emphasize something that was not mentioned in the other great answer.
How does malloc work internally? What does it do in assembly to create the needed memory?
According to this website, malloc and other memory calls use an operating system API function to allocate and free memory on the heap.
Comment: Exactly the answer I was looking for, thank you!


Exponential Decay with Replenishment

Question: I am working on a problem where 10% of a group of 10500 objects is diminished per year. However, 1000 new objects are added to the group each year, and I have to find the "long-term viability" of the group.
The issue is that I don't know how to integrate the replenishing factor into the exponential decay function. Is there some way to do this?
Thanks!
Answer: For a simple approach, if there is a stable population, it must satisfy $n=0.9n+1000$.  This is easily solved, giving $n=10000$  You can prove that if the population is greater than 10000 in any given year, it will be greater next year, but closer.  Similarly, (not important for your problem), if the population is less than 10000 one year, it will be less than 10000 next year, but closer.  So the population converges on 10000, regardless of the start.
Comment: Well just doing the first two years by hand, I am taking .9 of 10500 and adding 1000, taking .9 of that result and adding 1000, seeing a significant decrease in the number of objects. Am I understanding your response incorrectly?
Comment: @nmagerko:  I get 10450 for the first year and 10405 for the second.  Is that what you get?
Comment: Yes, that's what I get. I think your comment on the other answer helped me figure out what you were saying!
Answer: Let $a_n$ be the number of objects after $n$ years. Then you have $$a_0=10500,\qquad a_n=(.9)a_{n-1}+1000$$ Have you studied such linear recurrences?
Comment: @nmagerko:  If we define $b_n=a_n-10000$, the recurrence becomes $b_n=0.9b_{n-1}$ with the solution $b_n=b_0\cdot 0.9^n$, so $a_n=10000+500\cdot 0.9^n$
Comment: You could use this model to calculate the number of objects recursively, but if you have studied linear recurrences you may have learned that you can *solve* them and get a formula for $a_n$ that depends only on $n$ (in particular, *not* on previous values). Even if you haven't studied the topic, you mau be able to figure out the solution on your own, by doing a few iterations, guessing the pattern, and then proving it. Also, if all that interest you is the long-term viability, just think about solving $a_{n+1}=a_n$, and the implications of a solution.
Comment: Well my only issue is that using this model would require that I calculate the number of objects recursively, wouldn't I? Because I am adding 1000 to .1 of the population (.9 left), I would have to know the value after each decay, right?

Exponential Decay with Replenishment


Linq Where Clause with Into

Question: How do i supply where condition in this query with into clause ?
    var res = from aa in db.UserMsts.Where(p => p.Id == id)
              join bb in db.UserGrpHdrs on aa.usrgrpid equals bb.usrgrpid
              join cc in db.UserGrpDtls on aa.usrgrpid equals cc.usrgrpid where cc.pageid == pg
              join dd in db.UserPrivHdrs on new { aa.usrgrpid, userid = aa.Id } equals new { dd.usrgrpid, dd.userid }  into ddd
              from dd in ddd.DefaultIfEmpty()// <==  left outer join

//Error in following line
              join ee in db.UserPrivDtls on dd.usrprivid equals ee.usrprivid
              where ee.pageid == pg into eee // error here at into

              from ee in eee.DefaultIfEmpty() // <==  left outer join
              select new UserPrivDto{
                     CanAdd = ee.addpriv != null ? ee.addpriv : cc.addpriv,
                     CanEdit = ee.editpriv != null ? ee.editpriv : cc.editpriv,
                     CanView = ee.viewpriv != null ? ee.viewpriv : cc.viewpriv,
                     CanDel = ee.delpriv != null ? ee.delpriv : cc.delpriv,
                                  };

UserPrivDtls  must be filtered and should be joined with a left outer join.
The Error is

A query body must end with a select clause or Group clause

.
Thanks
Comment: You could use `db.UserPrivDtls.Where(ee1 => ee1.pageid == pg)`, just as you do with `db.UserMsts.Where`.
Comment: @GertArnold Thanks It worked.  Should  make it an answer.
Answer: As you're already mixing query syntax and fluent syntax, the most practical solution is add a Where condition to db.UserPrivDtls:
var res = from aa in db.UserMsts.Where(p => p.Id == id)
          join bb in db.UserGrpHdrs on aa.usrgrpid equals bb.usrgrpid
          join cc in db.UserGrpDtls on aa.usrgrpid equals cc.usrgrpid where cc.pageid == pg
          join dd in db.UserPrivHdrs on new { aa.usrgrpid, userid = aa.Id } equals new { dd.usrgrpid, dd.userid }  into ddd
          from dd in ddd.DefaultIfEmpty()

          join ee in db.UserPrivDtls.Where(ee1 => ee1.pageid == pg)
              on dd.usrprivid equals ee.usrprivid
              into eee
          from ee in eee.DefaultIfEmpty()

          select new UserPrivDto{
                 CanAdd = ee.addpriv != null ? ee.addpriv : cc.addpriv,
                 CanEdit = ee.editpriv != null ? ee.editpriv : cc.editpriv,
                 CanView = ee.viewpriv != null ? ee.viewpriv : cc.viewpriv,
                 CanDel = ee.delpriv != null ? ee.delpriv : cc.delpriv,
                              };

Linq Where Clause with Into


What is the distribution of the difference of two-t-distributions

Question: ... and why ?
Assuming $X_1$,$X_2$ are independent random-variables with mean $\mu_1,\mu_2$ and variance $\sigma^2_1,\sigma^2_2$ respectively. My basic statistics book tells me that the distribution of the $X_1-X_2$ has the following properties:

$E(X_1-X_2)=\mu_1-\mu_2$
$Var(X_1-X_2)=\sigma^2_1 +\sigma^2_2$

Now let's say $X_1$, $X_2$  are t-distributions with $n_1-1$, $n_2-2$ degrees of freedom. What is the distribution of $X_1-X_2$ ?
This question has been edited: The original question was "What are the degrees of freedom of the difference of two t-distributions ?". mpiktas has already pointed out that this makes no sense since $X_1-X_2$ is not t-distributed, no matter how approximately normal $X_1,X_2$ (i.e. high df) may be.
Comment: For the special case where the degrees of freedom is 1 (the Cauchy distribution) the answer to the original question is 1. The sum (or difference) of two independent Cauchy distributed random variables is Cauchy with scale parameter $2$, but then again, the Cauchy distribution does not even have a mean value.
Comment: Google the Satterthwaite t-test, the CABF t-test (Cochran's approximation to the Behrens-Fisher), and the Behrens-Fisher problem.
Comment: this is [related question](http://stats.stackexchange.com/questions/6304/what-is-the-sum-of-squared-t-variates) which might be of interest.
Comment: You need to check the Behrens–Fisher distribution
Answer: The sum of two independent t-distributed random variables is not t-distributed. Hence you cannot talk about degrees of freedom of this distribution, since the resulting distribution does not have any degrees of freedom in a sense that t-distribution has.
Comment: @steffen, no. It will be approximately normal, since you will add two approximately normal distributed normal variables. t-distribution with high df is approximately normal, but approximately normal is not necessarily t-distribution with high df.
Comment: @steffen, t-test statistic is derived from the difference of two normals not two t-distributions. Note that definition of t distribution is a fraction of normal and square root of chi-square.
Comment: @steffen, I often say to my students there are no stupid questions, only stupid people who do not ask any questions. I am not a very popular teacher I should add :)
Comment: @mpiktas: Dumb question. If the t-distribution with n-1 df can be derived from the sum of n indepent normal distributions (see wikipedia) and given df high enough so that the t-distribution approximates the normal distribution, doesn't derive from that that the sum of t-distributions is again a t-distribution ?
Comment: @mpiktas: What about the test-statistic of the t-test, which seems to be derived from the difference of two t-distributions ?
Comment: @mpiktas thank you for the response ! I often make the mistake to mix "precisely equivalent" with "close enough for practical purpose" which was the case here. I am going to reformulate this question in a few minutes since it is, well, rather stupid :).
Comment: Your first sentence is incorrect. If two independent t  have the same df then their sum is t. Your answer has lead to a confusion here
https://stats.stackexchange.com/questions/67623/sum-of-two-independent-student-t-variables-with-same-dof-is-t-distributed
Answer: Agree the answers above, the difference of two independent t-distributed random variables are not t distributed. But I want to add some ways of calculating this.

The easiest way of calculating this is using a Monte Carlo method. In R, for example, you random sample 100,000 numbers from the first t distribution, then you random sample another 100,000 numbers from the second t distribution. You let the first set of 100,000 numbers minus the second set of 100,000 numbers. The obtained 100,000 new numbers are the random samples from the distribution of the difference between the two distribution. You can calculate the mean and variance by simply using mean() and var().

This is called Behrens–Fisher distribution. You can refer to the Wiki page: https://en.wikipedia.org/wiki/Behrens%E2%80%93Fisher_distribution. The CI given by this distribution is called "fiducial interval", this is not a CI.
Numerical integration might work. This is continued as the bullet point 2. You might refer to the Section 2.5.2 in Bayesian Inference in Statistical Analysis by Box, George E. P., Tiao, George C. It has the detailed steps of integration, and how this is approximated to be a Behrens–Fisher distribution.
Comment: It seems to me that the Behrens-Fisher distribution applies where the variance of the two t-distributions are not equal. Can the same be said if the variance of the two distributions IS equal?
Comment: Sorry, pressed enter two early? To continue...
For example say we have two normal distributions of equal but unknown variance, but different means. We draw two samples from each of these distributions. The difference of means between the two samples from the same distribution will follow a t-distribution, but what is the distribution of the difference of the differences.


Spring não consegue se comunicar com o RabbitMQ (Docker)

Question: Subi o RabbitMQ e a aplicação no docker através do docker-compose, o container do RabbitMQ roda ok, mas a aplicação em spring não consegue se comunicar, dando erro:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'rabbitMQConnection': Invocation of init method failed; nested exception is org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused
Alguém sabe o pode ser? Segue abaixo os códigos:
<code>**DOCKER-COMPOSE**
version: "3.7"
services:
  server:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - 8080:8080
    depends_on:
      - rabbitmq
    restart: always
    networks:
      - backend
  rabbitmq:
    image: "rabbitmq:3-management"
    container_name: rabbitmq
    restart: always
    ports:
      - 5672:5672
      - 15672:15672
    environment:
      - RABBITMQ_DEFAULT_USER=guest
      - RABBITMQ_DEFAULT_PASS=guest
    networks:
      - backend
networks:
  backend:
    driver: bridge
</code>
<code>**DOCKERFILE DA APLICAÇÃO SPRING**
FROM openjdk:17
COPY build/libs/*.jar app.jar
ENTRYPOINT ["java", "-jar", "app.jar"]
</code>
Quando testo subindo a aplicação local com o Rabbitmq no docker, funciona normal.
Answer: 1  - Acho legal vc utilizar uma imagem rabbit com shovel, para vc conseguir enviar e receber as mensagens manualmente, tenho uma imagem pronta aqui
https://github.com/GuilhermeCesar/rabbit-shovel-jms/blob/main/docker-compose.yaml
2 - Vc precisa gerar as exchanges e filas programaticamente, https://spring.io/guides/gs/messaging-rabbitmq/


Laravel Eloquent - Get data from 3 tables with consecutive foreign keys

Question: I'm looking for a way to join 3 Data Tables.
<code> table a
 -------
 a_id
 b_id
 a_val

 table b
 --------
 b_id
 c_id
 b_val

 table c
 --------
 c_id
 c_val
</code>
Laravel Query;
<code>$join = DB::table('a')->join('b', 'b.b_id', 'a.b_id')->get();
</code>
How to fetch data from table 'c' by applying a query on table 'a'?
i'm new to Laravel.
Answer: Basically, it is not as much related to laravel it needs knowledge of the database.
You can join 3 tables like this.
<code>$join = DB::table('a')->join('b', 'b.b_id', 'a.b_id')->join('c','b.c_id','c.c_id')->select('c.c_id','c.c_cval')->get();
</code>
Comment: Thanks a bunch, brother!
You saved me alot of time..
Answer: Take a look at eloquent relationships on how to connect models.
specifically of use to you is the hasOneThrough() or hasManyThrough() functionalities
https://laravel.com/docs/7.x/eloquent-relationships#has-one-through


Nginx Server Block for SSL don't work

Question: My site is available without ssl via http but not via https. With https://www.example.com occurs a network timeout. Also the nginx error.log shows no errors. Why am I not able to redirect and reach the site via https?
This is my nginx server block file:
server {
    listen 80;
    listen [::]:80;
    server_name www.example.com example.com example.org www.example.org
    return 301 https://$server_name$request_uri;
}
server {
    # SSL configuration
    listen 443 ssl;
    listen [::]:443 ssl;
    ssl on;
    ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;

    root /var/www/example;

    # Add index.php to the list if you are using PHP
    index index.php index.html index.htm index.nginx-debian.html;

    server_name example.com www.example.com;

    # pass the PHP scripts to FastCGI server
    #
    location ~ \.php$ {
        try_files $uri  =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        # With php5-fpm:
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny all;
    }
}

Output of netstat -tulpen|grep 443
 tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      0          417562386   339/nginx: worker p
    tcp6       0      0 :::443                  :::*                    LISTEN      0          417562387   339/nginx: worker p

Edit:
This is my nginx.conf
user xy;
worker_processes 5;
pid /run/nginx.pid;

events {
        worker_connections 4096;
        # multi_accept on;
}

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;
        # server_tokens off;

        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

        gzip on;
        gzip_disable "msie6";

        # gzip_vary on;
        # gzip_proxied any;
        # gzip_comp_level 6;
        # gzip_buffers 16 8k;
        # gzip_http_version 1.1;
        # gzip_types text/plain text/css application/json application/javascript text/xml application/$

        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}

Answer: With that config there is no way for your site to be accessible via HTTP.
If it still is, then config is not used.
First of all, try to stop nginx and then start it again. Sometimes it hangs and does not restart correctly.
Then check, does your site really work from that part of configuration.
Add access_log directive to log requescts into some unusial (for your configuration) file. Something like /tmp/nginx.test.log (just to avoid write permissions handling).
http://nginx.org/en/docs/http/ngx_http_log_module.html#access_log
If you are accessing your site and no line are adding to log, then it is just served by other part of config.
Don't forget to remove that logging and log itself after the check!
Comment: Well I did like you told me. First stop and start nginx but nothing changed. Afterwards I wrote access_log /home/userx/test.nginx.log in front of the first server block.
Reloaded nginx and same result as before and I have something inside the test.nginx.log `xxx.xxx.xxx.xxx - - [19/Oct/2016:20:18:40 +0200] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0"`
Ok I tried to put it into the fist server block but the same result as before.
So I wrote it instead of that into the 2nd server block with the ssl config and now I got now new lines
Answer: Ok finally I found it. It was simply a fault in the firewall. Port 443 wasn't allowed.
But it still doesn't redirect from http:// to https://

Nginx Server Block for SSL don't work


SQL-Server migration assistant (SSMA) Sybase License

Question: It appears that Microsoft's "license registration download" for Sybase is returning a 404 error now.  SSMA was downloaded from http://www.microsoft.com/en-us/download/details.aspx?id=28765 .
I found a blog post that points to the Accsss license download (http://www.microsoft.com/en-us/download/confirmation.aspx?id=18589), but nothing for Sybase yet.  I'm hoping one of you have either worked thorough the Microsoft support gauntlet, or were able to snag a license before the page went offline.  Apparently it has been broken for a few months now.
Thanks in advance
John
Comment: I just opened a support case with Microsoft for this very problem. When I get the correct link I will post it. The product I'm using (trying to use) is SQL Server Migration Assistant V5.2 for Sybase ASE. I installed it last November on another server and the link worked fine then.
Answer: Microsoft sent me a license file but unfortunately it is only for my company and I can't share it.  The link hasn't changed but they said that the license website was being worked on and hopefully will be back up in a couple of days.
Comment: I've seen blog posts saying it has been down since October, so I'm not holding my breath.  How did you request the license from Microsoft?  Is there an email that they actually respond to, or a particular web-form you filled out?


Measure of union of uncountable set

Question: I am trying to understand or prove a conjecture:
Let $U$ be an uncountable set of Lebesgue measure zero. Suppose for each element of $U$, there exists a set $Z_i$ with Lebesgue measure zero. Then, $\bigcup_{i} Z_i$ is a set of Lebesgue measure zero.
Any hint or proof? Thanks
Answer: Take any measure zero set which has the cardinality of $\mathbb{R}$-it can be for example the Cantor set $C$. Then there is a bijection $f$ between $C$ and $\mathbb{R}$. Then for each $a \in C$ we can assosiate $f(a)$ and $\bigcup_{a \in C}f(a)=\mathbb{R}$. The reason is that two sets with the same cardinality may be very different from the measure theoretic point of view: in other words arbitrary bijection need not preserve zero-measure sets.
Comment: A side comment: This sort of argument - building up the union in continuum-many pieces - is necessary, in a precise sense. It is consistent with ZFC (but independent!) that the union of *fewer than* continuum-many measure-zero sets has measure zero. Obviously this follows from CH, but it turns out that it can be true even if e.g. $\vert\mathbb{R}\vert=\aleph_{17}$.
Comment: @Mohkam7 "Continuum-many" just means "as many as there are real numbers": when I say there are continuum-many elements of $A$, I mean there is a bijection between $A$ and $\mathbb{R}$. Cardinality can be surprising - for instance, there is no bijection between $\mathbb{Q}$ and $\mathbb{R}$, but there **are** bijections between $\mathbb{R}$ and $\mathbb{R}^n$. And there is a bijection between $C$ and $\mathbb{R}$. However, it is possible that there is a set of reals which is uncountable, but not in bijection with $\mathbb{R}$ (that is, of "intermediate" cardinality). (cont'd)
Comment: But I think that you have to assume your set to be measurable-in contrast to countable case where every coutable set is measurable and of measure zero (for Lebesgue measure).
Comment: I don't think that's right - I believe what I wrote is correct. Certainly you can have $\vert\mathbb{R}\vert=\aleph_{17}$ and every set of reals of size $<\aleph_{17}$ is null. But maybe my previous comment needs a measurability hypothesis, let me check.
Comment: Can we say these sort of counterexamples exist if and only if the cardinalities of  $\mathbb{R}$ and $C$ are equal. I mean, is it possible to come up with a counterexample where there is no bijection between  $\mathbb{R}$ and $C$? Thanks
Comment: I mean instead of $\mathbb{R}$, suppose we are in $\mathbb{R}^n$ and let $C\subseteq \mathbb{R}^{n-1}$ be uncountable.
Comment: But in fact the cardinalities of $C$ and $\mathbb{R}$ or even $\mathbb{R}^n$ are all the same and equal to continuum-regardless of the continuum hypothesis. So I don't know whether I understood your question correctly: do you mean that now we take an uncountable (but less than continuum) union of sets of measure zero and ask whether we can produce the set of positive measure? Then the answer is negative-see Noah Schweber comments.
Comment: Thanks, you are right. I am not a math major and I was thinking that cardinalities are different when the dimensions are different, but now I almost understand. Actually I don't know the definitions of continuum-many and fewer than continuum-many, but I am trying to find that on the web.
Comment: @Noah Schweber I think your side comment is useful for my specific problem. Could you please define continuum-many and fewer than continuum-many for me? or just give me a reference. Thanks
Comment: The statement that there is no such set is the **continuum hypothesis**, and is known to not be provable or disprovable from the usual axioms of set theory, ZFC.
Comment: Sorry, I am still a bit confused. If cardinalities of $\mathbb{R}^n$ and $\mathbb{R}^{n-1}$ are the same, why $\mathbb{R}^{n-1}$ is a set of Lebesegue measure zero in $\mathbb{R}^{n}$? Actually, I somehow understand, but I cannot digest all of these together. If I define a counting measure instead of the Lebesgue measure, is there any chance that the conjecture would work? Thanks truebaran @NoahSchweber
Comment: @Mohkam7 Measure and cardinality are, unfortunately, largely unrelated: we can have a size-continuum set with zero measure (e.g. Cantor set). Having positive measure means at the very least that the set must be uncountable (and, if measurable, then size continuum), but just knowing the cardinality of a set tells you nothing about its measure. Re: counting measure, there is no set which is uncountable but has counting measure zero, so I'm not even sure what you're asking there.
Answer: Hint: This is not true.
You can use any non-measurable set to build a counterexample if you index it with the elements of the Cantor set.
Comment: This isn't even true if every set is measurable! Just take $U$ to be the Cantor set, $f$ a bijection between $U$ and $\mathbb{R}$, and $Z_i=\{f(i)\}$ for $i\in U$. Then $\bigcup Z_i$ is all of $\mathbb{R}$.
Comment: I am still a bit confused by this answer, to be honest - unless I'm missing something, bringing non-measurable sets into the picture just makes things more complicated.
Comment: @NoahSchweber I suppose I could accomplish the same with any set of non-zero measure... but the point is that you can take a union if null sets to get a set that is not "measurable with measure zero".

Measure of union of uncountable set


Views - context filter by nid

Question: I have created a view, which basically queries files of type image. That view creates a block, which associated with a certain content type. So the block is displayed whenever one of the nodes of that type is displayed, exactly what I would like to have.
Each of the files displayed has an entity reference field, which contains multiple references to that content type. So that is a one to many relationship, where one image can have multiple nodes of that type associated.
Is it possible within the views ui, to set a contextual filter that it sorts out each file, whose entity reference field (to that content type) contains the current node id?
In pseudo SQL the statement should look like:
SELECT filename, path, node_refs FROM files WHERE node_refs contains <current node id>;
Thanks in Ahead!
Answer:
Add a relationship as Entity Reference: Referencing entity
Name it with the name of your content type for instance (easier to read in the view settings)
Check the Require this relationship option
Add a contextual filter with Content: Nid

Here comes the trick!

Choose Provide default value in the WHEN THE FILTER VALUE IS NOT IN THE URL fieldset
Type should be Content ID from URL

This will make Drupal fetch the context from the current URL where your block is displayed and loop through the files referenced by the current node.
TA-DAAA :-)
Comment: Thanks a lot, that trick did the trick and was the missing part!

Views - context filter by nid


package development: setting options before dependencies load

Question: My R package has a dependency that needs a certain option set before it loads. Setting this option in the .onLoad function of the zzz.r file of my package does not work, since the dependency appears to load before .onLoad is called.
How can I guarantee that a certain option is set for the user of my package before its dependencies load?
Here is a link to a sample package that illustrates the situation: soExample.zip
The dependency in my example is the bartMachine package. The setting in question controls the amount of memory available to Java. When I'm using bartMachine in interactive mode, I can simply set the option, load bartMachine, and the startup message informs me that it has recognized the java.parameters option I've set and made the requested amount of memory available to Java.
options(java.parameters='-Xmx5g')
library(bartMachine)
# ....
# Welcome to bartMachine v1.2.1! You have 4.77GB memory available.

However, when I load my package that depends on bartMachine, the java.parameter option set in .onLoad does not take effect in time and bartMachine makes only the default amount of memory available.
library(soExample)
# ....
# Welcome to bartMachine v1.2.1! You have 0.48GB memory available.

Comment: I've just found myself in a completely analogous situation, wishing for just the same thing. Since asking this question, have you learned some way of setting options before a package loads or attaches one of its Depends or Imports? (FTR: In my case, I'm wanting to set the option `exifr.exiftoolcommand`, which points to the location of the external executable exiftool, **before** my own package imports package **exifr**.)
Comment: Any solution how to deal with this in general and not specifically related to the `barMachine` package?
Answer: I'm the maintainer of the package and I never thought about this scenario. A few questions:

Can you ship your user (you?) a local package (in a tar.gz file)?
Do you need the ability to customize the amount of RAM still?

What I was thinking is: you clone the code, you call options(java.parameters='-Xmx5g') within the edited zzz.R after the jpackage on line 2 here. You do R CMD build bartMachine to get a package, you send the package to the user and have them install locally.
Comment: Thanks for your answer. The package is internal, so this might actually be feasible. I'm going to leave the question unanswered, since a workable solution for the mass-distribution scenario still escapes me.
Comment: Wait a minute: what prevents you from just running`options(java.parameters='-Xmx5g')` before you do anything at all?
Comment: That would of course ensure the right settings. My actual situation is one in which I'm deploying a package on several machines with the same resources and I'd like to fit as much of the R configuration into the package itself so that no matter how it is run on these machines, it will have the correct settings at load time. But the limitation is merely an inconvenience and by no means a deal breaker for using the package.
Comment: I believe all deployment with Java requires you to start a JVM with certain parameters and rJava implementations in CRAN packages are no exception.