determining the format in which date is coming in excel through poi

Question: Please advise one thing from excel i am reading cells data in which there are few cells in which dates are coming , now lets say one cell in which date is there is of date data type as i check by clicking on that cell and checking its data type but the other cell in which date is there are of string and text type .
now the dates in cell can be of UK format or of US format also so is there any way lets say if dates are coming as string in cell in excel we can check the format in which date is coming through POI in java and then can take necessary actions
so my major concern is for string cells in which date is coming as i want to determine that if date is coming and is of which format as i have to so some logic based on the for mats of the date
i am using poi 3.5 in java 5 to read the excel data
Comment: Apache POI will happily let you read "proper" date cells as a Java date object. Storing dates (or any number really) as a string cell rather than a date/numeric cell is generally advised against, is there a reason why you're doing that in your spreadsheet to start with?
Comment: Well actly most of the cells are of Date type and few are of numeric type also but since we are receiving this as from upstream so for few cells they are sending date as of string type that's why,  anyways is there any way to overcome from this
Comment: Ask the user where in the world they're from, and base it on that. Or make them use ISO-8601 format for all dates, as that's non-ambiguous. Your problem otherwise is not a coding problem, it's a bug in the real world...
Comment: Thanks I will ask the user to send the dates in date data type cell they are free to send date in cell I  any format but they should sent it in date type cell and then poi us intelligent enough to determine the format and return the java date object,  please correct me if I am wrong here
Comment: If it's date formatted, POI can give you the date. If it's random text in a string cell, in a random format, then all you can do is guess!
Comment: Yeah got the point, Thanks
Answer: Proper way is, that you will specify that it has to be in date format, if not reject the input from user.
You cannot find whether 2/3/2015 is US (February) or UK (March) date...
You can do some best effort approach, but you will have problems with this...
Comment: It's not about the poi, those two formats have "collisions" - dates you do not know in which format they are in as shown above.
Comment: Yeah agree with you completely on this as I think java poi is not intelligent enough


TrixBox Samba share stopped working

Question: I have a TrixBox VoIP server running TrixBox CE 126.96.36.199. Up until recently, I was able to access a Samba share on that box at \astersik\share from my Windows PCs. The share is suddenly no longer working, I get an error message "Windows cannot access \asterisk\share" and the error code is 0x80004005 "unspecified error". Really helpful, Windows, thanks.
I'm pretty clueless when it comes to Linux - can anyone help me troubleshoot and check if Samba is configured right on the TrixBox? I've already tried running the setup_samba script, which runs successfully.
UPDATE: I discovered that it is only some newly-upgraded Windows 7 machines that can no longer access the Samba share. My server (2003) can see it OK. Hmmm...
Answer: It is the new authentication in Windows Vista / 7 that stops older versions of Samba from communicating.
I had the same problem on a NAS (as most off the shelf NASs are based on Samba)
It is advised to leave it set, but if you want to turn it off, do the following. (Assuming there is no Domain Policy and this is a isolated machine or a workgroup)
Go to Control Panel > Administration Tools > Local Security Policy
From here, select Local Policies. Depending on the exact settings of the Samba server, it can be a few things but the first one to try should be.
Network security : LAN Manager authentication level. Try nocking this down a step at a time until you can access the Samba service.
If this does not help, Take a look at the other Network policies that are to do with authentication, especially NTLM/NTLMv2
The reason I am not listing all of them is because I am not 100% sure. To answer your question, I had a look at the security options and I have seen that there are quite a few new options since Vista. I apply my setting through group policy and have not had to look here for a while. I can confirm though that by doing the setting I said above, I can access a Samba share that I would of had problems with before so I think it should work.

TrixBox Samba share stopped working


Inequality combined with divisibility relation

Question: Let $k$ and $m$, where $k>m$, be positive integers such that $$k^3-m^3 \vert  km(k^2-m^2).$$
Prove that ($k-m)^3>3km$
I established that $k^3-m^3<km(k^2-m^2)$, which gives $k^2+m^2+km<km(k+m)$.
By AMGM $3km<k^2+m^2+km$.
Could someone give me a hint?
I'm stuck but I would like to solve it by myself.
Comment: Have you tried using the general solution in the [answer](/a/4839426) that I provided to your earlier related question, in particular using inequalities based on the lower limits of certain values? Note I've confirmed that this does work. However, I won't post an answer here since you've stated that you would like to solve it yourself.
Comment: @JohnOmielan  I think I've got it. I posted my solution below. Could you please confirm my solution? Thank you for your help
Comment: You're welcome for my assistance. It's great that you tried to get a solution using the forms for $k$ and $m$ that solve $k^3 - m^3 \mid km(k^2 - m^2)$. Unfortunately, as I stated in my answer, the expressions for $k$ and $m$ you're using are *only* a special case. Nonetheless, you've got the right general idea with what you've shown in your [answer](https://math.stackexchange.com/a/4839941/602049). I suggest you now try to use the full general form I give in my $(5)$ to reach the same conclusion.
Comment: @JohnOmielan I think now it's right
Answer: I think I've got now a solution.
With the expressions for k,and m from this question
Set $k=dk_1$, $m=dm_1$ and $d=n(k_{1}^2+k_1m_1+m_{1}^2)$.
Then the inequality becomes:
$3d^2k_1m_1<((k_1-m_1)(d))^3$
Which is equivalent to
$3k_1m_1<(k_1-m_1)^3d$
Since by AmGm $3k_1m_1\leq3nk_1m_1<d$ and $(k_1-m_1)>0$ the inequality holds.
Comment: Good work. This is basically correct, but there are a few minor issues. We have $3k_{1}m_{1} \le 3nk_{1}m_{1}$, since $n\ge 1$, not $3k_{1}m_{1} \lt 3nk_{1}m_{1}$, and also this is not due to the [AM-GM inequality](https://en.wikipedia.org/wiki/AM-GM_Inequality). Also, FYI, instead of using the AM-GM inequality to show $3k_{1}m_{1} \lt k_1^2+k_{1}m_{1}+m_1^{2}$, another method is to use $(k_1-m_1)^2\gt 0\;\to\;k_1^2+2k_{1}m_{1}+m_1^2\gt 0\;\to\;k_1^2+k_{1}m_{1}+m_1^2\gt 3k_{1}m_{1}$.
Comment: FYI, here's the way I solved it myself. I used $(k-m)^3-3km=d^2(d(k_1-m_1)^3-3k_{1}m_{1})\ge d^2(d-3k_{1}m_{1})\ge d^2(k_1^2+k_{1}m_{1}+m_1^2-3k_{1}m_{1})=d^2(k_1^2-2k_{1}m_{1}+m_1^2)=d^2(k_1-m_1)^2\gt 0$
Comment: Thank you! Could you maybe recommend some resources for elementary number theory?
Comment: You're welcome. First, note I made a typo in my earlier [comment](/questions/4839896/inequality-combined-with-divisibility-relation?noredirect=1#comment10307950_4839941) in that my $k_1^2\color{red}{+}2k_{1}m_{1}+m_1^2\gt 0$ should be $k_1^2\color{red}{-}2k_{1}m_{1}+m_1^2\gt 0$ instead. Regarding resources for elementary number theory, I don't have any specific recommendations as I've not used any such material myself recently. Nonetheless, a [site search](https://math.stackexchange.com/search?q=elementary+number+theory+resources) gives several potentially useful questions to check, e.g., ...
Comment: (cont.) [Very elementary number theory and combinatorics books.](/q/837852) and [which texts on number theory do you recommend?](/q/374662). They provide specific recommendations, links to other site questions, and external resources, such as the AoPS, i.e., [Art of Problem Solving](https://artofproblemsolving.com). Note the AoPS is also a quite good resource for high school math olympiad problems and solutions, where some of them involve challenging elementary number related questions.


Integrating $\arcsin \left(\frac{1}{2r} \left(\left(\lambda^2+(r+t)^2\right)^{\frac{1}{2}}-\left(\lambda^2+(r-t)^2\right)^{\frac{1}{2}}\right)\right)$

Question: In a mathematical physical problem, one has to deal with a non-trivial finite integral given by
$$
f(r,R,\lambda) = \int_0^R \arcsin \left( \frac{1}{2r}
\left( \left( \lambda^2+(r+t)^2\right)^{\frac{1}{2}}
-\left( \lambda^2+(r-t)^2\right)^{\frac{1}{2}}
\right) \right) \, \mathrm{d}t \, ,
$$
where $0<r<R$ and $\lambda>0$ are parameters.
In particular, for $\lambda=0$, it can easily be shown that
$$
f(r,R,0) = \int_0^r \arcsin \left( \frac{t}{r} \right) \, \mathrm{d}t
+ \frac{\pi}{2} \int_r^R \mathrm{d} t
= -r+\frac{\pi R}{2} \, .
$$
Is there a way to deal with the above integral for arbitrary values of the parameter $\lambda$?
Your suggestions and inputs are most welcome.
Thank you
Answer: Define
$$ g \colon [0,\infty)^3 \to [0,1] \, , \, g(r,t,\lambda) = \begin{cases} \frac{\sqrt{\lambda^2 + (r+t)^2} - \sqrt{\lambda^2 + (r-t)^2}}{2 r} &, \, r > 0 \\ \frac{t}{\sqrt{\lambda^2 + t^2}} &, \, r = 0 \, \wedge \, \lambda > 0 \\ 1 & , \, r = 0 \, \wedge \, \lambda = 0\end{cases} \, ,$$
and $A = \{(x,y,z) \in [0,\infty)^3 : x \leq y\}$. Then $g$ is continuous on $[0,\infty) \setminus (0,0,0)$ and bounded ($0 \leq g \leq 1$ follows from the mean value theorem). Therefore,
$$ f \colon A \to [0,\infty) \, , \, f(r,R,\lambda) = \int \limits_0^R \arcsin(g(r,t,\lambda)) \, \mathrm{d} t \, ,$$
is well-defined and satisfies $0 \leq f(r,R,\lambda) \leq \frac{\pi}{2} R$ for $(r,R,\lambda) \in A$. The substitution $t = R s$ shows that $f(r,R,\lambda) = R f\left(\frac{r}{R},1,\frac{\lambda}{R}\right) $ holds for $(r,R,\lambda) \in A$, so it is sufficient to compute
$$ F \colon [0,1] \times [0,\infty) \to \left[0,\frac{\pi}{2}\right] \, , \, F(r,\lambda) = f(r,1,\lambda) = \int \limits_0^1 \arcsin(g(r,t,\lambda)) \, \mathrm{d} t \, .$$

You have already derived $F(r,0) = \frac{\pi}{2} - r$ for $r \in [0,1]$, so we will assume $\lambda > 0$ from now on. Integration by parts yields
\begin{align}
F(0,\lambda) &= \int \limits_0^1 \arcsin \left(\frac{t}{\lambda^2 + t^2}\right) \, \mathrm{d} t = \arcsin \left(\frac{1}{1 + \lambda^2}\right) - \int \limits_0^1 \frac{\lambda t}{\lambda^2 + t^2} \, \mathrm{d} t \\
&= \arcsin \left(\frac{1}{1 + \lambda^2}\right) - \frac{\lambda}{2} \log\left(1+\frac{1}{\lambda^2}\right) \, .
\end{align}
Now let $r \in (0,1]$. It is easy to see that $g$ is differentiable and strictly increasing with respect to the second variable, so we can integrate by parts again and let $u = g(r,t,\lambda)$ to obtain
\begin{align}
F(r,\lambda) &= \arcsin(g(r,1,\lambda)) - \int \limits_0^1 \frac{t}{\sqrt{1 - g(r,t,\lambda)^2}} \, \partial_2 g(r,t,\lambda) \, \mathrm{d} t \\
&= \arcsin(g(r,1,\lambda)) - \int \limits_0^{g(r,1,\lambda)} \frac{g(r,\cdot,\lambda)^{-1} (u)}{\sqrt{1 - u^2}}  \, \mathrm{d} u \, .
\end{align}
Solving $u = g(r,t,\lambda)$ for $t$ is straightforward and we find (letting $\sqrt{\lambda^2 + r^2(1-u^2)} = \lambda v$)
\begin{align}
F(r,\lambda) &= \arcsin(g(r,1,\lambda)) - \int \limits_0^{g(r,1,\lambda)} \frac{u \sqrt{\lambda^2 + r^2(1-u^2)}}{1 - u^2}  \, \mathrm{d} u \\
&= \arcsin(g(r,1,\lambda)) - \lambda \int \limits_{\sqrt{1+\frac{r^2}{\lambda^2}(1-g(r,1,\lambda)^2)}}^{\sqrt{1 + \frac{r^2}{\lambda^2}}} \frac{v^2}{v^2-1}  \, \mathrm{d} v \\
&= \arcsin(g(r,1,\lambda)) - \left[\sqrt{\lambda^2 + r^2} - \sqrt{\lambda^2 + r^2(1-g(r,1,\lambda)^2)}\right] \\
&\phantom{= ~} - \lambda \left[\operatorname{arcoth} \left(\sqrt{1+\frac{r^2}{\lambda^2}(1-g(r,1,\lambda)^2)}\right) - \operatorname{arcoth} \left(\sqrt{1 + \frac{r^2}{\lambda^2}}\right)\right] \, .
\end{align}

The final result for $0 < r < R$ and $\lambda > 0$ is
\begin{align}
f(r,R,\lambda) &= R \arcsin(g(r,R,\lambda)) - \left[\sqrt{\lambda^2 + r^2} - \sqrt{\lambda^2 + r^2(1-g(r,R,\lambda)^2)}\right] \\
&\phantom{= ~} - \lambda \left[\operatorname{arcoth} \left(\sqrt{1+\frac{r^2}{\lambda^2}(1-g(r,R,\lambda)^2)}\right) - \operatorname{arcoth} \left(\sqrt{1 + \frac{r^2}{\lambda^2}}\right)\right] \, .
\end{align}
It contains the edge cases $r = 0$ and $\lambda = 0$ as limits. Although it looks quite complicated, expansions like
$$ f(r,R,\lambda) \stackrel{\lambda \to \infty}{\sim} \frac{R^2}{2 \lambda} \left[1 - \frac{R^2 + 3 r^2}{6 \lambda^2} + \mathcal{O}\left(\frac{R^4}{\lambda^4}\right)\right] $$
are easily obtainable from CAS.
Comment: +1, nice. What encouraged you to actually invert $g(r,\cdot,\lambda)$ explicitly? The algebraic form intimidated me from trying. It surprises me that it turns out to have a nice low order form. Was it the symmetry, perhaps associated with $\pm t$ in $g(r,t,\lambda)$, that gave you hope that the inversion might be simple enough to work?
Comment: @Hans Yes, it was indeed the symmetry of the two square roots that made this method seem feasible. The equation must be squared twice to get rid of the roots, potentially leading to terms up to the fourth order in $t$. However, almost all of them cancel due to symmetry, leaving only a simple quadratic term.
Comment: Yes, the cancellation is the miracle. What I want to ask is whether you saw the telltale of this cancellation from the beginning which encouraged you to plow ahead and try it or you just boldly tried it no matter what?
Comment: @Hans I saw that the higher order terms would cancel and decided to give it a try, but the cancellation of the linear terms was a pleasant surprise.


Node Reference, and Entity Reference are great; I need "Menu reference"

Question: Is there a Menu reference module I can use to attach menus to nodes, and render them on the page?
Comment: Which thing restricts you to choose a menu from menu list? Please clear about query!
Answer: I have never used the module, but in theory, Block Reference should be able to solve your problem. If needed, I assume you can combine it with Menu Block to set up the menu blocks you need.
Answer: You can control which pages to display blocks (menus) on. It would be quite simple only to show a specific menu in a page and region of your liking.
This is done in the block section.
Comment: Truth, but there is not a great UI for that.  This is for a customer.
Answer: Yes there is a Menu Reference Module
Answer: Consider the Context module. Awesomeness packaged.

Node Reference, and Entity Reference are great; I need “Menu reference”


Regex repeating substring

Question: I am trying to do a simple True/False test to see if a string matches my regular expression:
import re

sentence = "eee"

if sentence == r"e*":
    print(True)
else:
    print(False)

How can I get this to come up as True?
Comment: `print(re.match(r"e*",sentence)!=None)` or `print(re.match(r"^e*$",sentence)!=None)`
Answer: Try the following:
import re

sentence = "eee"
matches = sentence.match("e") !== "None"

if matches:
    print(True)
else:
    print(False)

The .match method returns "None" if the regex does not match. The variable matches returns true or false according to if it is matched.

Regex repeating substring


`delete` all `USER` except `Administrator`

Question: I am trying to write a simple SQL script to delete all USER except Administrator.
DELETE *
FROM [Project].[dbo].[User]
EXCEPT USER Administrator

[Project].[dbo].[User]  Table name
USER className
Administrator element which I want to keep

Does anyone know where I am making a mistake?
Comment: You don't say what type of database you're using. Have you checked the documentation for the server to see if this is valid syntax?
Comment: You want a `where` clause. Except is for combining two queries, it's not a condition on which rows to process
Answer: my guess you probably need something like
DELETE FROM Project.dbo.User WHERE UserName <> 'Administrator'

But that would depend on the schema of the User Table which isn't provided.
It seems like you are taking an object oriented approach thinking of Administrator as an object but in the database that would simply be a tuple (cell) in a row if it existed and you need to query the table to figure out all of the rows that you want to do the operation on.


Any easy way of implementing a mega menu?

Question: Im wondering if there is a easy way to implement the following dropdown menu(ive added a before hovering on a list item, and after):

If i had to do it right now, i would use a bootstrap dropdown, and basically have to create an entire module around making the paths to point in the right directions.
Do you guys know of any existing menus or any easier way of doing this?
thanks
Answer: (not a complete answer, but too much for a comment)
The main characteristic of a "mega menu" is that the contents of the menu are not limited to a simple list or tree of menu links. In your own example you have links with descriptions / subtitles, you have a picture, you have multiple columns that probably have nothing to do with a menu tree structure.
This is why you should use tools other than menu links system, for the contents of each megamenu box.
The first step is to forget you are creating a menu, and instead imagine you would be creating custom pages or blocks. How you create these, is a question for itself.
I have heard of someone who used nodes (possibly with pragraphs module), where every megamenu page is a node.
Another option would be to do something with panels.
The next question is how to anchor the megamenu contents to the actual menu items.
The person who used nodes for the megamenu pages (if I remember correctly) used a field where people specify the menu link path. Then when displaying the menu, the contents from the matching node are inserted as submenu.
You could also completely give up on the links being menu links, and instead just display node titles as toplevel items (sorted by whichever criterion), and then the rendered node as "submenus". This could be done with views, if you use a ul/li list as the style plugin (with custom classes) and a special view mode + layout for each item with its megamenu page. The special html you need would be in the custom layout.
Special attention should be given to multiple language versions, and possibly access checks for links. Maybe you use different paths in different languages?
This still requires some creativity in putting everything together.
But the main idea should be to look for solutions outside the menu links system.
EDIT:
I should add: You may want to think about doing something with ajax, to let the contents of the pages load after the main page contents. If I remember correctly, the person I talked to did this somehow, I just don't remember how exactly.
Credits to https://twitter.com/rachel_norfolk
Answer: I basically used the Responsive and off-canvas menu module in D8 and created a view of content, with a JSON output, to give men the mega-menu content that I could "collect" via a bit of jQuery and attach to the menu items lazily if (and only if) the main desktop menu
 was visible.
I speculatively submitted it to Frontend United. Not sure they want to admit people still need mega-menus, though ;-)
Answer: Just use https://www.drupal.org/project/menu_item_extras, it adds fields to the core Menus, no extra entities or configurations.
Answer: superfish has a D8 version yet. TB megamenu is in development, but I couldn't find it's source ...
But right now you probably have to do it on your own. You could make a view that you show as menu-item.
Answer: If you're already familiar with Drupal 7 site building with Panels module, there is a specific module that helps integrate Drupal 7 core Menu system with Mini-panels for mega menus:
Menu MiniPanels
I have built many Drupal 7 sites using this, but the 1.x version of the module depends on the QTip Jquery Library, which is very hard to wrap your brain around and theme.
Because QTip is a total PITA, I help update the 2.x module to better support integration with the Superfish module and Nice Menus module. Unfortunately I haven't had time to give the 2.x the attention it needs, and there is currently no plan to migrate this to Drupal 8 (yet) due to lack of time.
Answer: For anybody who may come across this, I tried https://www.drupal.org/project/we_megamenu which is released recently. It works!
Answer: You can check this https://megadrupal.com/project/md-megamenu
Very easy to use (I watch the video), the problem: it's not free


Omitted variable bias vs. Multicollinearity

Question: There's seems to be a bit like catch 22: suppose I am doing linear regression, and I have 2 variables that are highly correlated. If I use both in my model, I will suffer from multicollinearity, but if I don't put both I will suffer from omitted variable bias?
Comment: Usually, you would not care about both of them simultaneously. Depending on the goal of your analysis (say, description vs. prediction), you would only care about one of them. For description, multicollinearity is just a fact to be mentioned, just one of the characteristics of the data. For prediction, omitted variable bias is largely irrelevant.
Comment: Even though it makes sense, I need to give it some deeper thought. So I won't be accepting it yet.
Comment: Richard is right in the sense that your goal matters but it seems there is confusion about "prediction". Predictions and model performance are generally considered unaffected by multicollinearity. Multicollinearity is a bigger concern when you want to describe the relationships in sample estimated by the beta coefficients or make inferences on the true values/relationships of the betas.
Answer: Usually, you would not care about both of them simultaneously. Depending on the goal of your analysis (say, description vs. prediction vs. causal inference), you would care about at most one of them.
Description$\color{red}{^*}$
Multicollinearity (MC) is just a fact to be mentioned, just one of the characteristics of the data to report.
The notion of omitted variable bias (OVB) does not apply to descriptive modelling. (See the definition of OVB in the Wikipedia quote provided below.) In contrast to causal modelling, the causal notion of relevance of variables does not apply for description. You can freely choose the variables you are interested in describing probabilistically (e.g. in the form of a regression) and you evaluate your model w.r.t. the chosen set of variables, not variables not chosen.
Prediction
MC and OVB are largely irrelevant as you are not interested in model coefficients per se, only in predictions.
Causal modelling / causal inference
You may care about both MC and OVB at once when attempting to do causal inference. I will argue that you should actually worry about the OVB but not MC. OVB results from a faulty model, not from the characteristics of the underlying phenomenon. You can remedy it by changing the model. Meanwhile, imperfect MC can very well arise in a well specified model as a characteristic of the underlying phenomenon. Given the well specified model and the data that you have, there is no sound escape from MC. In that sense you should just acknowledge it and the resulting uncertainty in your parameter estimates and inference.
$\color{red}{^*}$I am not 100% sure about the definition of description / descriptive modelling. In this answer, I take description to constitute probabilistic modelling of data, e.g. joint, conditional and marginal distributions and their specific features. In contrast to causal modelling, description focuses on probabilistic but not causal relationships between variables.

Edit to respond to feedback by @LSC:
In defence of my statement that OVB is largely irrelevant for prediction, let us first see what OVB is. According to Wikipedia,

In statistics, omitted-variable bias (OVB) occurs when a statistical model leaves out one or more relevant variables. The bias results in the model attributing the effect of the missing variables to the estimated effects of the included variables. More specifically, OVB is the bias that appears in the estimates of parameters in a regression analysis, when the assumed specification is incorrect in that it omits an independent variable that is a determinant of the dependent variable and correlated with one or more of the included independent variables.

In prediction, we do not care about the estimated effects but rather accurate predictions. Hence, my statement above should become obvious.
Regarding the statement OVB will necessarily introduce bias into the estimation process and can screw with predictions by @LSC.

This is tangential to my points because I did not discuss the effect of omitting a variable on prediction. I only discussed the relevance of omitted variable bias for prediction. The two are not the same.
I agree that omitting a variable does affect prediction under imperfect MC. While this would not be called OVB (see the Wikipedia quote above for what OVB typically means), this is a real issue. The question is, how important is that under MC? I will argue, not so much.
Under MC, the information set of all the regressors vs. the reduced set without one regressor are close. As a consequence, the loss of predictive accuracy from omitting a regressor is small, and the loss shrinks with the degree of MC. This should come as no surprise. We are routinely omitting regressors in predictive models so as to exploit the bias-variance trade-off.
Also, the linear prediction is unbiased w.r.t. the reduced information set, and as I mentioned above, that information set is close to the full information set under MC. The coefficient estimators are also predictively consistent; see "T-consistency vs P-consistency" for a related point.
Comment: "Prediction" as used by 99.9999% of statisticians would be a case where multicollinearity is generally irrelevant. "Inference" or even just describing the relationships estimated with beta coefficients is when multicollinearity matters more. Multicollinearity does not cause bias in the estimation process and therefore, prediction (predicted Y values or model performance) is almost always considered unaffected by multicollinearity. Omitting pertinent variables, though, causes misspecification and can introduce at least bias but possibly inconsistency into the estimation procedure.
Comment: @LSC, multicollinearity does not cause bias, but this applies equally to prediction and inference. Importantly, while multicollinearity causes high variance, some combinations of parameters have low variance, e.g. the linear combination that is used for prediction in linear regression. That is why multicollinearity does not matter much for prediction. Meanwhile, the high variance of individual parameters is a problem in inference, as the high uncertainty of the point estimates is undesirable.
Comment: @LSC, (continued) Meanwhile, omitted variables cause not only finite-sample, but also asymptotic bias (hence also inconsistency w.r.t. to the true parameter), except when the omitted variables are orthogonal to the space of the included regressors.
Comment: @LSC, you mentioned confusion regarding prediction in a comment above and stressed the 99%... bit, but I do not see any confusion. While none of us has specified the notion of prediction explicitly, we seem to agree well on the implications of multicollinearity w.r.t. it.
Comment: Why the downvote? I would appreciate some constructive feedback so that I can improve my answer. Thank you.
Comment: I'm not trying to be funny, but the feedback I gave is in my post. Prediction is unaffected because multicollinearity doesn't introduce bias and allows for the use of whatever variables are useful for prediction even if information is redundant. "Prediction" as you were using it seemed more imprecise and to imply interpreting betas or making inferences on betas which isn't really prediction in a statistical sense. My use of "confusion" was more of an oblique way to say I think the word is used wrong and this context warrants correct usage of the term. 1/n
Comment: 2/2 I also think your comment that for "For prediction, omitted variable bias is largely irrelevant as you are not interested in model's coefficients per se, only in predictions. " is wrong because OVB will necessarily introduce bias into the estimation process and can screw with predictions because the linear predictor is no longer unbiased.
Comment: @LSC, thank you for your elaboration. Let me try to explain my points in more detail. **(1)** I do not see how I might have implied prediction to deal with interpreting betas or making inferences on betas, because I specifically stated the opposite: *you are not interested in model's coefficients per se*. **(2)** I believe my statement *For prediction, omitted variable bias is largely irrelevant as you are not interested in model's coefficients per se, only in predictions* is also correct; I have elaborated on it by appending my post.
Comment: Maybe we're saying the same thing in different language, but I'm sure confused by your post. "For prediction, multicollinearity and omitted variable bias are largely irrelevant as you are not interested in model's coefficients per se, only in predictions." But you claim "This is tangential to my points because I did not discuss the effect of omitting a variable on prediction. I only discussed the relevance of omitted variable bias for prediction. The two are not the same." I think you should elaborate on how you are using these differently, because it's not clear to me here. 1/n
Comment: You definitely implied the effects of OVB on predictions by your verbiage, so please clarify your wording. If you're conceding OVB has an implication for prediction, then certainly it matters for prediction but to know how much is more challenging in any particular case because it depends on the degree of bias. This feels more like a word game to me, but so I think clarifying your point further would be helpful rather than just saying "these things aren't the same." 2/2
Comment: And your original text was "For prediction, omitted variable bias is largely irrelevant as you are not interested in model's coefficients per se, only in predictions. " Which reads a lot like "biased estimation is irrelevant for predictions, so OVB doesn't matter if you're trying to get predictions." which would be not a great statement. This is mostly what I was commenting on at the origin of this discussion.
Comment: @LSC, Thank you for your comments! I have tried honestly to explain myself to a degree of sufficient detail. I think the best one can do now is carefully read what I have written and be extra careful about deriving implications. The ones you mention were not meant and do not follow from my statements. I have by now provided a definition of the OVB, and I have elaborated below on the tangential point which is not about OVB but about the effect of omitting variables on prediction. The confusion should clear up if one pays sufficient attention to definitions and my precise wording.
Comment: @RichardHardy I agree with you reply about prediction side. However I fear that your reply conflated causation and description role. I writed a related question here (https://stats.stackexchange.com/questions/464261/regression-causation-vs-prediction-vs-description) I would appreciate you reply there.
Comment: OVB is more of an econometrics term. In traditional statistics, not many use "omitted variable bias" but talk about biased estimation and how omitting a relevant variable (nonzero beta and nonzero correlation with something else in the model) could cause this. I think your explanation of "this sounds the same but it's not" is lacking, but if you don't feel further explanation is needed, that's okay! I think we agreed on the important points of what MC or biased estimation can mean, just maybe some vocabulary differences. 1/2
Comment: My point is that, to less technical readers, your point may be lost because they're asking the question in the first place and it may not necessarily follow what I have mentioned, but others can't necessarily pick that up, otherwise the question from OP wouldn't arise in the first place. 2/2
Answer: If your goal is inference, multicollinearity is problematic. Consider multiple linear regression where the beta parameters help us estimate the increase or decrease in Y for a unit increase in X1, all other variables held constant. Multicollinearity has the effect of inflating the standard errors of the beta parameters, making such inferences less reliable. Specifically, the variances of the model coefficients become very large so that small changes in the data can precipitate erratic changes in model parameters.

If the purpose of the regression model is to investigate associations,
  multicollinearity among the predictor variables can obscure the
  computation and identification of key independent effects of collinear
  predictor variables on the outcome variable because of the overlapping
  information they share.

(source)
However, multicollinearity does not prevent good, reliable predictions in the scope of the model.
In general, multicollinearity is acceptable when the goal is prediction, but if multicollinearity is present, it is something you should disclose and it affects the uncertainty surrounding your model estimates.
Be aware that perfect multicollinearity actually leads to a situation in which an infinite number of fitted regression models is possible. The VIF (variance inflation factor) is one rule-of-thumb for how much multicollinearity we can tolerate in inference.

In a model with perfect multicollinearity, your regression
  coefficients are indeterminate and their standard errors are infinite

(source).
Comment: Welcome to Cross Validated! Unfortunately, I think several of your statements are incorrect. Impecfect multicollinearity does not invalidate any assumptions. The coefficients do not lose interpretability or meaning either. The only thing that happens is that confidence bounds get wide.
Comment: @RichardHardy see my edit for sources. You are right that the confidence bounds get wide, and that is my meaning. The confidence bounds widen to infinity as the degree of multicollinearity increases, making coefficients unstable. Small changes in the data can cause coefficients to change erratically.
Comment: Multicollinearity (mc) can be perfect or imperfect. The original post specifically discusses **imperfect** mc: *I have 2 variables that are highly correlated*. Thus my points. Now it is a little unclear which type of mc you are discussing because your description does not fit either type but is a mix of both. Perfect mc (which is irrelevant to the OP) yields unidentified and in a sense meaningless point estimates and undefined/infinite (not just large) standard errors. I think you could improve your answer by making the distinction specific and explicitly stating the case you are discussing.
Comment: @RichardHardy I agree I should clarify the distinction between perfect and imperfect mc. Thanks for your feedback. I will revise my answer accordingly. I wanted to bring light to this point from your comment: "the high variance of individual parameters is a problem in inference." I feel this is a key insight. But when you assert "For description, multicollinearity is just a fact to be mentioned" it might be helpful to clarify the thing about the variances, for those who are wondering why multicollinearity can be a bad thing.


Zend Form create button link

Question: I have Zend_Form with button type element. i don't how to use onclick type from zend_form.
Index.phtml
Search
Zend_Form
<code>$Search = new Zend_Form_Element_Submit('Search');
    $Search->setAttrib('ID', 'searchbutton');
    $Search->setDecorators(array('ViewHelper'));
</code>
Here using this zend form how to perform the onclick action using search button.could you please any one help on this?
Thanks for advice!
Answer: Hey you would have to do something like this
<code>$Search = new Zend_Form_Element_Submit('Search');
$Search->setAttrib('ID', 'searchbutton');
$Search->setDecorators(array('ViewHelper'));

$form = new Zend_Form('FormExample');
$form->setAction('destination.php');
$form->setMethod('POST');
$form->addElement($Search);
$form->setView(new Zend_View());
print($form);
</code>
If you have other elements than the $Search you just have to addElements as an array, like this:
<code>$form->addElements([$Search,$Element1, $Element2]);
</code>
Comment: Hi Jefferson, Here i am not understand $form->setAction('destination.php'); what is mean that, how to i use ?
Comment: @user6420577 every submitt button has an action inside a Form,  in this case setAction was used is to navigate to another page.

Zend Form create button link


Passing a variable inside quotation marks to a command in bash

Question: Some context :
I'm attempting to run a command as part of a bash script to poll for system/device data.
# Recommended usage in the command line, contains single and double quotes
wbemcli ein 'http://localhost:5988/root/cimv2:some_class'
wbemcli gi 'http://localhost:5988/root/cimv2:some_class.DeviceID="Some Device ID"'

# I can get away with just 1 level of quotation marks
wbemcli ein http://localhost:5988/root/cimv2:some_class
wbemcli gi http://localhost:5988/root/cimv2:some_class.DeviceID="Some Device ID"
wbemcli gi http://localhost:5988/root/cimv2:some_class.DeviceID='Some Device ID'

So this is working ...
    #!/bin/sh

    C_PATH=http://localhost:5988/root/cimv2
    CLASS=some_class
    ID="Some Device ID"

    set -x
    wbemcli ein $C_PATH:$CLASS

Unfortunately, it falls apart when I attempt to integrate the quotation marks into the command. The code executed in the shell is unexpected to me.
    # Code
    wbemcli gi $C_PATH:$CLASS.DeviceID=\"$ID\"

    output $ ./myscript
    + wbemcli gi 'http://localhost:5988/root/cimv2:some_class.DeviceID="Some' Device 'ID"'

    # I was expecting this ...
    output $ ./myscript
    + wbemcli gi http://localhost:5988/root/cimv2:some_class.DeviceID="Some Device ID"

Bash is adding quotation marks in places I didn't expect. It's even enclosing the entire URL portion in single quotation marks. What's going on ?
Answer: Try like this:
wbemcli gi -nl "$C_PATH:$CLASS.DeviceID=\"$ID\""

or like this:
wbemcli gi -nl "$C_PATH:$CLASS.DeviceID='$ID'"

Comment: 1st one gives `+ wbemcli gi -nl 'C_PATH:some_class.DeviceID="Some Device ID"'` and 2nd one gives `+ wbemcli gi -nl 'C_PATH:some_class.DeviceID='\''Some Device ID'\'''`
Comment: @peonicles: Both the traces are OK — the `wbemcli` command gets to see either single quotes or double quotes around the 'Some Device ID' and sees the whole string as a single argument even though there are spaces in 'Some Device ID'.  `bash` does echo things differently under `set -x` from other shells; its output is typically unambiguous where other shells' output is ambiguous.
Comment: ahh ok, I had a really dumb syntax error (omitted the $ in $C_PATH). #1 is working perfectly, thanks guys!

#2 is still adding the weird `'\'` though.
Comment: That's just how bash displays the string when you have `set -x` enabled. It's the string `C_PATH:some_class.DeviceID=`, followed by a literal single quote `\'`, the string `Some Device ID`, another literal single quote `\'` and the empty string `''`. You get this weird-looking representation, because nested single quotes can't be escaped in single-quoted strings.
Comment: I've substituted in actual values into the variables, and #1 is working nicely. #2 seems to give me a usable string when I echo, but for some reason wbemcli is giving me errors. Your answer should work for other similar situations though.
Comment: Perhaps `wbemcli` is unhappy about the single quotes around the ID.


Elements are floating outside of bootstrap modal

Question: I have a form insite a modal. When the size of the window is small then everything is fine. If I maximise the window then the elements of the form are floating outside of the modal. I have checked all my css styling etc, but nothing seems to conflict. I have also set this up on JSFiddle, and it seems to happen and there aswell, with just JQuery and Bootstrap. Its seems to be something on my code but I cant figure out what. Could you please take a look on it and help me out?
http://jsfiddle.net/dsryycbq/

                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Change Password

                        <form action="{{url_for('admin')}}" role="form" id="editPasswordForm" method="post">
                            <input type="hidden" name="formType" value="changePassword">

                                Password

                                    <input type="password" class="form-control" name="password" />

                                Repeat Password

                                    <input type="password" class="form-control" name="confirmPassword" />

                                    <button type="submit" class="btn btn-default">Confirm</button>

                        </form>

Comment: @anpsmn that's not correct, `col-sm-3` means take up 3 columns on `sm` or larger. The other way around is important, I think it's a good idea to always have a `col-xs-...` class
Comment: You have classes set only for smaller devices. `col-sm-3`. What about larger devices? [Check this link](http://getbootstrap.com/css/#grid). Also see how forms are styled too.
Comment: As a start you need a `form-horizontal` class on the ``
Comment: Thanks @ckuijjer, You can answer the question, so I can mark it as accepted!
Answer: You need to add the class .form-horizontal to the form element. This makes the .form-group's act as rows. Next to some margin, this adds a clearfix which stops the columns from "floating".


Alterar o docker-compose reflete no container atual?

Question: Caso eu altere a porta exposta no meu docker-compose, ao rodar docker-compose up -d essa alteração irá refletir no container atual?
Answer: A ideia de container no Docker é justamente ele ser efêmero, ou seja ele pode morrer a qualquer momento. Seguindo essa ideia, ao meu ver, não seria adequado alterar a porta de um container já existe, mas sim criar um novo container e expor a porta desejada.
No seu caso, você pode alterar o arquivo yaml que está sendo lido pelo docker-compose e alterar aporta, posteriormente a isso poderia fazer algo como docker-compose up -d, isso vai gerar um novo container com as alterações especificadas no arquivo de configuração.
Complementando: dentro do seu arquivo de configuração (definição) do docker-compose você pode especificar um Dockerfile e definir tudo que sua imagem vai precisar, assim poderá destruir e subir o container sempre que precisar sem a necessidade de ficar reinstalando as coisas manualmente.
Comment: Obrigado pela explicação. Isso já resolve meu problema.


not able to forward values calculated in a servlet to a jsp page using RequestDispatcher.How to do the same?

Question: In my code..i have retrieved the value of input(text type) from a jsp page in a servlet using request.getParameter().
Now using these values,i have performed some calculation.
now i want to forward the calculated value (i.e. the result) as well as the operands.. i e. the retrieved value to a new jsp page. I am doing this by setting the values using request.setAttribute() and forwarding to the destined jsp page using getRequestDispatcher().forward(request,response).
But my page is not being forwarded.
package imsf;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import Service;

public class CalcPurRate extends HttpServlet {
    String iname;
    String cname;
    String mrate;
    String irate;
    String disR;
    String disP;
    String newAdd;
    String q;
    int imr;
    int iir;
    int idR;
    int idP;
    String dP;
    String dR;
    int ina;
    int iprate;
    int total;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
           String in=request.getParameter("iname");
           out.print("my name"+in);
           String cn=request.getParameter("cname");
           out.print("my cate"+cn);

          if(request.getParameter("mrate")!=null)
          {
            String mr=request.getParameter("mrate");
              if(!(mr.equals(null)))
              {
               imr=Integer.parseInt(mr);
               out.print(" mrp= "+imr);
              }
          }
          if(request.getParameter("irate")!=null)
          {
            String ir=request.getParameter("irate");
              if(!(ir.equals(null)))
              {
               iir=Integer.parseInt(ir);
               out.print("invoice= "+iir);
              }
          }
         if(request.getParameter("disR")!=null)
         {
            out.print("disR not null");
            dR=request.getParameter("disR");
            if(!(dR.equals(null)))
            {
             out.print("disR not zero");
             idR=Integer.parseInt(dR);
             /*if(request.getParameter("disP")==null)
                 {
                   out.print("disP not zero");
                   dP=request.getParameter("disP");
                     if(dP.equals(null))
                     {
                       out.print("disP not zero");
                        iprate=((iir)-(idR));
                        out.print("iprate="+iprate);
                     }
                 }*/
              out.print("integer dis R="+idR);
              iprate=((iir)-(idR));
              out.print("iprate="+iprate);
           }
         }
          /*if(request.getParameter("disP")!=null)
          {
              out.print("disP not null");
              dP=request.getParameter("disP");
              if(!(dP.equals(null)))
               {
                out.print("disP value="+dP);
                out.print("disP not zero");
                /*if(request.getParameter("disR")==null)
                  {
                   dR=request.getParameter("disR");
                   if(dR.equals(null))
                    {
                     idP=Integer.parseInt(dP);
                     out.print("integer dis P="+idP);
                     iprate=((iir)-(((idP)*(iir))/100));
                     out.print("pur rate"+iprate);
                    }
                  }*/
              //}
              //}
           /*if(idR!=0)
           {
               out.print("innn");
               iprate=((iir)-(idR));
               out.print("pur rate"+iprate);
           }
           out.print("heheh");

           if(idP!=0)
           {
               iprate=iir-((idP*iir)/100);
               out.print("vgfhg"+iprate);
           }*/
           if(request.getParameter("newAdd")!=null)
           {
               String na=request.getParameter("newAdd");
               if(!(na.equals(null)))
              {
              ina=Integer.parseInt(na);
              total=((ina)*(iprate));
              out.print("total="+total);
              }
           }
           request.setAttribute("purRate",iprate);
           request.setAttribute("total",total);
           //response.sendRedirect("ItemDetail.jsp");
           RequestDispatcher rd=request.getRequestDispatcher("/ItemDetail.jsp");
           rd.forward(request, response);
        }
        catch(Exception e)
        {
          e.getMessage();
        }
    }

}

Comment: What you're doing seems to be the right thing. You should provide some code so that we can look into the details.
Answer: processRequest() is not a method that has any meaning to an HttpServlet.  Your servlet is actually doing nothing whatsoever - processRequest() will not be invoked by anything.
You should be implementing either doGet() or doPost(), and put your logic in there.
Incidentally, storing data in fields of a servlet like this is an extremely bad idea. It's not thread-safe  - multiple concurrent requests will corrupt your servlet's state.
Comment: @skaffman..thanx for ur advice..but i want to share sumthing..i have implemented other codes too in d same way as above (i.e..in processRequest()..and they have worked out well.i want to know why this code is not working..hope i may get ur help...
Comment: @tammanna: I have no idea without seeing it. The code you posted won't work, that's all I can tell you.
Answer: if you want to land in a new page, just use the sendRedirect() method.
by the way the details that you have provided looks correct.
try to get the parameters at the destination jsp and let us know.. it should work..
HTH
Comment: @Ayusman...I want to get forwarded to a new page along with the values calculated in d servlet...using SendRedirect() only a new request will be made and the vlaues will not b forwarded.using RequestDispatcher().forward(req,res),i m not getting the values at d destinaltion page..anticipating for ur help..


gradle nod set up fails installing node x86_64

Question: I'm using gradle node plugin for my project and when I run the nodeSetup task it tries to install the node dist from https://nodejs.org/dist/v12.6.0/node-v12.6.0-darwin-x86_64.tar.gz which I know does not exists. The correct URL should be https://nodejs.org/dist/v12.6.0/node-v12.6.0-darwin-x64.tar.gz I'm not sure why its adding x86_64 instead of x64 and I was wondering if there is any way to directly specify the complete dist URL for gradle node plugin.
Here is my node config inside my build.gradle
node {
    version = '12.6.0'
    npmVersion = '6.0.0'
    yarnVersion = '1.13.0'
    download = true

    workDir = file("${buildDepsDir}/nodejs")
    npmWorkDir = file("${buildDepsDir}/npm")
    yarnWorkDir = file("${buildDepsDir}/yarn")
    nodeModulesDir = file("${project.projectDir}")
}

Answer: It sounds like you may be using an old version of the plugin, this exact issue has been fixed in 3.2.1


Removendo parte do link nas rotas ASP.NET MVC

Question: Meu RouteConfig está configurado desta forma:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
    name: "Default",
    url: "{empresa}/{controller}/{action}/{id}",
    defaults: new { empresa = "", controller = "Login", action = "Index", id = UrlParameter.Optional }
);

Meus acessos as controllers e actions estão ocorrendo normalmente, porem tenho chamadas à arquivos *.aspx para os meus relatórios, esses arquivos estão em um pasta chamada "Relatorios", quando vou realizar a chamada para eles está me retornar desta forma a url:
"http://localhost/minhaempresa/Relatorios/CustoMedio.aspx"
Desta forma ele não encontra o arquivo respectivo.
Estou necessitando acessar a url desta forma:
"http://localhost/Relatorios/CustoMedio.aspx"
Encontrei alguns exemplos como:
routes.Ignore("{*allaspx}", new {allaspx=@".*\.aspx(/.*)?"});

routes.IgnoreRoute("{*favicon}", new {favicon=@"(.*/)?favicon.ico(/.*)?"});

routes.IgnoreRoute("{Content}/{*pathInfo}");

routes.IgnoreRoute("myroute");
routes.IgnoreRoute("myroute/{*pathInfo}");

Porém não obtive sucesso com nenhum destes exemplos.
Comment: Qual versão do MVC você esta usando?
Comment: Estou utilizando a versão MVC 5
Answer: Pode criar outra rota ou modificar essa que vocês esta e deixar como abaixo :
     routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new {controller = "Login", action = "Index", id = UrlParameter.Optional }

);

Answer: Acima da rota Default, use assim:
routes.MapRoute(
    name: "Relatorios",
    url: "{empresa}/Relatorios/{action}",
    defaults: new { empresa = "", controller = "Relatorios", action = "Index" }
);


Is a product of two modulus functions the modulus of the product of the functions?

Question: I would just like to ask a simple question:
Is the following statement true? And is there a simple proof for it? $$|f(x)| \cdot|g(x)| = |f(x)\cdot g(x)| $$
Comment: Is $|ab|=|a||b|$ always?
Comment: @AnginaSeng when is it not precisley
Answer: For $a\in\Bbb C$, by definition $\lvert a\rvert=\sqrt{a\overline a}$. Since, for non-negative real numbers $a,b$, the identity $\sqrt{ab}=\sqrt a\sqrt b$ holds, it can be observed that $$\lvert ab\rvert=\sqrt{ab\overline{ab}}\stackrel{\left(\overline{z\cdot w}=\overline w\cdot\overline z\right)}=\sqrt{ab\overline b\overline a}\stackrel{\left(w\overline w\in[0,\infty)\right)}=\sqrt{a\overline a}\sqrt{b\overline b}=\lvert a\rvert\lvert b\rvert$$
The special case where $a,b\in\Bbb R$ has the same passages with $a=\overline a$ and $b=\overline b$. A subtlety might be the fact that, for most textbooks, $\lvert a\rvert=\sqrt{a^2}$ is considered a theorem, rather than the definition of $\lvert a\rvert$. There is very good reason to make that choice, but it is in principle just a matter of taste.
Comment: I was just a little confused by $a$ being complex and $a, b$ being real in the next sentence. The equation that follows in the next line has $a,b \in \mathbb{C}$.
Answer: Yes, it is true.
By definition (in $\mathbb R$) $$|x| =\begin{cases}x, &x\geq 0\\ -x, &x<0\end{cases} $$
Strictly speaking, there are four cases to consider, but effectively, we can make do by checking three cases.
1
Let $a,b\geq 0$, then $$ |ab| =ab = |a||b| $$
2
Let $a\geq 0, b<0$, then $$|ab| = -ab = a(-b) = |a||b| $$
For the last case, you would have to check this for $a<0$ and $b<0$.
Answer: Yes, $|a|\cdot|b|=|a\cdot b|$ holds for all real numbers. One proof is by considering the four cases

$a\ge 0, \, b\ge 0,$
$a<0, \, b\ge 0,$
$a\ge 0, \, b< 0,$
$a<0, \, b< 0.$

It also holds for complex numbers, btw.
Answer: Use the fact that $|x| = x\cdot\text{sign}(x)$. Then,
$$|x||y| = \text{sign}(x)\text{sign}(y)(xy) = \text{sign}(xy)(xy).$$
Comment: I like the signum approach, but you would have to prove the last equality, which is more or less the same as proving the initial problem.
Comment: @AlvinLepik You're right, but you don't have to work with the other definition of absolute $x$.
Comment: @A.Molendijk But now you have to work with signum, which is defined using three different cases, not two like absolute value.


Bash - reading two files and searching within files

Question: I have two files, file1 and file2. I want to reach each line from file1, and then search if any of the lines in file2 is present in file1. I am using the following bash script, but it does not seem to be working. What should I change? (I am new to bash scripting).
#!/bin/bash

while read line1
do
    echo $line1
    while read line2
    do
        if grep -Fxq "line2"  "$1"
        then
            echo "found"
        fi
    done < "$2"
done < "$1"

Note: Both files are text files.
Comment: Add examples of both files to your question.
Comment: @Cyrus: they're both .txt files.
Comment: Replace `"line2"` by `"$line2"`.
Answer: Use grep -f
grep -f file_with_search_words file_with_content

Note however that if file_with_search_words contains blank lines everything will be matched. But that can be easily avoided with:
grep -f <(sed '/^$/d' file_with_search_words) file_with_content

From the man page:
   -f FILE, --file=FILE
      Obtain  patterns  from  FILE, one per line.  If this option is used
      multiple times or is combined with the -e (--regexp) option, search
      for all patterns given.  The empty file contains zero patterns, and
      therefore matches nothing.

Comment: And OP had better be sure that `file_with_search_words` doesn't have any blank lines.
Answer: You may use the command "comm", it compare two sorted files line-by-line
This command show the common lines in file1 and file2
comm -12 file1 file2

The only problem with this command is that you have to sort the files before, like this:
sort file1 > file1sorted

http://www.computerhope.com/unix/ucomm.htm
Answer: File 1
Line 1
Line 3
Line 6
Line 9

File 2
Line 3
Line 6

awk 'NR==FNR{con[$0];next} $0 in con{print $0}' file1 file2

will give you
Line 3
Line 6

that is the content in file 2 which is present in file1.
If you wish to ignore the spaces you can achieve with the below one.
awk 'NR==FNR{con[$0];next} !/^$/{$0 in con;print $0}' file1 file2


Split array into separate objects based on unique attributes

Question: I have an array that I'm populating by some other means. It essentially contains this sample data;
PSComputerName              ResourceName   InstanceName       InDesiredState ConfigurationName StartDate
--------------              ------------   ------------       -------------- ----------------- ---------
server1.domain.local WindowsFeature Backup             True           BaseConfig        24/04/2018 14:31:23
server1.domain.local Registry       fDenyTSConnections True           BaseConfig        24/04/2018 14:31:23
server1.domain.local Registry       UserAuthentication True           BaseConfig        24/04/2018 14:31:23
server1.domain.local File           DscDemo            True           BaseConfig        24/04/2018 14:31:23
server5.domain.local WindowsFeature Backup             True           BaseConfig        24/04/2018 14:31:23
server5.domain.local Registry       fDenyTSConnections True           BaseConfig        24/04/2018 14:31:24
server5.domain.local Registry       UserAuthentication True           BaseConfig        24/04/2018 14:31:24

This is dynamic, and I'll have no idea when the array is populated what data will be inside. I need to split the array, into unique arrays (or PSObjects) based on the PSComputerName.
So in this case, I'd need to end up with two seperate objects/arrays for server1 and server5, bearing in mind there could be 6 servers or 80 servers. I can't think of the best way to approach this.
Answer: Why not just group the data and work on each group individually? Assuming $objects contains the data in the question
$objects | Group-Object pscomputername | Foreach-object{
    $_.Group
}

Each $_.Group will be a collection of entries associated to a unique computer. $_.Name would be the pscomputername of the current grouped item.
So you might need to have another inner loop to iterate of those results as well.
Answer: Ignore, not sure why I was banging my head against a wall.
$Servers = $CSV.PSComputerName | select -Unique

ForEach($server in $Servers){

    $arr = $CSV | Where-Object {$_.PSComputerName -eq $server}

    Write-Host "Compliancy for $Server"
    $arr
    Write-Host "End compliancy for $server"

}

Answer: group-object. See "Example 4: Group event log events by ID"


Discord.js HTTP Request

Question: I am a new developer that barley knows discord.js
I am trying to send an request to https://rolimons.com
The request is going to be to add a player to a database
using this api
https://www.rolimons.com/playerapi/addplayer?playername=(playernamehere)
I am really not sure how to do it. I would appreciate it if someone would help me out.
Thanks
Comment: Question is to broad. StackOverflow is for specific questions on specific items that are beneficial to the group as a whole. There are other forums to lean the basics of discord.js
Answer: You can use various packages to fetch data, like node-fetch, axios etc.
node-fetch: npm
axios: npm

Discord.js HTTP Request


What is the difference between an unbounded solution and infinite optimal solutions?

Question: I am currently studying Linear Programming, and one of the few things that I haven't found a solution for (pun obviously intended) is the difference between a solution being either unbounded or having infinite optimal solutions.
My thinking is, if something is unbounded, is that not the same as it being infinite? I must not have a proper understanding of both, as I cannot see why my thinking would correct.
If possible, could someone illustrate the differences with a graph?
Answer: Unbounded Solution refers to one solution being unbounded, in the sense that the $y = x$ is unbounded.
Infinite Optimal Solutions refers to an infinite family of functions that are all optimal solutions, in the sense that $x = \pi + 2n\pi$ is an infinity family of solutions to the problem $\min\cos(x)$.
Comment: Does [this](https://en.m.wikipedia.org/wiki/Bounded_function#:~:text=In%20mathematics%2C%20a%20function%20f,is%20said%20to%20be%20unbounded.) clarify what unbounded/bounded functions are?
Comment: Yes, absolutely. Thanks for the help :)
Comment: OK, that makes sense. The only thing I am struggling with then is what *unbounded* actually. Could you kindly elaborate on your point?
Comment: In fact, I may understand it, but without a graph I won't be able to fully show, but I'll try: if you have two constraints and the solution is in between the two lines, that would be considered to have *infinitely many solutions*; whereas if you had one constraint that was *greater than* and $z$ is to be *maximised*, the optimal solution would be anywhere above that line, i.e. *unbounded*. Correct?


How to segment/split words in file

Question: I have a file with a lot of words in it, and i have to split the word that a part of it already existed or appear during the scanning of the file:
Some of the words in the file are
member
members
membership
memberships

I have tried this, but I wanted the first lines[i](which is a) to keep looping the next words
func Split(lines []string) string {
    for i := 0; i < len(lines)-1; i++ { // position of words
        j := i + 1
        fmt.Println(lines[i], lines[j])
        if strings.ContainsAny(lines[j], lines[i]) {
            s := strings.Split(dictionary[j], dictionary[i])
            fmt.Println(dictionary[i], ".", s)
        }
    }
    ...
}

but it only outputs
member
member.s
members.hip
membership.s

The output that i want:
member
member.s
member.ship
members.hip
member.ships
members.hips

Comment: You question is unclear , what do you mean by looping the next word ?
Comment: @MostafaSolati i don't know how to explain it in words, but basically the code should check each letters in the word one by one, if the letters/some words in the word already appeared,the word would be split. And please do refer to the output for examples
Comment: @MostafaSolati extra output examples, member,member⋅ship, member⋅ships, members⋅hip
Comment: Why the last one turned to members.hip instead of member.ship ?
Comment: @MostafaSolati because members is also a word that appears before membership, i forgot to include it after member
Comment: Okay , lets assume there is a members , that should turn to member.s
Comment: @MostafaSolati yes, thats correct
Comment: @MostafaSolati member, member.s, member.ship, members.hip
Comment: You are wrong if members splits to members.s then membership cannot split to members.hip because members splitted earlier so it's not a new word to split new words based on that
Comment: @MostafaSolati it is not based from the next words, it is based from the entire words in the file, as long as the word already appear, if the next word contains the word, it will be split
Comment: What you want leads to something like this m.e.m.b.e.r.s.h.i.p.s because eventually we have smaller words that contain one or two letters
Comment: @MostafaSolati in the file there is no m, e,b,r,s,h,i,p by itself, so m.e.m.b.e.r.s.h.i.p is not possible
Comment: `I have a file with a lot of words in it,`  says what you have is a generic file but the example you have given clearly follows a pattern . Can you confirm if there are any special order in which words appear in the file or should it work on any random file ?
Comment: @SarathSadasivanPillai from a to z, another example i could give is begone, be.gone, beg.one
Comment: @strawberrylatte can you update the question with these examples.  The details are in comments , it would be good to update the question in a manner that the question does not imply assumptions
Comment: @strawberrylatte please check the answer
Answer: For the given input following would help.
func splitSegmant(prev string, cur string) string {
    if len(cur) < len(prev) || cur[:len(prev)] != prev {
        return ""
    }
    return fmt.Sprintf("%s.%s", cur[:len(prev)], cur[len(prev):])
}

func Split(lines []string) []string {
    splits := []string{lines[0]}
    for i := 0; i < len(lines); i++ {
        for j := 0; j < i; j++ {
            split := splitSegmant(lines[j], lines[i])
            if split != "" {
                splits = append(splits, split)
            }
        }
    }
    return splits
}

you may find working code here : playground
Comment: may i know what this means? cur[:len(prev)] , is the current word length output is similar to previous word length?
Comment: slice of current word upto the length of prev (here it could be any one of the previous words)

How to segment/split words in file


What is the minimum training set size required for a given number of features for document classification?

Question: For document classification problems, is there a rule of thumb for the number of training instances required for the number of terms in the vocabulary?
I am using a logistic regression classifier with TF-IDF weighted features. After stop-word filtering, stemming, and filtering by minimum and maximum document frequencies, I have a vocabulary of ~13,000 terms for a training set with ~20,000 documents. I have attempted using LDA for dimensionality reduction by adding topic probabilities as features, but this did not significantly affect performance. The performance of a classifier trained only on LDA topic probability features was inferior to the performance of the classifiers trained on TF-IDF features and TF-IDF+LDA topic probability features.
Answer: Unfortunately, I do not know of such a rule of thumb. There is an interesting discussion on the topic in David D. Thesis (1992), in section 2.3.3. I cannot copy it here because the original thesis is in PS format and I cannot copy from the PDF I link, but here you got an screenshoot:

If you follow Fuhr, and given that your limit is the number of documents (20k - I guess 20 newsgroups or Reuters-21578 dataset), you should have an upper limit of 200-400 atributes.
I suggest an alternative way, that is making use of feature selection. You can either select a  maximum number of attributes from those top scoring using a usual Information Theory quality metric like Information Gain or X-square. For instance, you can rank the words according to their Information Gain score and keep top 400 (or testing with different vocabulary sizes).
Alternatively, you can just keep those attributes (words) with an Information Gain score over 0.0 (meaning that they provide at least some predictive quality). You can use upper thresholds (0.1, etc.) to decrease the number of attributes.
In both cases, the optimal number of attributes can only be known through experimentation.
Answer: If you want to use something like plain (i.e., unregularized) logistic regression, then the argument cited by Jose stands: you need the ratio #features/#examples to be small.
However, you can do much better by using regularization. Popular forms of regularization include L1 (lasso) and L2 (ridge) regularization. If you regularize your features properly, you can get away with having many more features than training examples. In this paper, for example, using "dropout regularization" allowed us to train an efficient logistic regression model with 25k training examples and 5 million features.
Finally, if you have even fewer training examples (say, a few hundred examples and a million features), you may need to go even further and use generative models models like naive Bayes. As explained here, you may get away with having a number of training examples that grows logarithmically with the number of features.


Unity code to place object in particular position

Question: I need to place an object in a particular position using unity. May I know how to do that on code? While starting, the object wants to present in one location, after that it should go to a particular location using drag drop. After moving to that particular location, I want to show log to check whether the position is correct or not. Can anyone help me please, thanks!
Comment: [`objectReference.transform.position = XYZ`](https://docs.unity3d.com/ScriptReference/Transform-position.html)?
Comment: `objectReference.transform.position = (objA.transform.position + objB.transform.position) / 2f; Debug.Log(objectReference.transform.position)`
Comment: Actually the object want to place at between of two object and it should locked between those objects and want to give me the log.. could you help me
Comment: may i get a complete code .. im new to this
Answer: Try drag drop technique for GameObjects which highlighted in this thread: https://forum.unity.com/threads/drag-drop-game-objects-without-rigidbody-with-the-mouse.64169/
<code>using UnityEngine;
using System.Collections;

public class DragAndDrop : MonoBehaviour
{
    private bool _mouseState;
    private GameObject target;
    public Vector3 screenSpace;
    public Vector3 offset;

    // Use this for initialization
    void Start ()
    {

    }

    // Update is called once per frame
    void Update ()
    {
        // Debug.Log(_mouseState);
        if (Input.GetMouseButtonDown (0)) {

            RaycastHit hitInfo;
            target = GetClickedObject (out hitInfo);
            if (target != null) {
                _mouseState = true;
                screenSpace = Camera.main.WorldToScreenPoint (target.transform.position);
                offset = target.transform.position - Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));
            }
        }
        if (Input.GetMouseButtonUp (0)) {
            _mouseState = false;
        }
        if (_mouseState) {
            //keep track of the mouse position
            var curScreenSpace = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);

            //convert the screen mouse position to world point and adjust with offset
            var curPosition = Camera.main.ScreenToWorldPoint (curScreenSpace) + offset;

            //update the position of the object in the world
            target.transform.position = curPosition;
        }
    }

    GameObject GetClickedObject (out RaycastHit hit)
    {
        GameObject target = null;
        Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
        if (Physics.Raycast (ray.origin, ray.direction * 10, out hit)) {
            target = hit.collider.gameObject;
        }

        return target;
    }
}
</code>
Comment: The Object want to placed in particlar location for example, the object is present in position of x:0.025,y:0.491 and z:-1.79 and it want to go to position of X:-3.28,Y:-0.5 and Z: -5.32 , if the object placed in this new location means i need a log using drag drop if its on some other location means no need to show me log
Comment: To be clear, does I correctly understood behavior?
1. object in position A
2. you move it via drag/drop to point B
3. if object after moving in predefined point C then log something, else - leave object in point B without action


Can't access VNC port from local network

Question: I've installed VNC on CentOS and enabled it on port 5901.  I made sure that selinux, firewalld and iptables were disabled/stopped on the system for troubleshooting purposes.  Now I can successfully test access to port 5901 (using netcat) using localhost, but if I use the IP address, even if connecting locally, I get "connection refused":
<code># netcat to localhost works
$ nc -vz localhost 5901
Ncat: Version 7.70 ( https://nmap.org/ncat )
Ncat: Connected to ::1:5901.
Ncat: 0 bytes sent, 0 bytes received in 0.01 seconds.

# using IP doesn't work
$ nc -vz 192.168.3.57 5901
Ncat: Version 7.70 ( https://nmap.org/ncat )
Ncat: Connection refused.
</code>
Needless to say, I can't connect with a VNC client.  Does anyone have any idea of what I've missed either in my VNC configuration or firewall settings that could be causing this?  Thanks in advance.
Comment: localhost resolves to 127.0.0.1, try "nc -vz 127.0.0.1 5901"
Comment: Which VNC server?
Comment: It's tigervnc-184.108.40.206
Answer: Try running vncserver with <code>-localhost no</code>. IIRC, vncserver will only listen on localhost by default.
Comment: Thanks, this is definitely the problem, but in the latest versions VNC has is started and stopped using systemd and the vncserver command no longer works.  How would you do the same using systemd's systemctl command?
Comment: You could modify the systemd unit file - it will probably be in `/usr/lib/systemd`. However, VNC traffic is not encrypted at all, so a better approach would be for you to utilize SSH to port forward and then connect that way.
Comment: Adding "localhost=no" to the Services section of the unit file in /etc/systemd/system  enabled remote access.  Unfortunately, I'm using an IOS client which doesn't provide tunneling.  It's all on my test network, so there's no outside access.
Answer: I'm not sure which VNC server you're using, but I just tested this on CentOS 7 and it worked.
<code>$ sudo yum install -y tigervnc-server
$ sudo vncserver
</code>
Netcat will connect to that. However, in order to connect from another machine, I had to stop the firewalld service (I didn't bother opening the port).


RAID 10 not showing full capacity

Question: I am currently in the process of trying to setup a software raid using mdadm on my linux machine.
My system has 4x 8TB (all are exact same model) which I would like to put into a RAID 10.
However, after running
❯ sudo mdadm --create --verbose /dev/md/mdData --level=10 --layout=o3 --raid-devices=4 /dev/sda1 /dev/sdb1 /dev/sdc1 /dev/sdd1
mdadm: chunk size defaults to 512K
mdadm: size set to 7813893120K
mdadm: automatically enabling write-intent bitmap on large array
mdadm: Defaulting to version 1.2 metadata
mdadm: array /dev/md/mdData started.

lbslk only shows 9.7T and not the expected ~16TB of capacity on the Raid array:
❯ lsblk
NAME        MAJ:MIN RM   SIZE RO TYPE   MOUNTPOINTS
sda           8:0    0   7.3T  0 disk
└─sda1        8:1    0   7.3T  0 part
  └─md126     9:126  0   9.7T  0 raid10
sdb           8:16   0   7.3T  0 disk
└─sdb1        8:17   0   7.3T  0 part
  └─md126     9:126  0   9.7T  0 raid10
sdc           8:32   0   7.3T  0 disk
└─sdc1        8:33   0   7.3T  0 part
  └─md126     9:126  0   9.7T  0 raid10
sdd           8:48   0   7.3T  0 disk
└─sdd1        8:49   0   7.3T  0 part
  └─md126     9:126  0   9.7T  0 raid10
sde           8:64   0   7.3T  0 disk
└─sde1        8:65   0   7.3T  0 part
  └─backup  254:1    0   7.3T  0 crypt  /backup
nvme0n1     259:0    0 232.9G  0 disk
├─nvme0n1p1 259:1    0     2G  0 part   /boot/efi
├─nvme0n1p2 259:2    0    32G  0 part   [SWAP]
└─nvme0n1p3 259:3    0 198.9G  0 part   /

I already tried doing it directly with the devices (as using /dev/sd{a,b,c,d} and also tried it with partitions that span the whole hard driveces /dev/sd{a,b,c,d}1
Can anybody tell me what I am doing wrong?
Answer: I found out that the parameter --layout=o3 causes this to happen. Without it the full hdd capacity gets used as expected.
Not sure what causes this behavior though.
Comment: It's because you specified 3 copies of the data rather than 2, thus reducing your usable capacity by roughly a third. See the man page.

RAID 10 not showing full capacity


Orthonormal basis of $\{(x_1, \dots, x_n) \mid x_1+x_2+\cdots+x_n=0\}$

Question: How can we find the orthonormal basis of $\{(x_1,\dots,x_n) \in \Bbb R^n \mid x_1+x_2+\cdots+x_n=0\}$?
It is easy to find a basis, but using Gram-Schmidt procedure seems difficult to obtain an orthonormal one.
Comment: @ZackNi No...1+1+\cdots+1=n$, not zero.
Comment: Is (1,1,...,-1)/|| (1,1,...,-1)|| is an orthonormal basis.
Comment: Seems that my reply (or the method) then gives an explicit answer to the old question. Same vectors just a few sign changes. Gram-Schmidt is not necessary.
Answer: You need to find a orthonormal (sub-)basis of $n-1$ elements in ${\Bbb R}^n$ that is orthogonal to $v=(1,1,\ldots,1)$. I don't think there is a good canonical choice. Here is a simple way, though:
 \begin{align}
  u_1  &= \left( \begin{matrix}1 & -1 & 0 & 0 & \ldots & 0 \end{matrix} \right)\\
  u_2  &=\left( \begin{matrix}1 & 1 & -2 & 0 & \ldots & 0 \end{matrix}\right) \\
  u_3  &=\left(  \begin{matrix}1 & 1 & 1 & -3 & \ldots & 0 \end{matrix}\right) \\
    & ...\\
  u_{n-1}  &= \left( \begin{matrix} 1 & 1 & 1 & 1 & \ldots & -(n-1) \end{matrix}\right) \\
\end{align}
They are pairwise orthogonal and orthogonal to $v$ and you just have to normalize.
Comment: Nice solution ;) +1


Why does heroku give me this "incompatible type" error?

Question: I am trying to deploy my discord bot on Heroku.com, however i recieve a strange error...
Here's the code of the class that throws the error:
package main.Events.lavaplayer;

import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.track.playback.MutableAudioFrame;
import net.dv8tion.jda.api.audio.AudioSendHandler;
import org.jetbrains.annotations.Nullable;

import java.nio.ByteBuffer;

public class AudioPlayerSendHandler implements AudioSendHandler {
    private final AudioPlayer audioPlayer;
    private final ByteBuffer buffer;
    private final MutableAudioFrame frame;

    public AudioPlayerSendHandler(AudioPlayer audioPlayer) {
        this.audioPlayer = audioPlayer;
        this.buffer = ByteBuffer.allocate(1024);
        this.frame = new MutableAudioFrame();
        this.frame.setBuffer(buffer);
    }

    @Override
    public boolean canProvide() {
        return this.audioPlayer.provide(this.frame);
    }

    @Nullable
    @Override
    public ByteBuffer provide20MsAudio() {
        return this.buffer.flip();
    }

    @Override
    public boolean isOpus() {
        return true;
    }
}

This piece of code doesn't give me any problems while compiling with Intellij, but when i try to deploy it to Heroku they give me this error:

error: incompatible types: java.nio.Buffer cannot be converted to @org.jetbrains.annotations.Nullable java.nio.ByteBuffer
return this.buffer.flip();
Answer: flip returns a Buffer rather than ByteBuffer so a cast is needed
public ByteBuffer provide20MsAudio() {
    return (ByteBuffer) buffer.flip();
}

Comment: You can't override the return type with a less specific type.
Comment: Though I'm curious, why the Intellij compiler didn't mark this as an error and compiled everything just fine?
Comment: Eclipse (which has its own compiler) complained. IntelliJ is probably not as strict on return types...


Move Multi-lingual Content with Migrate Module

Question: I've got a single MySQL table with mixed english/french content in each row.  I'm trying to figure how to migrate this into a proper i18n configured Drupal site.
I can get Migrate to import the content into one language, but I want it to import it into both languages.  There are 901 rows, so it should ultimately create 1802 nodes that are linked.
I just can't figure out how to set up the Migrate module to loop through twice & link the nodes.
EDIT: I used this and was able to merge the two:
public function postImport() {
parent::postImport();

// $ii should really be determined by $count_query
$ii = 2000;
for ($i = 1; $i < $ii; $i++) {
  // Confirm SQL in phpMyAdmin to verify
  $query = "SELECT n.nid, tid.field_bv_transfer_id_value
    FROM {field_revision_field_bv_transfer_id} tid
    INNER JOIN node n ON tid.entity_id = n.nid
    WHERE tid.field_bv_transfer_id_value = $i;";
  $result = db_query($query);

  // Reset for each import
  $currentRowCount = $current_translateid = 0;
  foreach ($result as $record) {
    if ($currentRowCount % 2 == 0) {
      $node = node_load($record->nid);
      $node->pathauto_perform_alias = FALSE;
      $node->tnid = $record->nid;
      $current_translateid = $record->nid;
      node_save($node);
    } else {
      $node = node_load($record->nid);
      $node->pathauto_perform_alias = FALSE;
      $node->tnid = $current_translateid;
      node_save($node);
    }
    $currentRowCount++;
  }
}

}
Comment: I don't think you should use the postImport to add your translated nids, that'll mess up the migrate mapping (i.e. you won't be able to roll it back). Doing it as two separate migrate scripts within the same group would be the right way to do it, and using the 'sourceMigration' method allows you to add the tnid to the second migration to solve the question of linking the translations together.
Answer: You can create two migrations, both with the same mapping (except for the nids), but one saves nodes in English and the second in French.
Comment: True, but how do I link the two? I've got some rough code here, but I know it's possible to do it all at once. http://pastebin.com/ap1P5DGY

I think that the docs here are missing something for me - http://drupal.org/node/1132582 - in the prepareRow() what's returned? The linking can be done with postImport().
Comment: I have to do some migrate stuff tomorrow so I will take a look. I think you need to look at the mapping between the two migrations which has a record of the nids that have been imported and the original content id.
Answer: In prepareRow() you return either true or false. This determines whether that row is processed in that particular migration (and counted even).
This way, you can detect the language for each row, and only return TRUE for rows that contain content in the specific language for that migration.
so you could do something like:
public function prepareRow($row){
  $return = FALSE
  if ($row->lang == "fr"){
   $return = TRUE;
  }
  // Only rows with a source 'lang' value of 'fr' are processed
  return $return;
}

An even more performant way to do this, if you are going to do the dual migrations thing, would be to add a condition() to each source query (if you are using MigrateSourceSQL), such as ->condition('lang','en','=').
Answer: (The following applies to Drupal 7 — I don't know about Drupal 6 or before.)
I presume you want to define the relation of translation between English and French nodes.  To do that, first, each node should have the defined language, as defined in prepareRow():
$this->addFieldMapping('language', 'language_code');
$row->lang_dest = 'fr'; // or "en", depending on the row.

Second, you need to somehow define the tnid of the source-node to be its own nid and the tnid of the translation node to be the nid of the source node.  Note you can choose the random language for the source node, and so it is even acceptable to mix up the source-language between different contents.  The question is how.
(Note I think that is all you need, but I might be wrong.  I followed the steps in the second case below, and succeeded.)
If you explicitly specify the node-number (=nid) of each row in your migration, then it is easy, because you know which row corresponds to which nid, even before you import those nodes.  So, you can just set tnid of each row as such.  Obviously, you must be careful not to conflict the imported nid with any of the existing nids in the Drupal contents.
If you let Drupal decide the nid of each imported row, then it is more tricky.  I did with the 2 steps.  First, I imported all the source-language rows, adding a custom field to identify it as the source node for the later use.  Second, I imported the translated-language rows and set up all the tids of both source and translated-language nodes.  These two steps can be completely different modules, but are perhaps handier if you define those two as separate classes in the same (migration) group in the varialbe $api in your Your_ModuleName.migrate.inc.
For the second step for the translated language, I wrote as follows.
In short, it finds the source-language node with the SQL query, based on the custom field field_original_html_filename, which was defined when it was imported.
// In prepareRow()
//   Set up tnid, obtaining the nid from the node already imported.
    $this->addFieldMapping('tnid', 'row_tnid');
    //
    $field_name = 'field_original_html_filename';
    $query = sprintf("SELECT n.entity_id FROM {field_data_%s} n WHERE n.%s_value = '%s'",
                     $field_name, $field_name, $fbasename_trans);     // entity_id == nid of Node
    $result = db_query($query);
    $nid_trans = $result->fetchCol()[0];
    $row->row_tnid = $nid_trans;      // In my case, it is guaranteed there is only one candidate.

// In prepare()
//   Forcibly set up (Change) tnid of the node already imported.
  public function prepare(&$node, $row) {
    if (isset($node->tnid) && ($source = node_load($node->tnid))) {
      $node->translation_source = $source;
    }
  }

That is all.  I am not surprised if there would be an easier or better way, but it worked for me.  Anyway an advantage to set up the translations during migration is you can always rollback.  As a reference my entire migration code (for 2 languages, from the static HTML files) is available at GitHub:
https://github.com/masasakano/migrate_goo


How to create icon view to list view and vice versa switching mechanism in android

Question: I am looking to create an application where some items are showcased. Currently they are being shown in a list with title, subtitle, icon and some information. I am thinking of implementing a layout switcher here, which will enable to user to change this view to lets say icon view where they may be displayed as a grid of 3 columns. Also this switching can be animated if possible. There will be two buttons over the view, one representing list view and other icon. Clicking on any will show up the respective view. Any idea how to do that??
Answer: for list
gridview.setNumColumns(1);
and for grid
gridview.setNumColumns(2);
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes.
Comment: @Bolster, ...and where is the actual link?
Comment: Grr... It's autocommented from the review side. It's a 'answer with no explanation' issue.
Answer: You can switch the view shown in activity using setContentView() method you can call setcontentview in onClick callback.so that whole you can switch between gridview and listview.
Cheers....


Problema de compatilibidade com o Chrome e IE, texto deformado

Question: Chrome:

IE:

No mozila:

O certo seria ficar como esta no Mozilla. No chrome e no IE ele não esta certo.
Eu coloquei o texto em cima da imagem usando esse script:
CSS:
.img-containerAside{
    width: 359px;
    height: 184px;
    overflow: hidden;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: start;
    -ms-flex-pack: start;
        justify-content: flex-start;
    -webkit-box-align: end;
        -ms-flex-align: end;
        align-items: flex-end;

}

 .img-containerAside img{
   width: 100%;
   height: 100%;
   -webkit-transition: -webkit-transform .7s ease;
   transition: -webkit-transform .7s ease;
   -o-transition: transform .7s ease;
   transition: transform .7s ease;
   transition: transform .7s ease, -webkit-transform .7s ease;

}

.img-containerAside:hover img{
   -webkit-transform: scale(1.1);
   -ms-transform: scale(1.1);
      transform: scale(1.1);
}

.indexDivImagemAside{
    width: 359px;
    height: 184px;
}

 ul.noticiasIndex li h4{
  font-weight: 800;
  position: absolute;
}

HTML:
<!DOCTYPE html>

   <title>sas</title>
   <link rel="stylesheet" type="text/css" href="sis.css">

Esqueleto do homen mais azarado do mundo foi encontrado em Pompéia

Os arqueólogos acreditam que o homem estava fugindo das lavas do vulcão em busca de um lugar seguro, ele conseguiu escap...Continue lendo »

Comment: tenta montar um snippet aqui, ou no *codepen.io* para ficar mais fácil de visualizarmos o problema
Comment: @RicardoPontual Eu atualizei o script. Se vc vizualizar esse script no mozilla, chrome e IE, vai ver que o texto muda de posiçao em cada um. O certo seria fica como esta no Mozilla.
Answer: O que está faltando é um position: relative na div que abriga o texto. Para usar position: absolute, a div pai deve ter alguma position que não seja static, que é o padrão (CSS position).
Também é preciso especificar as propriedades do posicionamento (left, ou right, ou top ou bottom). No seu caso me parece ser left e bottom.
Exemplo:

.img-containerAside{
    width: 359px;
    height: 184px;
    overflow: hidden;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: start;
    -ms-flex-pack: start;
        justify-content: flex-start;
    -webkit-box-align: end;
        -ms-flex-align: end;
        align-items: flex-end;
        position: relative; /* propriedade adicionada */
        background-color: yellow; /* propriedade de exemplo */

}

 .img-containerAside img{
   width: 100%;
   height: 100%;
   -webkit-transition: -webkit-transform .7s ease;
   transition: -webkit-transform .7s ease;
   -o-transition: transform .7s ease;
   transition: transform .7s ease;
   transition: transform .7s ease, -webkit-transform .7s ease;

}

.img-containerAside:hover img{
   -webkit-transform: scale(1.1);
   -ms-transform: scale(1.1);
      transform: scale(1.1);
}

.indexDivImagemAside{
    width: 359px;
    height: 184px;
}

 ul.noticiasIndex li h4{
  font-weight: 800;
  position: absolute;
  left: 0; /* propriedade adicionada */
  bottom: 0; /* propriedade adicionada */
}

Esqueleto do homen mais azarado do mundo foi encontrado em Pompéia

Os arqueólogos acreditam que o homem estava fugindo das lavas do vulcão em busca de um lugar seguro, ele conseguiu escap...Continue lendo »

Comment: @Perfeito. Muito obrigado!


(SELECT JOIN?) Como pegar uma quantidade de registros de uma coluna especifica, de outra tabela (quando há chave estrangeira)

Question: Minha tela de listagem mostra os dados da tabela "PESSOA".
Existe uma tabela chamada MATRICULA q tem a coluna idpessoa fazendo referência.
Nessa matrícula existe um campo chamado EVADIDO pra saber se a pessoa se evadiu daquele curso que se matriculou.
Como eu faço pra saber, na minha LISTAGEM, quantas vezes essa pessoa (aluno) já se evadiu de uma matricula (curso), sendo que não tem esse campo na tabela de pessoa, somente pela tabela de matrículas.
Acho que ficou fácil de entender, meu sistema usa esse select atualmente:
SELECT pe.* FROM pessoas pe
INNER JOIN cidades ci ON (ci.idcidade=pe.idcidade)
INNER JOIN estados es ON (ci.idestado=es.idestado)
WHERE pe.removido = 'N';

Esse Inner JOIN Cidades e Estado é essencial também pois na minha listagem aparece o nome da cidade por referência por um ID (as cidades e estados são cadastrados no banco)... o mesmo pra estado.. Preciso deixar tudo isso dentro do mesmo select.
--
-- Estrutura da tabela `pessoas`
--

CREATE TABLE `pessoas` (
  `idpessoa` int(10) UNSIGNED NOT NULL,
  `idcidade` int(10) UNSIGNED NOT NULL,
  `ativo` enum('S','N') NOT NULL DEFAULT 'S',
  `removido` enum('S','N') NOT NULL DEFAULT 'N',
  `login_ativo` enum('S','N') NOT NULL DEFAULT 'S',
  `data_cad` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `nome` varchar(100) NOT NULL,
  `estado_civil` enum('S','C','D','V') DEFAULT NULL,
  `etnia` enum('B','P','N','O','A') NOT NULL,
  `data_nasc` date NOT NULL,
  `naturalidade` varchar(100) DEFAULT NULL,
  `documento` varchar(20) NOT NULL,
  `rg` varchar(20) DEFAULT NULL,
  `rg_orgao_emissor` varchar(20) DEFAULT NULL,
  `rg_data_emissao` date DEFAULT NULL,
  `nis` varchar(11) NOT NULL,
  `filiacao_mae` varchar(100) DEFAULT NULL,
  `filiacao_pai` varchar(100) DEFAULT NULL,
  `cep` int(8) UNSIGNED DEFAULT NULL,
  `endereco` varchar(100) DEFAULT NULL,
  `bairro` varchar(100) DEFAULT NULL,
  `numero` varchar(10) DEFAULT NULL,
  `complemento` varchar(100) DEFAULT NULL,
  `login` varchar(100) DEFAULT NULL,
  `email` varchar(100) DEFAULT NULL,
  `sit_ocupacional` enum('EM','DE','AU','AP') DEFAULT NULL,
  `emp_profissao` varchar(30) DEFAULT NULL,
  `emp_empresa` varchar(30) DEFAULT NULL,
  `pcd_visual` enum('BAI','CEG') DEFAULT NULL,
  `pcd_mental` enum('MEN') DEFAULT NULL,
  `pcd_auditiva` enum('SBP','SBT') DEFAULT NULL,
  `pcd_fisica` enum('AMP','1MS','1MI','CAD','NAN','AMS','AMI','OST','PAC','PAR') DEFAULT NULL,
  `vinc_empregaticio` enum('CA','AU','ME','FP','OU','NT') DEFAULT NULL,
  `pcd` enum('S','N') NOT NULL,
  `pcd_qual` enum('F','A','M','V') DEFAULT NULL,
  `pcd_grau` enum('L','M','A') DEFAULT NULL,
  `nacionalidade` varchar(100) NOT NULL,
  `escolaridade` enum('FI','FC','MI','MC','SI','SC') NOT NULL,
  `formacao` varchar(30) DEFAULT NULL,
  `sit_escolaridade` enum('C','I','T') DEFAULT NULL,
  `sit_escolaridade_curso` varchar(30) DEFAULT NULL,
  `sit_escolaridade_periodo` enum('1','2','3','4','5','6','7','8','9','10') DEFAULT NULL,
  `instituicao` varchar(100) DEFAULT NULL,
  `curso_fundat` enum('S','N') DEFAULT NULL,
  `curso_fundat_qual` varchar(200) DEFAULT NULL,
  `nr_membros_familia` int(11) NOT NULL,
  `renda_familiar` enum('1','2','3','4','5','6') NOT NULL,
  `password` varchar(128) DEFAULT NULL,
  `observacoes` text,
  `prog_federal` enum('S','N') DEFAULT NULL,
  `prog_federal_qual` varchar(200) DEFAULT NULL,
  `encaminhado_instituicao` enum('S','N') NOT NULL,
  `encaminhado_instituicao_qual` varchar(200) DEFAULT NULL,
  `telefone1` varchar(15) DEFAULT NULL,
  `telefone2` varchar(15) DEFAULT NULL,
  `ultimo_view` datetime DEFAULT NULL,
  `ultima_senha` datetime NOT NULL,
  `avatar_nome` varchar(100) DEFAULT NULL,
  `avatar_servidor` varchar(100) DEFAULT NULL,
  `avatar_tipo` varchar(100) DEFAULT NULL,
  `avatar_tamanho` int(10) UNSIGNED DEFAULT NULL,
  `sexo` enum('M','F','N') DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Estrutura da tabela `matriculas`
--

CREATE TABLE `matriculas` (
  `idmatricula` int(10) UNSIGNED NOT NULL,
  `idhorariooferta` int(10) UNSIGNED NOT NULL,
  `idpessoa` int(10) UNSIGNED NOT NULL,
  `removido` enum('S','N') NOT NULL DEFAULT 'N',
  `data_cad` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `matricula` int(8) UNSIGNED ZEROFILL DEFAULT NULL,
  `situacao` enum('M','I') NOT NULL DEFAULT 'M',
  `evadido` enum('S','N') NOT NULL DEFAULT 'N',
  `desistente` enum('S','N') DEFAULT 'N',
  `reprovado` enum('S','N') DEFAULT 'N'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Comment: @JulianoGuimaraes posta a estrutura das tabelas, para podermos usar como referencia.
Comment: Ta editado, pode conferir ^^ valeu.
Answer: Você pode usar um subselect com select count, por exemplo:
SELECT pe.*, (SELECT count(0)
              FROM matriculas ma
              WHERE ma.idpessoa = pe.idpessoa
                  AND ma.evadido = 'S') quantidade_evasao
FROM pessoas pe
INNER JOIN cidades ci ON (ci.idcidade=pe.idcidade)
INNER JOIN estados es ON (ci.idestado=es.idestado)
WHERE pe.removido = 'N';

Porem neste caso mostra quantidade de evação independente do curso, mas seria só adicionar mais clausulas no subselect de acordo com o que você precisa.
Comment: Exatamente o que eu preciso! É pra mostrar de todo os cursos mesmo! <3


Tabulation order in Display Suite

Question: Display suite (http://drupal.org/project/ds) allows you to modify the form display appliyng template layouts.
But if i chose (say) a 3 column layout, with say 6 field, the tab order is per column and not per field weight.
example:
left-----middle---right
field1 - field2 -field3
field4 - field5 -field6
if i press tab, the focus shift from field 1 to field 4, and not on field 2 as expected.
 it's possibile to set a tab order per row and/or per field weight?
Answer: You could probably do this if you use something like javascript or jQuery and using the tabindex attribute.  Take a look at the below link at Stackoverflow as an example:
https://stackoverflow.com/questions/2894539/how-to-set-tab-order-in-jquery
Comment: It would be better if you elaborate more. The answer might not be acceptable in this form.
Answer: Check out Renderable elements module.
You can also see a demo here.

Tabulation order in Display Suite


ImportError: No module named bs4

Question: I installed BeautifulSoup4 using pip in OSX but I yet get this error:
dyn-72-33-214-45:craiglist mona$ python t1.py
Traceback (most recent call last):
  File "t1.py", line 1, in <module>
    from bs4 import BeautifulSoup
ImportError: No module named bs4

Any idea how to fix it?
dyn-72-33-214-45:craiglist mona$ pip install BeautifulSoup4
....
Successfully installed BeautifulSoup4
Cleaning up...

Answer: I installed it using easy_install and now it is working. However first you should use sudo su :
dyn-72-33-214-45:craiglist mona$ sudo su
sh-3.2# easy_install beautifulsoup4

ImportError: No module named bs4


Is there a way to execute a chain of work items periodically in android WorkManager

Question: I am developing an application and have based my content fetch on WorkManager. I have a chain of work items that i want to execute periodically. My concern is that as per documentation here
I can not use a periodic work inside a chain of work items , but can I execute a chain of work items periodically ?
I have explored multiple posts but have not found the exact answer.
Comment: What if you make your *chain of work* inside your **periodic work** request?
Answer: Your PeriodicWorkRequest can in turn enqueue a chain of OneTimeWorkRequests. That's probably the best way to accomplish what you are trying to do.
Comment: The challenge in that is , i am not able to observe when the chain will finish, since the PeriodicWorkItem finished as soon as it queues up the Chain of work items, which might finish at a later point in time.
Comment: You can always tag the chain of work separately. That way you can just use getWorkInfosByTagLiveDat().


Is there a variable that keeps track of which pages are enabled or disabled in Page Manager?

Question: I'm using the Features module and I'm tired of manually enabling/disabling pages (user_edit, user_view, etc.)  Is there a variable that I can add to Strongarm to control this in code?
Comment: Where have you looked already? What have you tried?
Answer: Yes, there's a variable per page of the form "page_manager_MACHINE_NAME_disabled", eg. "page_manager_node_view_disabled". You need to set it to FALSE using Strongarm to enable the corresponding page.