Why estimate using GEEs inspite of their disadvantages over using ML?

Question: I know sometimes I want to know the population-level estimates, but the problem with GEEs is I can't calculate the likelihood, and therefore all models I make with it aren't comparable, and I don't know which model is right. For all I know what I am fitting with GEEs could be the noise rather than the true value. If models are specified differently, the entire conclusions can be different. There's Quasi-likelihood but I can't compare the quasi-likelihood to a chi-square distribution and do likelihood ratio tests with it.
Someone told me that GEEs are interpreted in the case of drug trials as if I were to give the entire population (all the people) many of whom are not sick, the drug, what kind of effect we would see.
But that would be stupid unless we're measuring clinical phase 1 trials, testing the toxicity on a generally healthy population.
Under no case would you ever want to give the drug to the entire population( that's impossible and useless and never going to happen). So why use a model that estimates what would happen if we did give the treatment to everyone on earth, the universe, and beyond?
I disagree with the contention that no model is correct; I believe there is an objectively correct model. To say no model is better than the other is to misunderstand or reject the validity of maximum likelihood and all good modeling metrics.
Why use GEEs?
I heard it's like the difference between public health and individual health. But why are the estimates of individual effects so different from population-level effects when individuals are supposed to be representative of the population level?
Answer: The GEEs have been originally proposed for clustered/grouped categorical data. Namely, when we have clustered/grouped data, it is expected that measurements within the same clusters/groups are correlated. In the case of normal data, we can go from the univariate normal distribution to the multivariate one to account for these correlations using the variance-covariance matrix of the distribution.
However, in the case of categorical data, going from a univariate distribution (e.g., Binomial of Poisson) to a multivariate one is not that straightforward as in the normal case. Liang and Zeger proposed the GEEs as an alternative. They observed that in the standard generalized linear model, the score equations contain a diagonal matrix with elements the variances of the observations implied by the family. They argued that we could replace this diagonal matrix with a full matrix containing some working correlations. The theory they next developed suggested that solving these equations would give asymptotically unbiased estimates for your coefficients, but with standard errors calculated with the sandwich formula. Moreover, the use of the sandwich estimator for the estimation of the standard errors provides protection against misspecification of the working correlation structure.
However, there is no free lunch! In case you have missing data in your outcome variable, the GEE will give unbiased estimates only when you have missing completely at random (there are extensions, such as the inverse probability weighted GEEs that will work under missing at random, but require that you correctly specify the dropout model). Also, the sandwich estimator will better protect you for misspecification of the working correlation when you have relatively few covariates that are continuous, and you have balanced data.
Comment: @Germania the consequence of small samples is that the analysis has low power. Some categorical models are biased in small sample sizes. Missing data can actually bias the analysis, in addition to having low(er) power. If 20% of a huge sample is missing completely at random, you can safely not care.
Comment: Is small sample size equally as bad as missing data?
Answer: Why use GEE (instead of Maximum Likelihood, ML)? Because the likelihood could be wrong. In fact, since we never know if it's right or not, GEEs safeguard against biases. We want results that require few assumptions. GEE's assumptions are some of the most general, hence the Generalized "G" of GEE.

... the problem with GEEs is I can't calculate the likelihood and therefore all models I make with it aren't comparable and I don't know which model is right.

You can absolutely compare nested models with the robust score or Wald tests. These results usually mostly agree with ML. Also, you never know if a model is right. Tests don't tell you that.

For all I know what I am fitting with GEEs could be the noise rather than the true value.

True of ML as well.

If models are specified differently the entire conclusions can be different.

True of ML as well.

Someone told me that GEEs are interpreted in the case of drug trials as if I were to give the entire population (all the people) many of whom are not sick, the drug, what kind of effect we would see.

This is a misunderstanding of what an "average treatment effect" is. In fact, GEE and ML agree on point estimates for independent data. Only with a repeated measures design is there a difference between individual-level and population-averaged effects. You need some critical imbalance in the design to get those different estimates. In that case, GEE does not actually estimate the desired quantity.
The main strength of GEE from a basic modeling perspective is that:

The probability model for the response is a "working model"
The data do not have to be independent or identically distributed to obtain valid inference.
The mean model does not have to be correctly specified.
Comment: @Germania A master's level statistician should have the appropriate training to identify, apply, test, and interpret longitudinal models. I think the matrix algebra is the most challenging aspect mathematically, but essential to understanding the software, output, etc. I think the best thing for you might be to back up and do some literature review, find papers where these models are proposed, fit, discussed, etc. this should give you some intuition as to how they are selected (or not) for their intended purpose.
Comment: @Germania regarding selecting the working correlation matrix in GEEs you can have a look in the QIC and in my new cvGEE package that evaluates predictive performance using proper scoring rules: https://drizopoulos.github.io/cvGEE/
Comment: So Mixed effects need independent or iid?
Comment: I was under the impression that the mean model *needs* to be correctly specified to get unbiased estimates from a GEE. Do you have a reference suggesting otherwise?
Comment: @DimitrisRizopoulos Cox & Hinkley 1974 Section 9.4: Robust Inference For Location Parameters. NB: The GEE doesn't magically recover lost info, if I fit a line to a curvillinear trend, that linear approximation is well defined, interpretable, and the robust GEE inference is correct. You must use the empirical B matrix in the calculation of the sandwich variance.
Comment: @Germania yes, mixed effects requires that the the *residuals* are IID (e.g. the difference between response and the fixed and random predictions.).
Comment: And doing likelihood ratio tests can't accurately determine whether I need the random-intercept and/or slope?
Comment: @Germania Testing for variance components is possible but the test statistic has fractional degrees of freedom. Using statistical testing to identify the mean model is biased due to unadjusted multiple comparisons.
Comment: I'm starting to lose hope in analyzing data because it seems like it's impossible to model longitudinal data correctly. If some conditions aren't met then everything is wrong. And some conditions aren't checkable with robust methods.
Comment: @Germania you could do many things for the analysis of longitudinal data, including parametric models for which you can check assumptions in various ways. You may find more info in my course notes: http://www.drizopoulos.com/courses/EMC/CE08.pdf
Comment: @AdamO but GEE in R has the option to use covariance structure like "exchangeable", "unstructured". If GEE guards against mispecification of covariance structure, then it shouldn't ask for a covar structure. And the thing about covariance structure is there exists the unstructured structure, which shouldn't that guard against mispecification? I'd rather sacrifice df to get the covar right than to use GEE which can't deal with missing data and is not updated in R and can't give me any log-likelihood
Comment: @Germania you should probably ask another question. Basically, in the GEE framework, if you specify the model *correctly*, you are rewarded with *semiparametric efficient* estimators, *incorrectly*: your estimates are still unbiased (and decently efficient). In the ML framework, specify the model *correctly* and you can asymptotically efficient estimators. Get the model wrong, and you don't have a likelihood at all. The DF don't differ between them.
Comment: @AdamO, unstructured covar pattern model uses more df than other covariance structures like AR(1). What do you use to determine correctness in GEE? Are ML frameworks, non-semi-parametric? ARe ML Frameworks parametric at all?
Comment: @DimitrisRizopoulos,  "the use of the sandwich estimator for the estimation of the standard errors provides protection against misspecification of the working correlation structure." If I'm selecting a working correlation matrix in GEEs, then am I risking mispecifying the working correlation structure even by using your cvGEE package? Do you have a cvNLME or cvGLS package for making the sure the covariance pattern model is right?
Comment: @Germania you can just look at the BIC for those. A good BIC won't tell you that it's right, but it will tell you if it fits the data. You'll never know if a corstr is "right".
Comment: We can't use BIC for longitudinal data because we don't know what n is. ln(n)k-2ln(L). What is n? The number of data points? What is that? the number of subjects*observations? The number of subjects? clusters? time points? You mean AIC? but I can't calculate p-values using AIC so LRT.


How to get divs to respond to screen resizing like imgs?

Question: In REACT, I have three divs that I would like to position side by side, separated by a small margin, and horizontally centered on the screen.
When the screen width becomes too small, I would like the right-most div to move below the first two divs, but still be horizontally centered.
When the screen becomes even smaller, I would like all three divs to be in a column in the center of the screen.
This is easy to achieve with images:
Html (the REACT flavor of html):

CSS:
#container {
    text-align: center;
}

How can this be done with objects that are not imgs?
Answer: Welcome to stack overflow, I think what you're looking for is css flexbox https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox.
#container {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
}

.childClass { // you would need to add a className to the child divs
  width: // add the width of your divs here, this will force them to wrap
  flex-grow: 0;
  flex-shrink: 0;
}

I think that should do it, but I highly encourage you to read https://css-tricks.com/snippets/css/a-guide-to-flexbox/ - it's one of the best resources on using flexbox for layouts
Answer:

//use flexbox for easy structuring html elements
.container {
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.first {
  background-color: red;
  height: 100px;
  width: 100px;
  flex-wrap: wrap;
}

.second {
  background-color: blue;
  height: 100px;
  width: 100px;
}

.third {
  background-color: yellow;
  height: 100px;
  width: 100px;
}

.flex-item {
  padding: 10px;
  margin: 1rem;
}

First div

Second div

Third div

for more info on flexbox visit here : https://css-tricks.com/snippets/css/a-guide-to-flexbox/


What's wrong with my program? It is always returning "not found"

Question: Check out my problem at:
 https://github.com/harishsambasivam/SearchingAlgorithms/blob/master/BinarySearch-RecursiveMethod.js

function BinarySearch(low, high, key, arr) {
  if (low > high) return 'Not Found';
  if (low === high) {
    if (arr[low] === key) return "Found";
    else return "Not found";
  } else {
    var mid = Math.abs((low + high) / 2);
    if (arr[mid] === key) return "Found";
    else if (arr[mid] > key) return BinarySearch(low, mid - 1,
      key, arr);
    else return BinarySearch(mid + 1, high, key, arr);
  }
}

let arr = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(BinarySearch(0, 7, 5, arr));

I expected both "found" and "not found", but only "not found" is being returned.
Answer: I think that the main problem is from your mid value calculus.
console.log(Math.abs((0 + 7) / 2)) //==> 3.5
And for the next iteration the value will be /w decimals. You can fix that first.
You can fix that by:
Math.trunc((min + high) / 2);
Comment: I think both are okay. I think we  need to drive adoption of ES6 and get browsers to improve their implementations rather than resorting to old features.
Comment: Not much sense in using an ES6 math function when an ES1 function would suffice.
Answer: You're using Math.abs when you should be using Math.floor, and that is why it's not working. Using Math.abs is pointless here since low and high are always nonnegative.

function BinarySearch(low, high, key, arr) {
  if (low > high) return 'Not Found';
  if (low === high) {
    if (arr[low] === key) return "Found";
    else return "Not found";
  } else {
    var mid = Math.floor((low + high) / 2);
    if (arr[mid] === key) return "Found";
    else if (arr[mid] > key) return BinarySearch(low, mid - 1,
      key, arr);
    else return BinarySearch(mid + 1, high, key, arr);
  }
}

let arr = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(BinarySearch(0, 7, 5, arr));
Answer: You can use other Math functions instead of Math.floor by refer this link https://stackoverflow.com/a/596503/6517783

function BinarySearch(low, high, key, arr) {
  if (low > high) return 'Not Found';
  if (low === high) {
    if (arr[low] === key) return "Found";
    else return "Not found";
  } else {
    var mid = Math.floor((low + high) / 2);
    if (arr[mid] === key) return "Found";
    else if (arr[mid] > key) return BinarySearch(low, mid - 1,
      key, arr);
    else return BinarySearch(mid + 1, high, key, arr);
  }
}

let arr = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(BinarySearch(0, 7, 5, arr));
Comment: Why are you using `Math.abs` and `Math.floor` ?
Comment: For convert float value to integer. Because in next statement value is using as array index
Comment: Why do you need `Math.abs` for that ?
Comment: `Math.abs` will use to convert negative value to positive
Comment: But the values well never be negative in this case.
Comment: Yes, the solution is not only for single selected values. In question he is asking that his program always return "Not Found" i don't think his mean to say for single value. He must be tried with many different values and he gives a sample in snippet
Answer: Here in mid value, you will get value in decimals which cannot select any arr[mid] element. So, for that, you can change the math.abs to math.floor/ math.ceil as per your requirement.


Confusion related to which transformation to use

Question: I have this confusion about which transformation to use in my data. The histogram of my original data looks like this

Now I have seen at most of the places to take log transformation in case the data is positively skewed. But when I take log transformation I get something like this
which is negatively skewed, not what I desire.

If I take square root transformation and cube root transformation I get like this

Now the data is pretty much close to normal. But I didn't get the intuition behind this. Why didn't it work with the log transformation when I see at so many places people mentioning about log transformation useful when data is positively skewed. Here square root and cube root worked.
I want to know at which condition we should use log transformation and at which condition to use cube root transformation. Suggestions?
Comment: The short answer may seem unhelpful, but it is whatever works and is valid, so long as it helps your goals.  Assuming all your values are positive, then all three transformations you've tried are well defined and it's clear that cube root works best _if it is important that you have a symmetric distribution_.
Answer: It's not clear from your question why you need to transform at all.
(What are you trying to achieve and why?)
As for why logs might make the appearance more symmetric in some cases and not others, not all distributions are the same - while log transformations may sometimes make skewed data nearly symmetric, there's no guarantee that it always does.
Often other transformations do much better.
For example logs work very nicely on lognormal distributions, while cube roots do better on gamma. Below, $a$ is simulated from a lognormal distribution, and $b$ from a gamma distribution. They look vaguely similar, but the log-transform makes $a$ symmetric (in fact, normal), while making $b$ left-skewed. On the other hand a cube root transformation leaves $a$ still somewhat right skew, but makes $b$ very nearly symmetric (and pretty close to normal):

Other times there's simply no monotonic transformation to achieve approximate symmetry (e.g. if your distribution is discrete and sufficiently skew, like a geometric(0.5), or say a Poisson(0.5), no monotonic transformation can make it reasonably normal - wherever you put them, the leftmost spike will always be taller than the next one).
Incidentally, you might want to use more bars on your histograms, and maybe consider using other displays as well, to get a handle on the distributional shape. See my cautionary tale.
Comment: Briefly why looking at the skewness doesn't help: 1. consider a shifted lognormal. No matter what the shift parameter, the skewness is the same -- but the effect of a log transform on the shape is quite different (if you shift up a lot, taking logs does very little)   2. consider a lognormal with $σ=0.164$; the population skewness is just below $0.5\,$. Now consider a gamma with shape parameter $\alpha=1$. Its skewness is $2$ -- i.e.considerably higher skewness -- but you should still take logs in the first case and something less strong in the second case (between $x^{1/3}$ & $x^{1/4}$).
Comment: Very neat answer. Would it make sense to do a skewness test on the log-transformed distribution and examine whether it is significantly lower than zero, thus a gamma GLM with log-link is preferred over simple OLS with log-transformed response?
Comment: Not to me it wouldn't. ... but to explain why in any detail would be lengthier than a comment. this should be a new question.


Is it OK to programatically access fields defined through the UI?

Question: This is a question about "best practise". I've taken over a project which I'm working on right now, and the custom modules this project comes with all access fields defined through the UI. In other words, the field names are "hard coded" in code - even though the fields are not defined in code. Is this alright?
I'm thinking that the code depends on data (in fields) which it has no guarantee will be there. Anyone could delete the fields at any time.
If you need to access fields from code, how do you make sure that the fields exist? Do you make sure that the modules define the field (programatically)?
Comment: Great question. I think you'll encounter lots of situations where you'll need to do this and you may never be 100% comfortable with the solutions. Use features and disable the UI in production, that should alleviate a lot of your concerns.
Answer: I usually use the entity_metadata_wrapper() function to create a wrapper, and deal with fields through that. But if the field doesn't exist, you can get some not-very-helpful wrapper errors.
To see if a field exists, you don't need a wrapper. You can use:
<code>if ($node->my_field) {
...
}
</code>
You can create content types in code, but nothing (except common sense) is stopping a rogue user from deleting fields after they are created. So if you are really worried about fields disappearing, you should check that they exist before using them, as above.
Comment: Thanks for your input. Even though you can check whether fields exist, is that really a good way to do it? If your'e setting up a new site, you need to configure those fields and know how the code use them? Isn't there a coupling which is just too tight here?
Comment: That's not how to check if a field exists on an entity (if it doesn't you'll get errors). You should either use `try...catch` with a wrapper, or `field_get_items` if you insist on doing it procedurally. If not at the entity level, you should use `field_info_field` and `field_info_instance` to determine existence. Fields can also be programmatically locked so they can't be deleted through the UI
Comment: @Clive : I'm thinking of doing something in the style of "locking" the fields, and I was thinking of using the Features module to do this. Modules which access fields defined in the UI could have a dependency on the configuration module produced by Features. That way, fields are locked and the modules depending on the (UI defined) fields have a declared dependency on the configuration module (which now "owns" the fields in question). I'm thinking that this could be a robust way to go about this.


Multi-target netstandard1.0 and netstandard2.0 side-by-side?

Question: When I create a multi-target .NET csproj which targets netstandard1.2, netstandard2.0 and net45, do I have to include both of the netstandard monikers in the  section of the .csproj or is it enough to just mention netstandard1.2 (the lower netstandard version)?
Proposal A:
<TargetFrameworks>netstandard1.2;net45</TargetFrameworks>
Proposal B:
<TargetFrameworks>netstandard1.2;netstandard2.0;net45</TargetFrameworks>
Answer: Yes, there is a difference between the behavior of netstandard1.x and netstandard2.x.
From Microsoft docs:

✔ DO include a netstandard2.0 target if you require a netstandard1.x target.
All platforms supporting .NET Standard 2.0 will use the netstandard2.0 target and benefit from having a smaller package graph while older platforms will still work and fall back to using the netstandard1.x target.

And one paragraph above explains the difference:

.NET Standard 1.x is distributed as a granular set of NuGet packages, which creates a large package dependency graph and results in developers downloading a lot of packages when building. Modern .NET platforms, including .NET Framework 4.6.1, UWP and Xamarin, all support .NET Standard 2.0. You should only target .NET Standard 1.x if you specifically need to target an older platform.

netstandard1.x supports 2 frameworks by using nugets, which causes the import of many packages.
Comment: Okay, you mean, if there are no preprocessor directives for 1.2- resp. 2.0-specific implementations, I can just specify netstandard1.2? That's what I thought. Someone asked me in this github issue (https://github.com/thomasgalliker/ObjectDumper/issues/31) that it is better to target netstandard2.0 too "in order to have a smaller dependency graph"... I don't understand this statement.
Comment: Using a NuGet package (ObjectDumper.NET) which defines ```netstandard1.2;net45```

- Project 1: TargetFramework: netstandard1.2
``````

- Project 2: TargetFramework netstandard2.0
``````

Now, if I install version 2.2.19015.4-pre of ObjectDumper.NET which defines ```netstandard1.2;netstandard2.0;net45```
I cannot see any difference. There is no additional NuGet package install
Answer: When I check the dependencies of both NuGet packages (1) with <TargetFrameworks>netstandard1.2;net45</TargetFrameworks> and (2) with <TargetFrameworks>netstandard1.2;netstandard2.0;net45</TargetFrameworks> I see that netstandard1.2 includes NETStandard.Library (>=1.6.1) which is probably the "depedency graph" which is described in @Baruch's answer.
ObjectDumper.Net dependencies (1)

ObjectDumper.Net dependencies (2)

To my knowledge, I can use <TargetFrameworks>netstandard1.2;net45</TargetFrameworks> if I want to support both, netstandard1.2 and netstandard2.0. A netstandard2.0 project which consumes a netstandard1.2 NuGet package references NETStandard.Library 2.0.3 (which fulfills the minimum requirement >=1.6.1). So, no unnecessary NuGet packages will be installed.


How should I deploy a webserver to Amazon EC2

Question: I am have a small website that we want to deploy to Amazon EC2. The reason is that it is cheaper than most other VPS systems, and we want to have completely custom configuration so a shared host is not a possibility. Also, the option to scale to a bigger server with the same images is one of the reasons of going for EC2.
Because we start with a t1.micro instance we will use EBS booted instances (x64_64). Our operating system of choice is Ubuntu Server. We don't compile any packages ourselve, sticking to stable packages from the repositories.
All our webserver data is stored on another EBS data volume.
Now the question: How can we best deploy our webserver, while keeping things up to data.
The options I have considered so far:

Making our own image with the all software we need installed.

Disadvantage: we have to regularly update the image to have a security updated image when we restart a server. Also, when we switch to a new version of the distribution we have to install everything againg.
Advantage: there is no time needed when starting the server for any installation procedures

Using standard Ubuntu Images, and on startup install all servers and copy all non-standard configuration files from the data disk

Disadvantages: Startup time takes longer, possibly things can go wrong with installation so error-prone
Advantages: New distribution, or updated images can be used very easily

What is the best way to do it? Are there any good options I missed, or are there any other aspects to my options that I didn't consider.
Answer: We use Fabric and libcloud to write python scripts that can call api's to spin up a server, install all the necessary software, and change configurations. It takes slightly longer every time we spin up a server than if we had a disk image, but we think the simplicity of not having to build lots of images is much better.
Make sure all these files live in your VCS (including config files) so you can essentially use that as documentation for what your configuration looks like. Then spinning up a new server can be as simple as
<code>fab create_server:server_type=webserver
</code>
Comment: Interesting concept that I will have to check out for my Amazon EC2 deployments. Thanks for sharing!  :)
Answer: Check out Chef and the hosted service from OpsCode.
Chef allows you to automate your deployment and configuration.
The chef-client runs on the server as a daemon and can upgrade packages for you, if you wish.
Fabric is great too, we use it mostly for manipulating live servers.
Answer: I created my own AMI that already has the LAMP stack and all applications installed. I keep track of any changes and then when I have enough I update the image. I have the apache, mysql, and php configuration files and mysql databases symlinked to the EBS. This allows me to not have to track those changes and they are captured when I attach a current snapshot to the new instance.


How to (ant) build a subfolder from GIT?

Question: In a Jenkins freestyle project, how to build an ant project that is in a subfolder?
With SVN, we would just check out the folder with the ant files, but now with GIT, checking out a subfolder of a repo is not supported (as per questions on this site, like this one) and I also see no option to CD into a subfolder before the ant task, or a similar option in the "Invoke Ant" step.
Comment: Consider doing a sparse checkout, if you are worried about the space that it takes to checkout a whole commit.
Answer: IMHO the linked question does show how it works with git (it suggests sparse checkouts, similar to what eftshift0 suggests in a comment or another popular Q&A about it).
But that only as an early commentary, there is an alternative to sparse checkouts working for checking out sub directories from a git repository. It works with git(1) pipelining to tar(1). Given we're talking about build systems here, it should be very likely you've got both tools at hand.
The actual git command is git-archive and this is conceptually a tarpipe.
You can specify the revision to "checkout", the path you want to "checkout" and where you want to checkout the files to (in this answer, an imaginary build/ant target directory):
git archive --format tar \
    --prefix build/ant/ \
    HEAD \
    subdirectory/path/to/check-out \
  | tar x -vf -

git archive:

--format tar use tar (tape archiver) format. required.
--prefix build/ant/ the target directory, that is where to checkout to. If not with slash (/) at the end, the first component would be prefixed by this only (so not resulting in a directory). If you're checking out into a git repository work-tree, mind that you're checking out into a git repository work-tree. The target directory will be created, incl. all necessary parents.
HEAD the revision to checkout, replace with the revision you have.
subdirectory/path/to/check-out the subdirectory you want to checkout from the repository.

tar x -vf-:

x - extract
-v - verbose, outputs the files being extracted on standard output
-f- - file to read, here - (minus sign) stands for standard input.
tip: you can replace x with t for test, that is showing all file information that would be "checked out", including the final paths.

From your question it is not fully clear to me which limitations there are next to not being able to change the working directory. With the git archive | tar pipe, you can extract to any directory, including root, however you need to manage what happens then. E.g. when I had this in an answer recently, this was over the top for the user leaving them with a chaotic state in the work-tree of their build-system, they had problems to handle it any longer. YMMV.

https://stackoverflow.com/a/76046285/367456


Users unable to view order history

Question: I have drupal 6 with ubercart
When a user clicks on View order history, it takes them to a please register or login page.
Admin can see order history just fine.
I've checked the options for
Allow customers to view order invoices from their order history in Order settings and it's set to true.
I've checked permissions and its set to allow authorized and even anonymous users to view own orders.
Yet they keep getting this strange redirect to register or login.
I'm wondering if anyone has any suggestions where else to check for the problem.
I haven't been able to find the solutions yet.
Thanks!!
UPDATE:
I just noticed what when the Admin account tries to look at another users order history
mysite.com/user/105718/orders
even admin gets please login or register.
I've triple checked permissions and its set for admin to have access to everything and for users to view their own order history. Still not working.
Comment: Have you tried rebuilding permissions? https://drupal.org/node/147961
Comment: Yeah, I've ran the rebuild permissions in the
admin/content/node-settings section, didn't have any impact.
Answer: Have you looked at the view permissions?  They override drupal core permissions.
Also, is there an order content type, or entity type?  You have to grant anon and auth users access to view their own order content type in drupal core permissions.
Answer: figured it out, apparently there used to be a order_history view or something, but it was no longer there.
So I created a new order_history view and assigned it permissions, now the order history tab on users works fine.

Users unable to view order history


Combining string (URL) with Array

Question: I am trying to scrape some data. B is the number of pages required for 1000 items to be scraped - there are 22 per page.
usernum = 1000
b = usernum.to_i/22
Array.new(b) {|b| b+1}

I have an array for the number of pages (1000/22 = 45 int.) - [1,2,...44,45] I need to scrape, with each array element pertaining to a page to be downloaded by Nokogiri. I wasn't sure how to proceed.
www.google.com&page=1
www.google.com&page=2

etc. in this case it would need to reach "www.google.com&page=45"
Is it possible to append the prefix to each item of the array? If so, does it make sense to format the array and download each page chronologically, or compile a list of the URLs in an external text file and load them into a method? I'm going to try and add threading.
Answer: Could you loop through instead of creating an array?
(1..b).each do |page|
  url = "http://google.com?page=#{i}"
  # .. fetch the page
end

Comment: Silly me... That's the way to do it! But if I'm going to multithread the scraping, do I not need to put the completed (prefix + numbered) URLs into an array?
Comment: You can create a thread within the each loop if you want a thread for each request. If you want fewer threads you might want to look at `each_slice`.

Combining string (URL) with Array


How configure Ganglia in Unicast correctly?

Question: I'm working with Ganglia, great tool by the way!
I'm trying to make this topology, with some nodes running centOS 6.4, centOS 5.9.
So for this I'm trying this configuration for GMetad (the rest is default):
##########################################################################
Head Monitor Cluster (GMetad + Gmond > mute no > deaf no + GWeb ) | centOS 6.4 (desktop)
##########################################################################
data_source "head monitor clusters" 10 192.168.1.100 # 192.168.1.100 == localhost
data_source "monitor cluster" 10 192.168.1.51:8649
gridname "Company"
authority "http://192.168.1.100/ganglia/"

##########################################################################
Monitor Cluster (GMond > mute no > deaf no ) | centOS 6.4 (minimal)
##########################################################################

globals {
  daemonize = yes
  setuid = yes
  user = ganglia
  debug_level = 0
  max_udp_msg_len = 1472
  mute = no
  deaf = no
  allow_extra_data = yes
  host_dmax = 86400 /*secs */
  cleanup_threshold = 300 /*secs */
  gexec = no
  send_metadata_interval = 5 /*secs */
}

cluster {
  name = "Monitor"
  owner = "unspecified"
  latlong = "unspecified"
  url = "unspecified"
}

/* The host section describes attributes of the host, like the location */
host {
  location = "unspecified"
}

udp_send_channel {
  host = 192.168.1.51 # send the data collect to itself
  port = 8649
  ttl = 1
}

udp_send_channel {
  host = 192.168.1.100 #send the data to
  port = 8649
  ttl = 1
}

/* You can specify as many udp_recv_channels as you like as well. */
udp_recv_channel {
  port = 8649
}

/* You can specify as many tcp_accept_channels as you like to share
   an xml description of the state of the cluster */
tcp_accept_channel {
  port = 8649
}

##########################################################################
Node (Gmond > mute no > deaf yes ) | centOS 5.9 (minimal)
##########################################################################

/* This configuration is as close to 2.5.x default behavior as possible
   The values closely match ./gmond/metric.h definitions in 2.5.x */
globals {
  daemonize = yes
  setuid = yes
  user = ganglia
  debug_level = 0
  max_udp_msg_len = 1472
  mute = no
  deaf = yes
  host_dmax = 86400 /*secs */
  cleanup_threshold = 300 /*secs */
  gexec = no
}

cluster {
  name = "Monitor"
  owner = "unspecified"
  latlong = "unspecified"
  url = "unspecified"
}

/* The host section describes attributes of the host, like the location */
host {
  location = "unspecified"
}

/* Feel free to specify as many udp_send_channels as you like.  Gmond
   used to only support having a single channel */
udp_send_channel {
  host=192.168.1.51 #send to monitor cluster
  port = 8649
  ttl = 1
}

/* You can specify as many udp_recv_channels as you like as well. */
udp_recv_channel {
#  mcast_join = 126.96.36.199
  port = 8649
#  bind = 184.108.40.206
}

/* You can specify as many tcp_accept_channels as you like to share
   an xml description of the state of the cluster */
tcp_accept_channel {
  port = 8649
}

And that's it.
But this configuration it's not working, I already setup 9 virtual machines to make this work out, but nothing so far.
I disabled iptables, ip6tables and selinux. I'm working on this for 3 day and night and nothing seems to work..
I would like some help in this, please, please, I beg for help. I really don't understand why this configuration ain't working, after read so many tutorials and O'Reilly book about Ganglia. Any idea ? Or help ?
And yes, if I do :
from 192.168.1.100 8649
telnet 192.168.100 8649, the whole data collected is displayed.
The same thing to 192.168.1.51, from 192.168.1.100, but this one do not display in the Ganglia Web.
The charts, of it,  are always -nan.
Any idea ? Thank you!
Comment: what's 'gstat -a' on the gmetad instance return?  I had problems with Unicast initially by allowing TCP traffic on 8649 but not allowing UDP, but it sounds like you've disabled your firewall already.
Answer: I was able to fix the problem.
For some reason ganglia-gmond that came with centOS 5.* is gmond-3.0.7 which came with EPEL package, but I added rpmforge repository and could found out the version 3.1.7 which seems to support the unicast configuration, now everything is working fine.
Thank you!


Insert multiple Mysql record using Array

Question: i have an array of company name, i insert each company name as separate record.below is the code
<input type="text" name="company_name[]">

$company_name = $_POST['company_name'];

 if($company_name)
 {
    foreach($company_name as $company)
    {
    $mycompany[] = $company;
    }
 }

$val="('".implode("'), ('",$mycompany)."')";
$sql = "INSERT INTO `table`
 (`company_name`) VALUES ".$val."";

The above query look like this and it successfully inserted 2 records in table.
INSERT INTO `table` (`company_name`) VALUES ('DELL'), ('IBM')

Now the problem is that with every company_name there is a company_code which i want to insert with each record and there is 3rd values lets suppose order_num which i also want to insert but the order_num should be same in all records,i need the query below
INSERT INTO `table` (`order_num`,`company_name`,`company_code`) VALUES ('123','DELL','axc89'), ('123','IBM','bxc90')

Comment: get comapny code same as company name
Comment: where company code goes from?
Comment: and why do you need company code and name? can't it be only code?
Comment: @Col.Shrapnel i edit my code plz check it, and i m making a very complex online order form so thats y i need both company_code & order_num
Comment: WHERE DO YOU GET THE COMPANY CODE?
Answer: Okay, at last you endeavored to produce something understandable
1) This this code is absolutely useless:
$company_name = $_POST['company_name'];

 if($company_name)
 {
    foreach($company_name as $company)
    {
    $mycompany[] = $company;
    }
 }

as $mycompany being an exact duplicate of $company_name
2) To get your "very complex" query
foreach($_POST['company_name'] as $key => $value)
{
    $name = mysql_real_escape_string($value);
    $code = mysql_real_escape_string($_POST['company_code'][$key]);
    $mycompany[] = "(123,'$name','$code')";
}
$sql  = "INSERT INTO `table` (order_num,company_name,company_code) VALUES ";
$sql .= implode(",",$mycompany);

Comment: Not my problem.`"get comapny code same as company name"` - so I did.
Comment:

$company_name = $_POST['company_name'];
$company_code = $_POST['company_code'];

yes sure its same but i don't know y its not working
Comment: go on fix it. this is not do-my-job-for-free site. this is Q&A site. you've got the answer. go finish the job.
Comment: see if $_POST['company_code'] contains anything. if not - check the spelling.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/8490/discussion-between-arif-and-col-shrapnel)
Answer: INSERT INTO `table` (`order_num`,`company_name`,`company_code`) VALUES ('123','DELL','axc89');
INSERT INTO `table` (`order_num`,`company_name`,`company_code`) VALUES ('123','IBM','bxc90');

You can use an array
$arrray_to_be_inserted=array
(
   [0]=>array('123','DELL','axc89'),
   [1]=>array('123','IBM','bxc90')
);

Comment: i know the query but i want it through php code like i did for 1 record, now i need it for inserting 3 records
Answer: Instead of passing value to a new variable in foreach , try to access as $key and $value, try this and see if it can help you
<?php

$company_name = array("DEL","IBM");
$company_code = array("1","2");
$order_num = array("4","5");

if($company_name)
 {
foreach($company_name as $key => $value)
{
    $mycompany[] = $value;
    $mycompanycode[] = $company_code[$key];
    $myordernum[] = $order_num[$key];
}
}

?>
Just make sure names and their values are corresponding to each other .
Comment: explain the reason for 1 down


Visual Studio 2019 Installer doesn't start

Question: I'm using Windows 10 ver. 1909.    Installer hangs or does nothing.   No feedback.
Comment: When I tried to install with cmd command for offline installation its working but I want to install it with normal installer.
Comment: Where did you get the installer from?
Comment: from official website
Answer: In my case, the issue was that I have downloaded and launched the installer to a user folder that contains non-English characters. Moving the installer to another folder fixed the issue. I´ve diagnosed the issue by looking into an installer log file in C:\Users<username>\AppData\Local\Temp\dd_vs_professional__143315035.1628536728_decompression_log.txt.
Answer: I had exactly this problem.   Same version of Windows 10.  I tried both vs_community.exe and vs_professional.exe.  On a Microsoft Surface Pro 4.  The installer launches, a brief unpacking screen appears, that vanishes, and you're left with the task manager showing the installer but no user interface. I tried numerous different suggestions from Googling as well as the Collect.exe tool.  None of that helped.  Someone had a similar problem that hinted that a display could cause the problem.   My Surface had Duet installed, which allows you to use an iPad as a second monitor.   Uninstalling that allowed Visual Studio to install normally.  Apparently the Visual Studio installer is finicky about displays so if you have any unusual display drivers, or screen sharing utilities, they should be removed to allow installing.   I suspect that the driver or utility could be put back after installation.
Comment: Same here - I was connective via RemotePC and when I hooked up a monitor - there was a window that Remote PC was not showing.
Comment: Using the command line to install vs build tools may circumvent the monitor issue. See Visual Studio Build Tools 2019 Silent Install (How-To Guide) at https://silentinstallhq.com/visual-studio-build-tools-2019-silent-install-how-to-guide/. It didn't work in my case, though.
Answer: At first you need to download this tool Event Collect for visual studio, open your CMD as administrator,then run Collect.exe , after that you need to run your visual studio installer in the event of an error you will find and file named C:\Users{username}\AppData\Local\Temp\VSSetupEvents.txt that you can check to see the error messages.
For more details you can check documentation .
Comment: [4/12/2020, 10:28:25] The entire Box execution exiting with result code: 0x0

[4/12/2020, 10:28:25] Launched extracted application exiting with result code: 0x138a
Comment: @pybll did you find VSSetupEvents.txt file
Comment: @pybll do you another version of visual studio installed ?
Comment: no i didn't install before any version of vs on this pc
Comment: you can install VS2019 off line , you can follow the instruction in the link https://learn.microsoft.com/fr-fr/visualstudio/install/create-an-offline-installation-of-visual-studio?view=vs-2019
Comment: I said already I could download it offline but I want to solve this problem.
Comment: probably you should report the problem to microsoft team https://learn.microsoft.com/en-us/visualstudio/ide/how-to-report-a-problem-with-visual-studio?view=vs-2019
Answer: My case is very embarrassing for Microsoft. I downloaded Visual Studio Setup and started it right away from browser. It was opened and then immediately closed. Nothing I could read on the Internet about this problem was not helping. Then I did one very simple thing. Moved setup from original location: C:\Users(user name)\Downloads, to c:\Temp -> worked like a charm. The thing is that my user name contains international characters (plus containing a space). All in all 21. century, full unicode support everywhere, but not in windows. Really embarrassing.
Comment: If you have any spaces on your username, the setup crashes. This method worked for me, thanks for sharing.
Answer: Visual Studio 2019 Installer doesn't start
I lost time about something I shouldn't have, I couldn't install vscode studio 2019 (I've installed it on multiple machines before).
I don't know exactly why, observed there might be something in my folder blocking it, I just moved it to a new folder and I could install. Good luck and don't make the same mistake as me
Answer: And in my case, with both 2015 and 2013 installers on a Win 7, I had my user's folder not in C:\Users\ but on a netdisk. Which made it so that the installer would not run at all, no matter where I was running it from.
Creating a second user with their home folder on C:\ solved the problem.
That's Microsoft for you. Over 40 years of spearheading personal computing.


Is it possible to deduce type conversion to templated type in C++?

Question: I want to create a class which is implicitly convertable to another class with template parameter. Here is MCE of what I want to achieve:
#include <iostream>

template <typename T>
class A {
    T value;
public:
    A(T value) {this->value = value;}
    T getValue() const {return value;}
};

class B {
    int value;
public:
    B(int value) {this->value = value;}
    operator A<int>() const {return A(value);}
};

template <typename T>
void F(A<T> a) {std::cout << a.getValue() << std::endl;}

void G(A<int> a)  {std::cout << a.getValue() << std::endl;}

int main()
{
    B b(42);

    F(b);           // Incorrect
    F((A<int>)b);   // Correct
    G(b);           // Also correct
}

Is it possible to make F(b) example work if both class A and void F are library functions and can't be modifyed?
Comment: Nope. Calling `F` like you do means template argument deduction. Which in turn means conversions are not considered. You may call `F(b)` however.
Comment: Depending on the design and use-cases, maybe make `B` inherit from `A` instead? Possibly using `private` inheritance?
Answer: This:
F(b);

requires template argument deduction. As a result, it won't do what you want.
Try passing explicitly the argument template, like this:
F<int>(b);

since you provide a () operator in class B.


(Mutators ou Middlewares) Qual seria o ideal utilizar na hora de converter uma string antes de inserir no banco de dados no laravel?

Question: Qual seria mais recomendado utilizar na hora de manipular uma string que nesse caso seria o (,) para o (.) na hora de inserir um valor na base de dados (MySQL) do tipo decimal no Laravel?
1 - Utilizando um middleware customizado
class convertCommaInDot extends TransformsRequest
{

    protected function transform($key, $value)
    {
        return str_replace(',','.',$value);
    }
}

Chamando o middleware no arquivo route/web.php
Route::post('/numeros/add', 'NumeroControlador@store')->name('number.store')
    ->middleware('CommaInDot');

OU
2 - Utilizando o mutator setNumeroAttribute($value), nesse caso não necessita utilizar o middleware.
class Numero extends Model
{

    public function getNumeroAttribute($value)
    {
        return $this->attributes['numero'] = str_replace('.',',',$value);
    }

    public function setNumeroAttribute($value)
    {
        $this->attributes['numero'] = str_replace(',','.',$value);
    }
}

Ambos geram o mesmo resultado ou seja, eu insiro no formulário um numero 1,23 e automaticamente o valor é transformado para 1.23
Comment: Mutator é para alterar dado; middleware é para lidar com mensagens HTTP. Então, mutator é a resposta.
Comment: @VirgilioNovic Eu utilizo o laravel 6.
Comment: Igor por curiosidade esse TranformesRequest é um pacote?
Comment: Na versão 6 existe `middleware` que tira espaço de texto, por exemplo, então, eu vejo assim qual é a melhor forma vai depender porque o `framework` abriu uma brecha ! a sua versão é a 5 ou 6 (especifica certinho)
Comment: @VirgilioNovic Sobre o TransformsRequest, ela é uma classe que o Laravel utiliza para criar o middleware ConvertEmptyStringsToNull.
Comment: Sim acabei achando ... eu acho que a sua pergunta pode ser feita das duas formas o Laravel tem isso, mas, claro que com configurações e um código apropriado
Comment: Obrigado pela resposta @AndersonCarlosWoss , agradeço.
Comment: @VirgilioNovic hm, entendi, obrigado por colaborar mano!!
Comment: Porque assim Igor essa middleware você pode fazer por rotas (verbo `post`,`put`) onde essa rota tem dados que serão formatados/validados a sua maneira. (é uma ideia inicial, estou na rua, mas, a noite vou dar uma olhda)
Answer: Como eu gosto sempre ter uma ideia sobre o que cada coisa faz eu resolvi fazer um exemplo, o middleware que herda da classe TransformsRequest tem uma função global que é executado na pilha geral de middleware da aplicação laravel.
Inclusive esse tipo de middleware é chamado no array global:
class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

e esse middleware não deve ser configurado nas rotas porque a sua função como citado é global.
Para o seu problema, não deveria ser usado, porque, ele confere cada item enviado na sua requisição e se for satisfeito a troca de ponto por virgula, é feito em todos os campos que fazem parte dessa regra e isso não é bom, já pessou ter um nome com ponto, exemplo Stack.OverFlow ele vai substituir sumariamente por virgula ficando Stack,OverFlow e não é isso que você quer, você só precisa mudar onde for número com virgula, então, TransformsRequest só deve ser usado quando essa mudança ocorrer em todos os valores enviados na sua requisição, que no laravel atual versão 6 (até essa data) tem dois TransformsRequest globais que são:

TrimStrings.php
ConvertEmptyStringsToNull

No seu caso é melhor utilizar Eloquent: Mutators igual está na sua pergunta com uma mudança no seu código para verificar também milhar e deixar o valor original sem mudança, somente traga a mudança quando for resgatada, exemplo:
class Numero extends Model
{
    public function getNumeroAttribute($value)
    {
        return str_replace(['.',',']],['','.'], $value); // mudança aqui.
    }
    public function setNumeroAttribute($value)
    {
        $this->attributes['numero'] = str_replace(',','.', $value);
    }
}

Referencias

Eloquent: Mutators
TransformsRequest
TrimStrings.php
ConvertEmptyStringsToNull
Comment: Hm... , então pelo que eu entendi, o uso do TransformsRequest é válido apenas para middlewares globais que é o caso do  TrimStrings e ConvertEmptyStringsToNull, e que no meu caso não seria interessante,  já que o meu objetivo era aplicar em rotas específicas, e que nesse caso o mais recomendado seria o Mutator. Obrigado pela resposta
Comment: é que o `TransformsRequest` seria para todos os itens da requisição, eu não acho válido então para trocar valores monetários ...
Comment: @IgorAC se for útil sinalize como resposta da sua pergunta


Solving system of ordinary linear differential equation

Question: I want to solve the following system of differential equations
$$\dot x_0(t)=-ax_0(t)+\mu x_1(t)$$
$$\dot x_n(t)=(\lambda(n+1)+a)x_{n-1}(t)-(a+(\lambda+\mu)n)x_n(t)+\mu(n+1)x_{n+1} \qquad \forall n\geq 1.$$
To do this I wanted to calculate the matrix exponential $\exp(tA)$ where A is the matrix associated with the given system. Unfortunately I wasn't able to do this. Is this even the right strategy?
Answer: I don't know the origin of your set of equations, but an infinite dimensional dynamical system smells a lot like a PDE to me. As it turns out, you can convert the above to a (linear!) PDE as follows. Introduce
\begin{equation}
y(z,t) = \sum_{n=0}^\infty x_n(t)\,z^n.
\end{equation}
The recursive relation you posted is equivalent to demanding that $y$ satisfies
\begin{equation}
 \frac{\partial y}{\partial t} = \left(z(\lambda+a)-a\right)\,y + (1-\lambda-\mu)z \frac{\partial y}{\partial z} + \mu \frac{\partial y}{\partial z},
\end{equation}
if I haven't made any mistakes. This linear first order PDE can now be solved using the method of characteristics. The series expansion of the solution in powers of $z$ will give you $x_n(t)$; to find a specific $x_n$, calculate $\frac{1}{n!}\frac{\partial^n y}{\partial z^n}(0,t)$. FYI: This could be called the 'generating function approach'.


flutter More than one file was found with OS independent path 'AndroidManifest.xml'

Question: I have a sample flutter project that has multiple lib modules that can build with
./gradlew app:assembleDevRelease

but for some reason when I run
flutter run --release --flavor dev

It is trying to run
./gradlew assembleDevRelease

command that of project level, then I got the error
> Task :track_sdk_plugin:mergeDevReleaseJavaResource FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':track_sdk_plugin:mergeDevReleaseJavaResource'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > More than one file was found with OS independent path 'AndroidManifest.xml'

Any idea why this is not working? Can provide the gradle file if needed.
Answer: In my case, there were more than two AndroidManifest.xml files in one of the modules due to migrating from the old project.
Please search for the AndroidManifest.xml files under your project directory, if you could find there were more than one in src folder, only keep the one in src/main folder.
Answer: I had a similar case with the following error message:
More than one file was found with OS independent path 'lib/x86/libswscale.so'.

The problem was that I accidentally had both the following dependencies in my pubspec.yaml:

ffmpeg_kit_flutter_min_gpl: ^4.5.0
ffmpeg_kit_flutter: ^4.5.0-LTS

The top one of course has everything that the below one has and that caused the issue. The below one was unnecessary.


How To Give Input In Python Selenium In WordPress

Question: I want to select one of this category in my WordPress website through input how I can do that please help thanks in advance
16 gb ram games
category16gbgames = driver.find_element(By.XPATH, '//*[@id="in-category-11"]')
category16gbgames.click()

256 mb ram games
category256mbgames = driver.find_element(By.XPATH, '//*[@id="in-category-9"]')
category256mbgames.click()

512 mb ram games
category512mbgames = driver.find_element(By.XPATH, '//*[@id="in-category-7"]')
category512mbgames.click()

1 gb ram games
category1gbgames = driver.find_element(By.XPATH, '//*[@id="in-category-17"]')
category1gbgames.click()

8 gb ram games
category8gbgames = driver.find_element(By.XPATH, '//*[@id="in-category-10"]')
category8gbgames.click()

4 Gb Ram Games
category4gbgames = driver.find_element(By.XPATH, '//*[@id="in-category-15"]')
category4gbgames.click()

2 Gb Ram Games
category2gbgames = driver.find_element(By.XPATH, '//*[@id="in-category-16"]')
category2gbgames.click()

Action Games
actiongames = driver.find_element(By.XPATH, '//*[@id="in-category-12"]')
actiongames.click()

Please help how to select one category through input in python selenium
Comment: Can you provide resource, so we are able to help you?
Answer: you can simply use f-string to take the user input for the categories.
game_category = input("choose the category: ") # in-category-9, in-category-11

driver.find_element(By.XPATH, f'//*[@id="{game_category}"]').click()

or
game_category = input("choose the category: ") # 9, 11, ........

driver.find_element(By.XPATH, f'//*[@id="in-category-{game_category}"]').click()

Comment: I'll go with the first approach. In the second you may need contains.
Comment: it is not working sir unable to locate element
Comment: well, I would be able to help you better if you could provide more details.


QFormLayout expands column of QGridLayout

Question: I am creating a QFormLayout with some items like this:
QFormLayout *tableLayout = new QFormLayout();
QLineEdit *line1 = new QLineEdit();
QLineEdit *line2 = new QLineEdit();

tableLayout->addRow(tr("LineText1 "), line1);
tableLayout->addRow(tr("LineText2 "), line2);

After that I try to add this Layout to a QGridLayout like this:
QGridLayout *layout = new QGridLayout();
QPushButton *btn1 = new QPushButton();
QPushButton *btn2 = new QPushButton();
layout->addWidget(btn, 1, 1, 3, 3);
layout->addWidget(btn2, 1, 4);
layout->addLayout(tableLayout, 2, 4);

After I added the tableLayout, btn1 as width as 1 column and the tableLayout is as width as 3 columns.
I already tried to put the QFormLayout into a own widget and add the widget to the QGridLayout. But it didn't changed anything. The way I am doing that is the following:
QFormLayout *tableLayout = new QFormLayout();
QLineEdit *line1 = new QLineEdit();
QLineEdit *line2 = new QLineEdit();

tableLayout->addRow(tr("LineText1 "), line1);
tableLayout->addRow(tr("LineText2 "), line2);

QWidget *widget = new QWidget();
widget->setLayout(tableLayout);

QGridLayout *layout = new QGridLayout();
QPushButton *btn1 = new QPushButton();
btn1->setText("btn1");
QPushButton *btn2 = new QPushButton();
btn2->setText("btn2");
layout->addWidget(btn1, 1, 1, 3, 3);
layout->addWidget(btn2, 1, 4);
layout->addWidget(widget, 2, 4);

What is the reason for this strange situation? And how to solve it?
Here is a picture of the result:
And here is wat I want to have:
Comment: You can add expanding (size policy) widget instead tableLayout, and set tableLayout for this widget. Chain like this: layout->widget->tableLayout
Comment: Apart from the typo, the code does exactly what it is told to: `btn1` on the first row spanning 3 rows and 3 columns, `btn2` on row 4 with the form layout right next to it. So, what is the problem exactly?
Comment: @scopchanov You are right this way it does what it is aspected to do. In my example I mixed the row and the column of `addWidget`. I am sorry for that. I changed it now.
Comment: @Ahrtaler you say: *I already tried to put the QFormLayout into a own widget and add the widget to the QGridLayout. But it didn't changed anything.*. you could place the code you are using to do that, we call that [mcve], it would also be interesting to show an image of what you get and what you want to obtain.
Comment: @eyllanesc Yes I will do that please wait a minute
Comment: @Ahrtaler what you want to obtain?
Comment: @eyllanesc Now I added picture of what I want to obtain
Answer: To build the design you want the first thing is to establish the position of the elements, remember that the position of the rows or columns start at 0, not at 1 as you do. The second part is to set the size policies, some widgets already have some established policy such as the QPushButton that stretches horizontally but not vertically so even if the rowSpan is large it will not change the height of the button, so we must change that behavior and finally the stretch.
#include <QApplication>
#include <QFormLayout>
#include <QLineEdit>
#include <QPushButton>
#include <QSizePolicy>
#include <QWidget>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWidget w;

    QGridLayout *layout = new QGridLayout(&w);

    QPushButton *btn1 = new QPushButton("Btn1");
    btn1->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);

    QPushButton *btn2 = new QPushButton("Btn2");
    btn2->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);

    QFormLayout *tableLayout = new QFormLayout();
    QLineEdit *line1 = new QLineEdit();
    QLineEdit *line2 = new QLineEdit();
    tableLayout->addRow("LineText1 ", line1);
    tableLayout->addRow("LineText2 ", line2);

    layout->addWidget(btn1, 0, 0, 3, 3);
    layout->addWidget(btn2, 0, 3);
    layout->addLayout(tableLayout, 1, 3);

    // column 0 x3
    layout->setColumnStretch(0, 3);
    // column 3 x1
    layout->setColumnStretch(3, 1);

    w.resize(640, 480);
    w.show();

    return a.exec();
}

Note that the QFormLayout will make the widgets always on top, so it will not necessarily occupy the height of the space offered by the QGridLayout.
Comment: Thank you very much! I totaly misunderstood the QGridLayout. I always thought, it is a even grid. And If you want to make one element bigger you have to add more columns and rows. But it is much better to use this way. Thank you that you spend so much time for me.


Recognizing downwards intervals by humming corresponding upwards interval - bad practice?

Question: Originally I tried to recognize intervals by ear through the use of songs (e.g. m3 = first two notes in Greensleeves). This worked until I got to m6-M7, where the songs I had for downwards intervals didn't really stick. So I started recognizing them by humming out the downwards interval, then the upwards one back to the first note (e.g. m6: C-E-C).
This is working, but it feels like a 2 step process, when I should actually try to recognize them right away (e.g. m6: C-E). Am I handicapping myself with this method? Or will I eventually start to recognize the downwards intervals without having to go back up?
Answer: Eventually, if you keep practicing, all intervals will be obvious to you without having to relate to a song. At least by then it will not matter.
I was taught (for some really tricky non-tonal sight singing ear training exercises) to use all tricks I could think of to find the next note. Suggested tricks included such as

humming scale steps up or down to the next note to sing,
humming, for the context, an easy interval - such as perhaps a fifth - and finding the tricky note some major or minor second interval from there, or adding/subtracting two intervals - perhaps an octave and a third - to find the next (tricky) note,
relating the next (tricky) note to a previous note still in your ear memory instead of the last one.

In time less and less tricks will be needed. So in conclusion I think that whichever tricks that help you on your way are valid. So by all means do your two-step trick for now. However you should consider trying to eliminate the extra step as a good exercise in order to progress!
Comment: That first method was the one I've been using for the ascending 6th and 7ths. I can recognize a perfect 5th and an octave, so I'd hum up or down until I found it. I think that's the best trick I've heard. It also feels like it helps you develop an ear for both the interval you're hearing, and the adjacent ones you're going through until you get to your comfortable interval.
Answer: Bearing in mind that each interval going up has a 'partner' the other way, it won't matter. For example, your maj. 3rd of C-E is 'opposite' to the min.6th that E-C gives. The perfect 4th of, say, A-D is 'opposite' to the perfect 5th of D-A. So you could say that you only have to learn half as the examples show.
You should be able to sing up and down intervals.The general rule will involve the number 9. (maj 3-min.6 etc.)
Comment: Yes! The sum makes 9, minor becomes major and vice-versa, diminished becomes augmented and vice-versa, perfect stays perfect. Very helpful for 6ths and 7ths :)
Comment: Yep, it always works.Obviously the rule of 9 will only work within an octave though...
Comment: That's an interesting trick. So for example: if you're trying to recognize a descending A-D (P5), you could find the corresponding ascending A-D (P4) to the next D note. Is that right?
Answer: I think it's ok. Besides, relying on songs to remember intervals is a two step process as well: you recognize the song, than the interval. However, as you progress you won't need to rely on the songs anymore, and you'll be able to instantly get the right answer.
I also think it's ok to cheat for a while and sing the intervals backwards if it helps you. As long a you keep practicing, no matter how much you cheat the intervals will start sticking in your memory eventually.
Answer: Any trick you can use to find the right note is fine.  As you practice, you will "memorize" the correct notes, and use the tricks less and less.
It's like when you were learning arithmetic as a kid.  There are tricks that you learn when you need to multiply by 5, for example, such as counting by 5s and using your fingers.  Eventually, you do enough math problems that you just remember that 7 x 5 = 35.


How to filter JSON dictionary in SwiftyJSON

Question: I'm using SwiftyJSON to get a list and printing it out to a TableView.
My issue is I can't filter this dictionary, I tried to make a for loop to remove the unwanted elements (or even pushing a new element), but I couldn't find a way to remove or pushing an element with a JSON type that SwiftyJSON provides.
var FilteredTripList:JSON = TripsList
for (key: String, Trip: JSON) in TripsList {
    if String(stringInterpolationSegment: Trip["TripFrom"]) != SearchFilter["From"]!
    || String(stringInterpolationSegment: Trip["TripTo"]) != SearchFilter["To"]! {
            // I'm hoping for something like the line below
            // FilteredTripList[key.toInt()!].remove()
        }
    }
}

Comment: What type is your TripsList? is it a JSONArray? Or a JSONObject? Because your for loop is for JSONObjects which are key based... JSONArrays are index based... So I need to know what type TripList is?
Comment: It's JSON from SwiftyJSON
Comment: Yes, that it is a JSON is clear, but is it a JSONArray, or a JSONObject? It only can be one of those types?
Comment: How can I know? The variable made by Alamofire
The code is: Alamofire.request(.GET, url, parameters: parameters)
  .responseJSON
Comment: Could you NSLog the responded JSON from your request, and post it in here? If I see the JSON, I can tell you what to do next
Comment: Also, is it a requirement to use SwiftyJSON? Or ist it ok if I write you a simpler Class that you can query easily? As I see in your Profile, you have multiple unsolved Questions... If you want to, post me your, or an eMailAdress, I will send you an eMail and we can clear this problems?
Comment: Oh, I got it, it's JSON array, thanks man I can make the custom class but I have a deadline, I was just wanted to make sure that SwiftyJSON array doesn't have remove function, I guess I will just make a for loop to put the JSON into a NSMutablearray or something
Comment: Alright, yes thats a good idea...
Answer: I don't know swifty json, because I always use the native way with NSJSONSerialization... So I have to guess
Please change this line
FilteredTripList[key.toInt()!].remove()

To this line
FilteredTripList.removeValueForKey(key)

And write me what happened
Comment: Nope, tried those, not working. I need something works with SwiftyJSON
Answer: Try something like this:
FilteredTripList.dictionaryObject?.removeValueForKey(key.toInt()!)

It should work.
Answer: For me, the best way to filter the [JSON] was doing this:
        self.places = self.locals.filter({ (json) -> Bool in
            return json["monthlyPurchasesLocalCount"].intValue > 0;
        });

Answer: Try with the below code snippet if you are using SwiftyJSON,
it works perfectly for me. I got it after a lots of tries.
let jsonObj = some JSON
let jobj = jsonObj.arrayValue
if !jobj.isEmpty {
   let j = jobj.filter({ (json) -> Bool in
       return json["country"].stringValue == "US"; })
   print ("filterdData: \(j)")
}

Note: jobj should be .arrayValue, otherwise it won't work.


Deny access to routes in Angular js 2

Question: I have a file with the routes and wanted to deny access to some when the user does not have the login done ,how can i do this?
my routes
import { provideRouter, RouterConfig }  from '@angular/router';
import {SymfonyComponent} from './symfony.component';
import {Symfony2Component} from './symfony2.component';
import {Symfony3Component} from './symfony3.component';
import {LoginComponent} from './login.component';

const routes: RouterConfig = [
  {
    path: 'all',
    component: SymfonyComponent
  },

  {
    path: 'one',
    component: Symfony2Component
  },
   {
    path: 'post',
    component: Symfony3Component
  },
  {
    path: 'login',
    component: LoginComponent
  },
];

export const appRouterProviders = [
  provideRouter(routes)
];

Comment: https://angular.io/docs/ts/latest/guide/router.html#!#guards
Answer: You can do this with Angular2's AuthGuard, check out this AuthGuard documentation.
Here is an example of its use in app.routes.ts:
import {AuthGuard} from './app/common/guards/auth.guard';
import {HomeComponent} from './app/home/home.component';

export const Routes : RouterConfig = [{
            path: 'home',
            component: HomeComponent,
            canActivate: [AuthGuard]
        }]

Then you need to create a guard, it'll look something like this:
import {Injectable} from '@angular/core';
import {CanActivate, Router} from '@angular/router';
import {FooAuth} from 'foo';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class AuthGuard implements CanActivate {
constructor(
    private _fooAuth: FooAuth,
    private _router: Router
){}
canActivate() : Observable<boolean>{
    return this.isAllowedAccess();
}
private isAllowedAccess() {
    if(!this._fooAuth.currentSession) {
        this._router.navigate(['/login']);
        return Observable.of(false);
    }
    return Observable
        .fromPromise(this._fooAuth.validateSession(this._fooAuth.currentSession))
        .mapTo(true)
        .catch(err => {
            this._router.navigate(['/login']);
            return Observable.of(false)
        });
}

Once you set up the guard, you can add canActivate: [AuthGuard] to each route and it will check your auth logic each time you change routes.
(your auth logic will vary depending on your login authentication service/module)

Deny access to routes in Angular js 2


batch rename code needs modification

Question: guppies_2018_02-01_001thrusday.jpg --> day001.jpg
guppies_2018_02-02_002friday.jpg --> day002.jpg
guppies_2018_02-03_003saturday.jpg --> day003.jpg
guppies_2018_02-04_004sunday.jpg --> day004.jpg

The above is what I want. I found a batch renaming code and tried to modify it. But have trouble removing the monday-sunday part.
for file in *.jpg; do echo $file day$(echo $file | cut -f3- -d- ); done

Please help.
Answer: Assuming all your files have similar names with the same length text before the number, you could probably do something like this:
setlocal EnableDelayedExpansion
dir /b *.jpg >dir.txt
for /f %%A in (dir.txt) do (
set var=%%A
set %var:~19%
set var=%var:~0,3%
ren "%%A" "Day%var%.jpg"
)

It removes the first 19 characters from the file name, then takes the next three and puts that between Day and .jpg.

batch rename code needs modification


Templates em c++ só podem ser usados uma vez?

Question: tenho este codigo em c++ e estou recebendo um erro:
<code>#include<iostream>
using namespace std;
template <class T>

void setVector(T* v, int sizeOfV){
for(int i=0;i<sizeOfV;i++)cin>>v[i];

}
void showVector(T* v, int sizeOfV){
for(int i=0;i<sizeOfV;i++)cout>>endl>>v[i];}
</code>
Está ai o erro:
<code>T não está no escopo
V não está no escopo
</code>
Será que um template só pode ser usado uma vez???
Queria esclarecer esta dúvida :D
Answer: O erro ocorre porque o compilador não enxerga o tipo T na segunda função. Duas funções não podem compartilhar o mesmo tipo genérico, você precisar declarar cada função como template:
<code>#include<iostream>
using namespace std;

template <class T>
void setVector(T* v, int sizeOfV)
{
    for (int i = 0; i<sizeOfV; i++)
        cin >> v[i];
}

template <class T>
void showVector(T* v, int sizeOfV)
{
    for (int i = 0; i<sizeOfV; i++)
        cout >> endl >> v[i];
}
</code>


Use a Token in Minimum Field

Question: I am new to rather new to Drupal (coming from Django/Python), and was wondering if there was anyway I could use a token in the minimum field of my registration.
What I basically have is a registration from, which is then a field in one of my content types. In this content type I also have a field called minimum deposit. So I wondering if I could somehow link the value in the minimum deposit field to the minimum in my registration? Like for the minimum value have: [node:minimum_deposit].
Comment: I'm not sure I understand: are you trying to set the default value of the "minimum deposit" field in your registration form to contain the same value as in the field "minimum deposit" in a pre-existing node?
Comment: Yes, essentially that is that I'm trying to do.
Answer: In a nutshell, there is no way that I know to do this with a token. You need to create a custom module that implements hook_form_alter() to set the default value of your minimum deposit field before the form is rendered. You'll set this default value using the value of the field in the pre-existing node (you'll need to load the node programmatically within the hook function and get the value of the field).
I could give you more details if you let me know what type of form you are using: are you creating a form programmatically with Form API? Using Entityform module to create the form? Using Webform module? Using the "Add to Cart" form provided by the module Drupal Commerce? Post a comment below and I'll edit this answer.
Comment: Thanks for the response, I am using the [Entity Response](https://www.drupal.org/project/registration) module.
Comment: Do you think you can handle it with the information I had above? Do you have other specific questions?
Comment: Yes, I'm fairly new, but I have a good idea of what I should be looking into now. Thanks.

Use a Token in Minimum Field


Pegar valor de Input

Question: Sei que o título faz parecer que já tenha milhões desta pergunta, mas vamos lá.
O meu caso funciona assim, eu tenho um DataList para que possa autocompletar buscando em um array de objetos. Quando eu pego esse array, ele vai me retornar um dos itens e este item eu vou procurar pelo html dele, html que está com o mesmo nome que o item.
A questão é, como eu pego somente um dos valores? O valor que está escrito no Input??

jsonOptions = [
    {"product": "22222", "description": "description 2"},
    {"product": "33333", "description": "description 3"},
    {"product": "44444", "description": "description 4"},
    {"product": "55555", "description": "description 5"},
    {"product": "66666", "description": "description 6"},
    {"product": "77777", "description": "description 7"}

     ];

$(document).ready(function() {

   var dataList = document.getElementById('json-datalist');

 jsonOptions.forEach(function(item) {

  var option = document.createElement('option');

  option.value = item.description;
  option.text = item.product;
  option.setAttribute('data-product', item.product);
  dataList.appendChild(option);
    });

});

<input type="text" list="json-datalist" placeholder="Nome ou Número">
<datalist id="json-datalist"></datalist>

Olhem o código, é bem simples.. O que quero fazer é pegar o valor de descrição e usar ele como parâmetro para buscar por uma página html.. Também preciso daquele production que procurar pelo número também será uma opção.
Comment: Considere alterar o título para que ele seja mais específico ao problema
Answer: Adicione o evento input ao campo.
var inp = document.querySelector('input');
inp.addEventListener('input', function() {
  var value = this.value;
  var opt = [].find.call(this.list.options, function(option) {
    return option.value === value;
  });
  if(opt) {
    alert('Product: ' + opt.textContent + '\nDescription: ' + opt.value);
  }
});

Veja funcionando

jsonOptions = [
  {"product": "22222", "description": "description 2"},
  {"product": "33333", "description": "description 3"},
  {"product": "44444", "description": "description 4"},
  {"product": "55555", "description": "description 5"},
  {"product": "66666", "description": "description 6"},
  {"product": "77777", "description": "description 7"}

];

$(document).ready(function() {

  var dataList = document.getElementById('json-datalist');

  jsonOptions.forEach(function(item) {

    var option = document.createElement('option');

    option.value = item.description;
    option.text = item.product;
    option.setAttribute('data-product', item.product);
    dataList.appendChild(option);
  });

  var inp = document.querySelector('input');
  inp.addEventListener('input', function() {
    var value = this.value;
    var opt = [].find.call(this.list.options, function(option) {
      return option.value === value;
    });
    if(opt) {
      alert('Product: ' + opt.textContent + '\nDescription: ' + opt.value)
    }
  });

});

<input type="text" list="json-datalist" placeholder="Nome ou Número">
<datalist id="json-datalist"></datalist>

Referências

find
call
input
Comment: Parabéns por sua resposta amigo, resolveu 100%. Muito obrigado.

Pegar valor de Input


Background thread loop and two-way-communication

Question: I already used BackgroundWorker and Task to do something in the background and after it posting it back to the UI. I even used BackgroundWorker and ReportProgress with an endless-loop (beside cancellation) to continuously post things to the UI thread.
But this time I need a more controllable scenario:
The background thread continuously polls other systems. With Invoke it can send updates the the UI. But how can the UI send message to the background thread? Like changed settings.
In fact I am asking for the best .NET practice to have a worker thread with these specifics:

Runs in background, does not block UI
Can send updates to UI (Invoke, Dispatch)
Runs in endless loop but can be paused, resumed and stopped in a proper way
UI thread can send updated settings to the background thread

In my scenario I still use WinForms but I guess it should not matter? I will convert the application to WPF later.
Which best practice do you suggest?
Comment: Any additional suggestions (to BrokenGlass)? What about `SynchronizationContext`?
Comment: `SynchronizationContext` might work, but that would be a low-level abstract. [My take](http://stackoverflow.com/a/21968329/1768303) is to use TPL and a custom task scheduler.
Answer: I would use TPL and a custom task scheduler for this, similar to Stephen Toub's StaTaskScheduler. That's what WorkerWithTaskScheduler implements below. In this case, the worker thread is also a task scheduler, which can run arbitrary Task items (with ExecutePendingTasks) while doing the work on its main loop.
Executing a lambda wrapped as a TPL Task on the worker thread's context is a very convenient way to send the worker thread a message and get back the result. This can be done synchrounsly with WorkerWithTaskScheduler.Run().Wait/Result or asynchronously with await WorkerWithTaskScheduler.Run(). Note how ContinueExecution and WaitForPendingTasks are used to pause/resume/end the worker's main loop. I hope the code is self-explanatory, but let me know if I should clarify anything.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace Console_21628490
{
    // Test
    class Program
    {
        static async Task DoWorkAsync()
        {
            Console.WriteLine("Initial thread: " + Thread.CurrentThread.ManagedThreadId);

            // the worker thread lambda
            Func<WorkerWithTaskScheduler<int>, int> workAction = (worker) =>
            {
                var result = 0;

                Console.WriteLine("Worker thread: " + Thread.CurrentThread.ManagedThreadId);

                while (worker.ContinueExecution)
                {
                    // observe cancellation
                    worker.Token.ThrowIfCancellationRequested();

                    // executed pending tasks scheduled with WorkerWithTaskScheduler.Run
                    worker.ExecutePendingTasks();

                    // do the work item
                    Thread.Sleep(200); // simulate work payload
                    result++;

                    Console.Write("\rDone so far: " + result);
                    if (result > 100)
                        break; // done after 100 items
                }
                return result;
            };

            try
            {
                // cancel in 30s
                var cts = new CancellationTokenSource(30000);
                // start the worker
                var worker = new WorkerWithTaskScheduler<int>(workAction, cts.Token);

                // pause upon Enter
                Console.WriteLine("\nPress Enter to pause...");
                Console.ReadLine();
                worker.WaitForPendingTasks = true;

                // resume upon Enter
                Console.WriteLine("\nPress Enter to resume...");
                Console.ReadLine();
                worker.WaitForPendingTasks = false;

                // send a "message", i.e. run a lambda inside the worker thread
                var response = await worker.Run(() =>
                {
                    // do something in the context of the worker thread
                    return Thread.CurrentThread.ManagedThreadId;
                }, cts.Token);
                Console.WriteLine("\nReply from Worker thread: " + response);

                // End upon Enter
                Console.WriteLine("\nPress Enter to stop...");
                Console.ReadLine();

                // worker.EndExecution() to get the result gracefully
                worker.ContinueExecution = false; // or worker.Cancel() to throw
                var result = await worker.WorkerTask;

                Console.Write("\nFinished, result: " + result);
            }
            catch (Exception ex)
            {
                while (ex is AggregateException)
                    ex = ex.InnerException;
                Console.WriteLine(ex.Message);
            }
        }

        static void Main(string[] args)
        {
            DoWorkAsync().Wait();
            Console.WriteLine("\nPress Enter to Exit.");
            Console.ReadLine();
        }
    }

    //
    // WorkerWithTaskScheduler
    //

    public class WorkerWithTaskScheduler<TResult> : TaskScheduler, IDisposable
    {
        readonly CancellationTokenSource _workerCts;
        Task<TResult> _workerTask;

        readonly BlockingCollection<Task> _pendingTasks;
        Thread _workerThread;

        volatile bool _continueExecution = true;
        volatile bool _waitForTasks = false;

        // start the main loop
        public WorkerWithTaskScheduler(
            Func<WorkerWithTaskScheduler<TResult>, TResult> executeMainLoop,
            CancellationToken token)
        {
            _pendingTasks = new BlockingCollection<Task>();
            _workerCts = CancellationTokenSource.CreateLinkedTokenSource(token);

            _workerTask = Task.Factory.StartNew<TResult>(() =>
            {
                _workerThread = Thread.CurrentThread;
                return executeMainLoop(this);
            }, _workerCts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
        }

        // a sample action for WorkerWithTaskScheduler constructor
        public static void ExecuteMainLoop(WorkerWithTaskScheduler<TResult> worker)
        {
            while (!worker.ContinueExecution)
            {
                worker.Token.ThrowIfCancellationRequested();
                worker.ExecutePendingTasks();
            }
        }

        // get the Task
        public Task<TResult> WorkerTask
        {
            get { return _workerTask; }
        }

        // get CancellationToken
        public CancellationToken Token
        {
            get { return _workerCts.Token; }
        }

        // check/set if the main loop should continue
        public bool ContinueExecution
        {
            get { return _continueExecution; }
            set { _continueExecution = value; }
        }

        // request cancellation
        public void Cancel()
        {
            _workerCts.Cancel();
        }

        // check if we're on the correct thread
        public void VerifyWorkerThread()
        {
            if (Thread.CurrentThread != _workerThread)
                throw new InvalidOperationException("Invalid thread.");
        }

        // check if the worker task itself is still alive
        public void VerifyWorkerTask()
        {
            if (_workerTask == null || _workerTask.IsCompleted)
                throw new InvalidOperationException("The worker thread has ended.");
        }

        // make ExecutePendingTasks block or not block
        public bool WaitForPendingTasks
        {
            get { return _waitForTasks; }
            set
            {
                _waitForTasks = value;
                if (value) // wake it up
                    Run(() => { }, this.Token);
            }
        }

        // execute all pending tasks and return
        public void ExecutePendingTasks()
        {
            VerifyWorkerThread();

            while (this.ContinueExecution)
            {
                this.Token.ThrowIfCancellationRequested();

                Task item;
                if (_waitForTasks)
                {
                    item = _pendingTasks.Take(this.Token);
                }
                else
                {
                    if (!_pendingTasks.TryTake(out item))
                        break;
                }

                TryExecuteTask(item);
            }
        }

        //
        // TaskScheduler methods
        //

        protected override void QueueTask(Task task)
        {
            _pendingTasks.Add(task);
        }

        protected override IEnumerable<Task> GetScheduledTasks()
        {
            return _pendingTasks.ToArray();
        }

        protected override bool TryExecuteTaskInline(
            Task task, bool taskWasPreviouslyQueued)
        {
            return _workerThread == Thread.CurrentThread &&
                TryExecuteTask(task);
        }

        public override int MaximumConcurrencyLevel
        {
            get { return 1; }
        }

        public void Dispose()
        {
            if (_workerTask != null)
            {
                _workerCts.Cancel();
                _workerTask.Wait();
                _pendingTasks.Dispose();
                _workerTask = null;
            }
        }

        //
        // Task.Factory.StartNew wrappers using this task scheduler
        //

        public Task Run(Action action, CancellationToken token)
        {
            VerifyWorkerTask();
            return Task.Factory.StartNew(action, token, TaskCreationOptions.None, this);
        }

        public Task<T> Run<T>(Func<T> action, CancellationToken token)
        {
            VerifyWorkerTask();
            return Task.Factory.StartNew(action, token, TaskCreationOptions.None, this);
        }

        public Task Run(Func<Task> action, CancellationToken token)
        {
            VerifyWorkerTask();
            return Task.Factory.StartNew(action, token, TaskCreationOptions.None, this).Unwrap();
        }

        public Task<T> Run<T>(Func<Task<T>> action, CancellationToken token)
        {
            VerifyWorkerTask();
            return Task.Factory.StartNew(action, token, TaskCreationOptions.None, this).Unwrap();
        }
    }
}

To implement worker-to-client notifications, you can use the IProgress<T> pattern (example of this).
Comment: This looks very interesting. I will check it out. Thanks for sharing that much information! May I ask what you edited?
Answer: First thing that comes to mind, and the cleanest approach imo is to have the background thread method that is continuously running be an instance method of a class. This class instance can then expose properties/methods that allow others to change state (e.g. through the UI) - some locking may be required since you are reading/updating state from different threads.
Comment: With this you mean do to `new Thread(new ThreadStart(threadWorkerInstance.RunMethod));` and manipulate the `threadWorkerInstance` from main thread and have `RunMethod` looking for them?
Comment: Yes, essentially - don't forget to put locks in place to handle concurrency.


What does $\mathbb{C}[G ]\otimes_{\mathbb{C}[H]} W$ mean?

Question: I am reading the group representation book by Serre. In chapter 7 (which is about induced representation), he introduces the notation
$$ \mathbb{C}[G] \otimes_{\mathbb{C}[H]} W .$$
What does this notation mean? I understand $W$ as a $H$-module, or a representation of $H$. I also can accept $\mathbb{C}[G] \otimes  W$ as a tensor product space of $(\sum_{g\in G} a_g g , w)$, where $w\in W$. But how to understand the $ \mathbb{C}[H] $ in the subscript?
Comment: [Wikipedia on tensor products over a ring](https://en.wikipedia.org/wiki/Tensor_product_of_modules). You may be thinking of / familiar with tensor products over $\Bbb{C}$ (or a field). Here there will be more cancellations due to the rules
$$a\otimes rw=ar\otimes w$$ for all $a\in\Bbb{C}[G]$, $r\in\Bbb{C}[H]$, $w\in W$.
Comment: Because $\Bbb{C}[H]$ is a free right module over $\Bbb{C}[H]$ with a basis consisting of a set of representatives $D\subset G$ of cosets $gH$. This tensor product becomes a left $\Bbb{C}[G]$-module because $\Bbb{C}[G]$ itself is a bimodule: $\Bbb{C}[G]$ acts on it by multiplication from the left, and $\Bbb{C}[H]$ acts on it by multiplication from the right, and the two actions commute. The end result is called *the induced representation of $G$,* $\mathrm{Ind}_H^G(W)$.
Comment: Sheesh :-( ^$\Bbb{C}[G]$ is a free right $\Bbb{C}[H]$-module etc.
Answer: Let $R$ be a ring.
Given a right $R$-module $M$ and left $R$-module $N$, we can form the tensor product $M ⊗_R N$.
This tensor product can be described as the abelian group with generators $m ⊗ n$, where $m$ and $n$ range through $M$ and $N$ respectively, subject to the the relations
\begin{align*}
  (m_1 + m_2) ⊗ n &= m_1 ⊗ n + m_2 ⊗ n \,, \\
  m ⊗ (n_1 + n_2) &= m ⊗ n_1 + m ⊗ n_2 \,, \\
  (m r) ⊗ n &= m ⊗ (r n)
\end{align*}
for all $m, m_1, m_2 ∈ M$, $n, n_1, n_2 ∈ N$, $r ∈ R$.
Let now $S$ be another ring and let $M$ not just be a right $R$-module, but actually an $S$-$R$-bimodule.
The tensor product $M ⊗_R N$ can then be made into a left $S$-module such that
$$
  s ⋅ (m ⊗ n) = (s m) ⊗ n
$$
for all $s ∈ S$, $m ∈ M$, $n ∈ N$.
Let us consider the special case that $R$ is a subring of $S$.
We can then regard $S$ as an $S$-$R$-bimodule.
For every left $R$-module $M$ we can thus form the left $S$-module $S ⊗_R M$.
This construction of going from left $R$-modules to $S$-modules is the extension of scalars from $R$ to $S$.
It satisfies the adjunction
$$
  \operatorname{Hom}_S( S ⊗_R M, N )
  ≅
  \operatorname{Hom}_R( M, N )
$$
for every left $R$-module $M$ and every left $S$-module $N$.
(On the right hand side, we regard $N$ as a left $R$-module by restriction of scalars.)
Suppose now that $G$ is a group, $H$ is a subgroup of $G$, and $V$ is a representation of $H$.
We would like to extend the representation $V$ into a representation of $G$.
In other words, we would like to extend the $ℂ[H]$-module $V$ to a $ℂ[G]$-module.
The group algebra $ℂ[H]$ is a subalgebra of the group algebra $ℂ[G]$, so we can use the extension of scalars
$$
  ℂ[G] ⊗_{ℂ[H]} V
$$
to solve this problem.
This is then called the induced representation of $V$ from $H$ to $G$, and often denoted by $\operatorname{Ind}^G_H(V)$.
This induced representation satisfies the adjunction
$$
  \operatorname{Hom}_G( \operatorname{Ind}^G_H(V), W )
  =
  \operatorname{Hom}_{ℂ[G]}( ℂ[G] ⊗_{ℂ[H]} V, W )
  ≅
  \operatorname{Hom}_{ℂ[H]}( V, W )
  =
  \operatorname{Hom}_H( V, W )
$$
for every representation of $V$ of $H$ and every representation $W$ of $G$.
In this context of group representations, this adjunction is often referred to as Frobenius reciprocity.
More details about tensor products and extension of scalars can, for example, be found in section 10.4 of Abstract Algebra (3rd edition) by Dummit and Foote.


Linear Mixed-Effects Models (lmer function in R) - Statistical significance?

Question: I have the following mixed models:
modeloIa<-lmer(log(FstPSAmm2+1)~AntherAreamm2+(1|plant), REML = F)

modeloIIa<-lmer(log(FstPSAmm2+1)~AntherAreamm2*color+(1|plant), REML = F)

modeloIIIa<-lmer(log(FstPSAmm2+1)~AntherAreamm2*color*FlPerBranch+(1|plant), REML = F)

modeloIVa<-lmer(log(FstPSAmm2+1)~color*AntherAreamm2*PlVoldm3+(1|plant), REML = F)

The first one is the null modell. The variable color is the fixed effect I want to test. FlPerBranch and PlVoldm3 are covariables.
How do I select the best model? How do I know if the variables are significant?
These two questions are for me a dilemma.
If I use the AIC criterion I should select one model, but if I use the likelihood ratio test, starting from my null modell, I should select another. Any advice will help me a lot, thanks.
Comment: Looking through [our previous questions tagged both "mixed-model" and "model-selection"](https://stats.stackexchange.com/questions/tagged/mixed-model%2bmodel-selection) gives a number of hits. Does anything there help you?
Comment: See the help file `?lmer` for examples of performing tests with mixed effects models.
Answer: I would look at mixed effect model selection in Zuur et al. (2009) (? maybe 2007)
You could use AICc to aid in model selection for sure but I know he goes into it a lot more in his book.
As for the p-values there are two ways I know of. One way would be to install the package lmerTest it gives you pvalues for you model outputs. The other way that I know more about is to use anova (with a chi-square distrib.) in order to get some sort of p-values.
For example if you do an AICc on two models
model1 is Y ~ x+(1|y)
model2 is Y ~x + z +(1|y)  and the aic difference is extremely close you can run an anova on both:
aov(model1,model2, type = "chisq")

and get a p -value telling you the significance of that extra parameter (z)
Comment: Can you give a little more information, maybe a link, to the paper/book you are citing?
Comment: http://www.springer.com/us/book/9780387874579