angular-nvd3 margin doesn't work? (krispo)

Question: No matter how much I change the margin. The dates get cut off. I am trying to show a 7 date range, but the last date gets cut off. Any ideas, to work around this?
My code:
<code>vm.lineChartOptions = {
    chart: {
        type: 'lineChart',
        height: 450,
        tickPadding: 25,
        margin: {
            top: 50,
            right: 1000,
            bottom: 60,
            left: 1000
        }
}
</code>
Answer: There's a property in the xAxis object, and I had the showMaxMin: set to false, and changed it to true. I also realized my gulp wasn't running for about an hour so there's that.
After I set to showMaxMin to true, and booted my gulp up again, I was able to change the margin.


What can cause a "Error() model is singular error" in aov when fitting a repeated measures ANOVA?

Question: I have the following data set:
                 |       Scenario 1       |     Scenario 2         |
                 |Trial 1|Trial 2| Trial 3|Trial 1|Trial 2| Trial 3|
 -------------------------------------------------------------------
              S1 | ...
 Condition 1  S2 | ...
              S3 |
 -------------------------------------------------------------------
              S5 |
 Condition 2  S6 |
              S7 |

Thus the Trials are nested in the Scenarios and all of them are within subject. I am trying to run an ANOVA on this data set. Here is the model without defining that Scenarios (and Trials) are within subject.
 my_data.aov <- aov(value~Condition*Trial%in%Scenario,data=my_data) #works fine

But when I specify that these are within subject:
my_data.aov <- aov(value~Condition*Trial%in%Scenario+Error(Player/(Trial%in%Scenario)),data=my_data)

I get the following error
In aov(value ~ Condition * Trial % in % Scenario + Error(Player/(Trial %in%  :
Error() model is singular

The closest set-up I could find was Split plot in R but there the subjects are nested inside each Trial not in each Condition.
EXAMPLE FILE
Here is an example file in long format.
What about this approach?
If I treat each Trial as a sample, then I can collapse across Scenarios by averaging them, so I will have a simpler model, where each Subject's behavior is described per Scenario. And since I need to analyze the relationship of value~Condition*Scenario I can do so by defining the Error like Error(Subject/Scenario).
Will this approach invalidate my analysis?
Comment: What does the last sentence mean? Do all subjects get all the conditions? I'm afraid you don't have a Split-plot design and now you misspecified your model to have non-estimable parameters.
Comment: As the data description shows: `S1, S2, S3, ...` take only `Condition 1` and `S7, ...` only `Condition 2`. But I want to compare the effects of `Condition 1` with `Condition 2`. The reason why it fails (I think) is that each `subject` has the `Scenario`, which nests the `Trial`, which I could not clearly integrate in the model.
Comment: Now I see. Try ``Error(Player/(Trial*Subject))``. The nesting is irrelevant to specify this error term. You have 3*2 measures for each subject and want to integrate all the possible covariances between these measures into your model. To this end, you don't need to specify that these covariances may be decomposable into one part from the trial and one from the scenario. The covariance would be the same if scenario and trial would be crossed. In fact this is the part that makes your covariance parameters non estimable.
Comment: You meant `Error(Player/(Trial*Scenario))`?
Comment: Ah, yes, of course, sorry! Does it work?
Comment: I get the same error.
Answer: Without an example dataset (say from 6 subjects) it is hard to say for certain.  You might try to use dput towards this end.
The error message Error() model is singular suggests to me that you have insufficient degrees of freedom to calculate your model.  I think it is probably unlikely you meant to use %in% in this context, but maybe I'm wrong.  Look at ?%in%.  %in% produces a logical TRUE/FALSE vector of whether the Trial # matches the Scenario #.  When you do estimate that subject effect then you only have two observations in the cell where Trial # matches the Scenario number and then you won't have enough observations per subject left over to also look at a Condition * Trial %in% Scenario interaction.
Consider:
library(doBy)
summaryBy(value~Condition*Trial%in%Scenario,data=mydata,FUN=c(mean,var,length))

... and be sure it matches your expectations.
Comment: Repeated measures ANOVA can not handle missing values.
Comment: You only have 6 or 7 players (independent replications), right? You may consider to drop some trials. Are these random effects anyway? Or you can use SAS proc mixed which is quite versatile with repeated measures, but then it's no more pure ANOVA as @rpierce pointed out.
Comment: @HorstGrünbusch: With respect, I recommend caution.  Mixed models are more complex than SAS lets on; this can lead users without mixed model experience down unfortunate paths.  Although a mixed model will likely 'work' here, I want it clearly specified that PROC MIXED is not a panacea for repeated measures data with missing observations.
Comment: I am getting `NA` for `mean` and `var`.
Comment: var I expected to be NA because from a single variable you can't calculate variance.  Do you have missing values in your dataset?  `summaryBy(value~Condition*Trial%in%Scenario,data=mydata,FUN=function(x) {any(is.na(x))})`
Comment: You would expect that the result would say "TRUE" if you are missing any values in that cell.
Comment: Yes, I have missing values.
Comment: @Pio:  I'm sorry this isn't the outcome you were hoping for.  I hope you'll mark my answer as accepted all the same.  Alternatively, if there are points I could clarify - please let me know.
Comment: Repeated measures ANOVA with missing values is possible for missing values, even as available cases analysis without need for imputations. It's just not yet published.
Comment: @Horst, such a procedure would not be repeated measures ANOVA. Mixed models can fit models with missing data (and that has been published and peer reviewed).  However those are not repeated measures ANOVA. I think your comment only serves to cloud the issue.
Comment: @rpierce what you're saying is there is no model that could incorporate all the aspects of this experiment the way I described?
Comment: Well as @HorstGrünbusch indicated, and I acknowledged, there are other types of model that could potentially fit your data.  However, there is no proper model specification that you can fit to your data with your selected variables and the aov function without dropping players MlpV0YuEXKZrU5Wg0VGlWYyi, jsp75Kqov11ZgWn3B5WjglWa, BWtRG1272KYjC8N0oE51ScrH, uYJHoWZJLrnCKDWWzoo4UEGL, and LCawAtJXipsGxSkTOHlRD7v5.
Answer: I found a solution, even though it solves a my bigger problem, but as you could see from my question I went down a road, where I got stuck and I didn't really get an answer how to solve it. So I opted for the lme4 package and used the lmer function to model the relationship in my data.
BTW, the my approach where I suggest collapsing the data is a traditional approach in psychology, which I found out recently (after asking the question).
Finally the tutorial which saved the day for me (using lmer) is written by Bodo Winter, where he works on a dataset that almost matches mine -- even though it's not so obvious from the first time you read it.
In short my linear model looks like this:
 lmer(value~Condition*Scenario + (1+Scenario|Player) + (1|Scenario/Trial)

This perfectly models my experimental setup.
Comment: I'm perplexed as to why you selected this answer to a question that asks "what can cause".  I answered what can cause.  What can one do instead is a different question.

Collapsing the data is traditional in psychology (and many other fields) because it yields data you can run an ANOVA on.  The approach you decided on is the mixed model approach that Horst and I mentioned above (lmer is the R version of PROC MIXED).  I suspect your next question might be "where are the p-values". Rather than get into why that is a bad idea, here is a link: http://cran.r-project.org/web/packages/afex/index.html


The correct way to use set builder notation of this set?

Question: Is this the correct way to represent this set using this set builder notation?
$$\big\{1, 4, 9, 16, ..., 100\} \cap \big\{1, 3, 5, 7, ...\}$$
$$A=\big\{2x - 1 \wedge y^2 \; | \; x \in \mathbb{N}, y \in \mathbb{N}, x \leq 10\}$$
I am confused as to how to set one variable to describe an infinite range and another to describe a finite one.
Answer: The $\wedge$ operator is from logic and applies to propositions or boolean variables, but doesn't apply to numbers.
Either you use the existential quantifier, as in $$\{n\in \mathbb{N}\ |\ (\exists k\in\mathbb{N},(n=k^2)\wedge(k\leq10))\wedge (\exists \ell\in\mathbb{N},n=2\ell-1)\}$$
Or you can use the fact that the square of an integer is odd if and only if that integer is odd:
$$\{(2n-1)^2\ |\ n\in\mathbb{N},n\leq5\}$$
Comment: @ALKI You only want to square the odd numbers, since $\cap$ takes the intersection of two sets. Perhaps you are confusing $\cap$ with $\cup$?
Comment: Doesn't your second set only square the odd numbers? And it doesn't include the odd number set
Comment: @ALKI you are correct, but your set contains only squares of odd numbers anyway.
Comment: Ah I was confusing $\cap$ with $\cup$. Thank you


Difference between $\cos(x)$= positive and $\cos(x)$= negative

Question: I'm confusing myself here so need some clarification. If I was to work out the solutions to $\cos(x) = 1/\sqrt2$ , I know the solutions would be $\pi/4, 2\pi - \pi/4, 2\pi + \pi/4...$ etc.
What is the difference when working out the solution to $\cos(x) = -1/\sqrt2$. What values need to be added to what, and what are the solutions significance to the solutions when the value is positive (above) ?
Answer: $\cos(x)=-\dfrac{1}{\sqrt{2}}$ implies that the solutions lie in the "negative" quadrants for cosine, i.e. the $2$nd and $3$rd quadrants.
So, for $x$, you would get:
$x=\big(\pi-\dfrac{\pi}{4}\big)$, $\big(\pi+\dfrac{\pi}{4}\big)$, ...
$\hspace{3 mm}=\dfrac{3\pi}{4}$, $\dfrac{5\pi}{4}$, ...
Answer: If $\cos x > 0$, then the terminal side of angle $x$ lies in the first quadrant, the fourth quadrant, or the positive $x$-axis.  If $\cos x < 0$, then the terminal side of angle $x$ lies in the second quadrant, the third quadrant, or the negative $x$-axis.
One solution of the equation $\cos x = -\dfrac{1}{\sqrt{2}}$ is
$$x = \arccos\left(-\frac{1}{\sqrt{2}}\right) = \frac{3\pi}{4}$$

By symmetry, $\cos(-x) = \cos x$, so another solution is
$$x = -\frac{3\pi}{4}$$
Any angle coterminal with one of those angles will have the same cosine.  Hence, the general solution is
$$x = \pm \frac{3\pi}{4} + 2k\pi, k \in \mathbb{Z}$$
As the diagram indicates,
\begin{align*}
\cos(\pi + \theta) & = -\cos\theta\\
\cos(\pi - \theta) & = -\cos\theta
\end{align*}
which you can verify using the sum and difference of angle formulas for cosine.  You know that one solution of $\cos\theta = \dfrac{1}{\sqrt{2}}$ is
$$\theta = \arccos\left(\frac{1}{\sqrt{2}}\right) = \frac{\pi}{4}$$
so the solutions to the equation $\cos x = -\dfrac{1}{\sqrt{2}}$ include
\begin{align*}
x = \pi - \frac{\pi}{4} = \frac{3\pi}{4}\\
x = \pi + \frac{\pi}{4} = \frac{5\pi}{4}
\end{align*}
Observe that
$$x = \frac{3\pi}{4} = \arccos\left(-\frac{1}{\sqrt{2}}\right)$$
and that
$$x = \frac{5\pi}{4} = -\frac{3\pi}{4} + 2\pi$$


Cache problem on entity view mode teaser

Question: I'm using two slightly different versions of a teaser of a node on two different pages. It's the same fields used for both, but different HTML around each field.
In both cases, I get the renderable array of my node this way :
$view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$vars['renderable_node'] = $view_builder->view($referenced_node, 'teaser');

What I would like to have :

Page Node 1
Node 3 teaser version 1
Page Node 2
Node 3 teaser version 2

The problem is when I flush caches, the cache is set for the first time rendering the teaser of my node, but on my other page it render the same version.
Here is what I have then :

Page Node 1
Node 3 teaser version 1
Page Node 2
Node 3 teaser version 1

I looked into ['#cache']['max-age'] but I don't really want to set it to 0 because it's not appropriate for obvious performance reasons.
I see that there is also ['#cache']['keys'], ['#cache']['context'] and ['#cache']['tags'] but not sure what to do.
Comment: Why not use two different display modes and use `$view_builder->view($node, 'teaser');` and `$view_builder->view($node, 'other_teaser');`?
Comment: That's a good remark indeed, but in my case, I'm in a preprocess_node where I render a node teaser from an other type. Some info differ based on the current node.
Answer: I ran into the same problem recently.
Adding a key to the ['#cache']['keys'] array as unique id solved my cache problem.
For your case it should be like this :
$view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$vars['renderable_node'] = $view_builder->view($referenced_node, 'teaser');
$vars['renderable_node']['#cache']['keys'][] = "page_1";

On your second call to the teaser node then it should be like this :
$view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$vars['renderable_node'] = $view_builder->view($referenced_node, 'teaser');
$vars['renderable_node']['#cache']['keys'][] = "page_2";

Comment: That sounds good indeed ! In my case, I use the current nid of my preprocess node to make a difference `$vars['renderable_node']['#cache']['keys'][] = $current_node->id();`


Exercises for 21st century piano sightreaders

Question: There is already a large body of technical exercises for pianists based on common-practice music, such as major and minor scales and arpeggios or the books of Czerny, Hanon, etc. These exercises are indispensable for my own practice of sight-reading, since these patterns frequently come up in common-practice music.
I would like to strengthen my sight-reading of non-common-practice music. Are there techniques that I can practice which distill the "molecules" of the much broader musical practice of the 20th and 21st centuries, to improve my sightreading? Are there specific excercises that can improve those techniques?
For example, recently I have been playing Messaien's Modes of Limited Transposition in all positions on the keyboard.
Comment: I've personally found pieces with several parallel quartal chords in a row (e.g. some video game music, Rautavaara, Sonny Chua) to be quite helpful at sight-reading quartal harmony.
Comment: Briefly, many composers wrote Etudes that reflect their techniques: Ligeti and Philip Glass come to mind immediately.
Comment: @Aaron Thank you for your comment. Indeed, I am familiar with these sets of Études, but I am looking for something more on par with exercises and scales: the "molecules" of non-common practice music instead of those great purified solutions.
Comment: Hi Joshua, unfortunately external resource requests including exercises is off-topic. If you have a specific area you want to study or practice, we can focus on answering that instead.
Comment: @Dom Please consider re-opening. Although this is a request for resources, I think it's one of genuine and lasting value for the site that does not run afoul of the "opinion-based" reasoning behind the usual resource-request closures. i
Comment: @Aaron we've closed similar questions in the past and we should try to keep the site consistent. Another thing is questions looking for example  typically turn into just and endless list of examples that you can always add more to and none are more correct than others.
Comment: @Dom I see part of my comment got dropped: it said that the question lends itself to a fairly small number of concise answers, and if not, then it could be closed or protected. But allowing the question stays closed, do you see a way to rework it? I think there's a lot to be gained here (maybe as a community wiki?). I'll chime in if I come up with a good alternative question.
Comment: @Aaron retroactively moderating thing like this is hard and wikis are not always a good path. Very few wikis on the site seem to be working the way we want, most have problems that have needed more advanced moderation. I think there is a good specific question to be asked here that isn't as open ended and leans away from just listing exercises. We can continue in chat if you want.
Comment: @Dom I have revised the question to attempt to address this issue; please let me know if this fixes the issue or if I should revise differently.
Comment: @JoshuaMundinger I'm going to edit it a bit more so it focuses on techniques rather than exercises themselves.
Answer: I've personally used Bartok's Mikrokosmos for practicing sightreading. It helps me pay more attention to what notes are really there, and avoid trying to anticipate the harmony of the piece (which, for most contemporary music, is impossible).
The Mikrokosmos also has a wide variety of difficulty levels, so you should be able to find something easy enough or difficult enough for your sightreading needs.
Answer: First of all, technique doesn't come from exercise books or more practice, it comes from moving properly.   You can practice ten hours a day but if you move incorrectly, you won't improve.  If you are unlucky, you will brow beat your technique into the wrong muscles which will result in eventual injury.  You will know you are moving wrong if you wake up in the morning with stiff arms and hands.
Sight reading comes from your knowledge of music theory and having a technique which can play what your brain sees.  Your ear will also aid in discerning what is coming next.  Much like reading words. It deosn't mttaer in waht oredr the ltteers in a wrod are, the olny iprmoetnt tihng is taht the frist and lsat ltteer be at the rghit pclae. The rset can be a toatl mses and you can sitll raed it wouthit porbelm. Tihs is bcuseae the huamn mnid deos not raed ervey lteter by istlef, but the wrod as a wlohe. Music is the same.
You don't need exercises nor exercise books.  Only real music. You'll get all the technique you need from therein.
Comment: This doesn't answer the question, which is about developing the "knowledge of music theory" and "technique" that you mention. Of course one learns from playing real music, but it is an extreme to say, for instance, that one should not learn major scale fingerings on their own and merely learn it piecemeal whenever it comes up in a piece.


Create woocommerce custom form

Question: I want to create a custom form in wordpress woocommerce. I want to create a form to register and sign new customers. could you give me a clue?
Answer: Can you explain more? What kind of form? Is there a reason you can't use the native woocommerce registeration features? They are easy and work with wordpress login credentials.
Comment: Did my answer help you get where you wanted to go? Or can you be more specific so we can get your woocommerce bigger & better than ever?

Create woocommerce custom form


Strange behavior with SSE endpoint using Redis

Question: I need to push some data to the client if it is in Redis, but client keeps reconnecting to the SSE endpoint every 5 seconds.
The backend code:
@RestController
@RequestMapping("/reactive-task")
public class TaskRedisController {

    private final TaskRedisRepository taskRedisRepository;

    TaskRedisController(TaskRedisRepository taskRedisRepository){
        this.taskRedisRepository = taskRedisRepository;
    }

   @CrossOrigin
    @GetMapping(value = "/get/{id}")
    public Flux<ServerSentEvent<Task>> getSseStream2(@PathVariable("id") String id) {
        return taskRedisRepository.findByTaskId(id)
            .map(task -> ServerSentEvent.<Task>builder().data(task).build());
    }
}

@Repository
public class TaskRedisRepository {
    public Flux<Task> findByTaskId(String id) {
        return template.keys("task:" + id).flatMap(template.opsForValue()::get);
    }
}

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@EqualsAndHashCode
@Entity
public class Task {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    @Column(length = 25)
    private String result;
}

The client consumes using JS:
var evt = new EventSource("http://localhost:8080/reactive-task/get/98"); evt.onmessage = function(event) {
  console.log(event);
};

Can anyone point me in the right direction?
Any advice would be appreciated.
Update: I need to store data for some time (5-10 mins) in Redis.
Update: I wrote similar code on MongoDB and it works fine.
Answer: In this case, taskRedisRepository.findByTaskId(id) is probably sending a finite Flux - meaning several elements and a complete signal finishing the stream.
Spring WebFlux will interpret the onComplete signal as the end of the stream and will close it. The default behavior of browser SSE clients is to reconnect right away to the endpoint in case the connection has been terminated.
If you wish to keep a persistent connection and only be notified of new elements being added, you need to leverage that directly as a feature of your datastore. For Redis, this mode is supported with the pub/sub feature (see reference documentation).
To summarize, I think you're seeing the expected behavior as in this case your datastore won't produce an infinite stream notifying you of new elements added to the collection, but rather a finite stream of elements present in that collection at a given time.


making a copy of the list but with following changes:

Question: I'm writing a function that takes as a parameter a list but returns a copy of the list with following changes:
• Strings have all their letters converted to upper-case
• Integers and floats have their value increased by 1
• booleans are negated (False becomes True, True becomes False)
• Lists are replaced with the word "List"
this function should leave the original input unchanged
This is what I have done so far but I'm not sure how can I add all of these to an empty list, here is my program:
name = [1, 2, "abc123", True, [1, 2, 3]]

new_list = [ ]

for element in name:

    if(type(element) == str):
        for i in element:
            if(i.isalpha()):
                element = element.upper()
        new_list += element
        #print(new_list)
        print(element)

    elif(type(element) == int):
        element = element + 1
        print(element)

    elif(type(element) == bool):
        print(not(element))
    else:
        print("list")

Comment: new_list.append(new_item) is all you need.
Answer: This is much easier if you make a function to handle individual cases first.
def convert(item):
    if isinstance(item, str):
        return item.upper()
    if isinstance(item, bool):
        return not item
    if isinstance(item, list):
        return "List"
    if isinstance(item, int) or isinstance(item, float):
        return item + 1
    raise ValueError("invalid type: {}".format(type(item)))

Once we have this, we can just apply a map:
map(convert, my_list)

And if you desperately need it to be a list and not just an iterable, convert it to a list:
list(map(convert, my_list))

Answer: you were so close and fell down on the last hurdle. Just use append to add to the empty list.
name = [1, 2, "abc123", True, [1, 2, 3]]

new_list = [ ]

for element in name:

    if(type(element) == str):
        for i in element:
            if(i.isalpha()):
                element = element.upper()

        new_list.append(element)

    elif(type(element) == int):
        element = element + 1
        new_list.append(element)

    elif(type(element) == bool):
        new_list.append(not element)
    else:
        new_list.append('list')

Comment: I think it's unpythonic to use `type(x) == foo` instead of `isinstance(x, foo)` in this case. See: http://stackoverflow.com/a/1549854/3377150
Comment: That's fair, but I think the spirit of this site would suggest that we guide the questioners in finding a better solution than their own, where appropriate. In this case, I think it's worth at least pointing out to OP that `isinstance` is generally preferred over `type` for such things.
Comment: @PierceDarragh I won't disagree with that. But the OP clearly put effort in and had one missing step. If you want to elaborate then you should at least say what they were missing before jumping forwards. If they missed `append` then how will they understand `map`?
Comment: That's a really good point, yeah. I guess I was answering the question "How do I do X?" when the intended question was more "What is wrong with my code?" I've given you an upvote, but I'll leave my answer as an alternative solution. :)
Comment: @PierceDarragh that may be so, but the question said only "I'm not sure how can I add all of these to an empty list" and so I made the minimum modifications to make it work with original work to fill in the gap.
Comment: i have another question, instead of making a new list that I'm adding to how can i mutate my original list to do all this
Comment: @SyedNaqi Good question :) Stack Overflow operates, almost always, on a single question at a time. Have a go and, if you get stuck, you need to raise as a new question. Make sure you show your efforts moving on from this point.
Comment: I understand that, but the function does the same thing the only difference is that instead of making a copy of the original list we are changing the list itself. I have tried to use some of the list methods but they are not working also I think I can just make my original list empty and than add to it, but that wouldn't be a efficient.
Comment: @SyedNaqi again, it's not directly to do with this question so, should you get stuck, it needs to be raised as a new question. You don't make a copy of the list in this code, you build one from scratch (you start with `[]` and `append` to it bit by bit). You might not think it efficient, but I can't think of a more efficient way of modifying your original list to match all your constraints. Just build a new one.


Proving matrix equation: $GM^\top(MGM^\top)^{-1}MG=G$

Question:
I want to show $$GM^\top(MGM^\top)^{-1}MG=G$$ where $MGM^\top$ is invertible, $G$ is a symmetric square matrix. $M$ does not have to be a square matrix. I am not 100% sure this is true (90% sure it is) so a contradictory proof will be great as well.

Thanks Justingpassby for the contradictory proof. I came into above from the following but I'm not sure where it is wrong?
Let $u = Mv$, $\text{var}(v)=G$, $u$ and $v$ be both Normal random variables with mean 0 so $\text{var}(u)=MGM^\top$.
Then $v=GM^\top(MGM^\top)^{-1}u$ is one possible solution of $u = Mv$ since
$$ Mv=MGM^\top(MGM^\top)^{-1}u = u.$$
Now $$\begin{array}\text{var}(v) &=& GM^\top(MGM^\top)^{-1}MGM^\top(MGM^\top)^{-1}MG\\
&=& GM^\top(MGM^\top)^{-1}MG
\end{array}$$
Therefore $GM^\top(MGM^\top)^{-1}MG=G$. But as shown this it not true for some non-square $M$ so there must be a hole in my logic somewhere above. Any idea anyone?
Comment: Might be worth noting that the rest of the expression after the first $G$ on the lhs gives the orthogonal projection onto the row space of $M$ relative to the scalar product defined by $G$.
Comment: I do not understand the first line in the expression for $var(v).$
Comment: It is variance of $v$ but fair enough, this bit is statistical.
Comment: But where does it come from? It does not seem to follow the same rule as your earlier computation of $var(u).$
Comment: Hi, we let $var(v) = G$. Then since $u=Mv$ and it is normal rv, it follows that $var(u) = MGM^\top$.
Answer: Let $G$ be the unit 3 by 3 matrix and $M$ any nonzero 1 by 3 row. Then the LHS has rank 1 (and determinant 0).
Comment: Thanks, elegant contradictory proof. I just added my logic of how I got to this but I'm not sure where it fell short. Will you be enlighten me where it might have gone wrong?
Comment: I would like to understand where the equality $\text{var}(v)=GM^\top(MGM^\top)^{-1}MGM^\top(MGM^\top)^{-1}MG$ comes from. It gives you the variance of a *possible* $v$ that solves $u=Mv$ but there is no guarantee that it is the variance of the original $v$ that you started with.
Comment: Actually you are correct. That is probably where my logic failed. Sorry must have been staring at the problem too long to not realise that obvious -.-
Answer: If $L$ is the left side, $$M L M^T = (MGM^T)(MGM^T)^{-1}(MGM^T) = MGM^T$$
If $M$ is a square matrix, $M$ must be invertible for $MGM^T$ to be invertible, so $L = G$. If $M$ is not square, then as Justpassingby noted $L$ does not have full rank, whereas $G$ could have full rank.
Answer: Formally,
$$(MGM^\top)^{-1}= M^{\top(-1)}G^{-1}M^{-1}$$
So
$$\begin{align}
GM^\top(MGM^\top)^{-1}MG &= GM^\top M^{\top(-1)}G^{-1}M^{-1} MG \\
& = G
\end{align}$$
since everything else cancels.
This assumes that both $G$ and $M$ are invertible.


The conditional expectation of a positive random variable is positive

Question: How can the following property of conditional expectation can be proven: $X \ge 0 \implies E[X|G] \ge 0$?
Answer: Hint: If $\Bbb E[Y\Bbb 1_E]\ge0$ for every measurable set $E$ then $Y\ge0$ almost surely.
Comment: Could you expand on that. The case $E \in G$ is trivial. But what about a general measurable set?
Answer: $$ E[X | G] = \int_{-\infty}^{\infty} xf_{x|g}(x|g)dx $$
$X \geqslant 0$, and $ 0 \leqslant f_{x|g}(x|g) \leqslant 1$ because $f_{x|g}(x|g)$ it is a probability distribution function.  Thus, $E[X | G] \geqslant 0$ because it is a sum of products of non-negative numbers.
The discrete case is similar:
$$ E[X | G] =  \sum_x xf(x|G) $$
Similarly, this is a sum of products of non-negative numbers, so $E[X|G] \geqslant 0$.
Comment: It is not necessary that $X$ has a conditional density. Also, you should not assume the general $G$ can be represented by some random of variable $Y$.
Comment: The y's were typos; fixed.  Thanks for pointing it out.
Comment: The problem still exists, in general $E(X|G)$ doesn't have the integration or summation representation as you presented. You need some measure-theoretic probability knowledge to show this rigorously.
Comment: What does the notation $f_{x|g}(x|g)$ mean?
Comment: The pdf of the conditional distribution X|G


Proof that bilinear form is coercive

Question: Hi everyone I'm stuck with a proof and would be happy if anyone could help me out.
Let V be a Hilbert Space and $A:V\times V \rightarrow \mathbb{R}$ symmetric, elliptic (coercive with constant $\alpha1$) and continuous (with constant $\alpha2$) bilinear form. We define of the space $X := V \times V$ the bilinear form $B : X \times X \rightarrow \mathbb{R}$ with
\begin{align*}
B((u_1,u_2),(v_1,v_2)) := A(u_1,v_1) + A(u_1,v_2)+ A(u_2,v_2) \  \forall (u_1,u_2),(v_1,v_2) \in X
\end{align*}
Show that $B$ is coercive with constant ? .  Let $X_N\subset X $ be a linear subspace. Is $B$ also coercive on $X_N$?
Here is my try:
By definition $B$ is coercive on $X$ if
\begin{align*}
B(z,z)\geq \beta ||z||^2_X \ \forall z \in X, \ \beta \in \mathbb{R^+}
\end{align*}
If $z \in X$ arbitrary we have $z=(u,v)$ for some arbitrary $u,v \in V$. Then we have
\begin{align*}
B(z,z)=B((u,v),(u,v)) = A(u,u) + A(u,v)+ A(v,v)
\end{align*}
Now we can use that $A$ is coercive with constant $\alpha_1$ to get
\begin{align*}
B(z,z)=B((u,v),(u,v)) \geq \alpha_1||u||^2_V + \alpha_1||v||^2_V + A(u,v) \\ \geq (\alpha_1 + \frac{A(u,v)}{||u||^2_V + ||v||^2_V})(||u||^2_V + ||v||^2_V)
\end{align*}
Note that the left term defines a norm on $X$ so we have $||z||^2_X := (||u||^2_V + ||v||^2_V)$. This follows by the properties of the given $||\cdot||_V$ Norm on $V$. Therefore the coercivity constant $\beta$ of $B$ must be
\begin{align*}
\beta = \inf_{u,v \neq 0}(\alpha_1 + \frac{A(u,v)}{||u||^2_V + ||v||^2_V})
\end{align*}
If $B$ is coercive we need $\beta>0 \forall u,v \in V$.
Is this proof right so far? Now I dont know how to show that $\beta>0$ since I dont know about $A(u,v)$.
Answer: You can estimate
$$
|A(u,v)| \le \alpha_2 \|u\|_V\|v\|_V \le \frac{\alpha_2}2(\|u\|_V^2 + \|v\|_V^2).
$$
Then you get coercivity of $A$ under the condition $\alpha_1 \ge\frac{\alpha_2}2$.
However, one can do better.
Since $A$ is symmetric,
it holds
$$
B(z,z) = A(u,u) + A(v,v) + \frac12 ( A(u,v) + A(v,u))\\
= \frac34 A(u+v,u+v) + \frac14 A(u-v,u-v).
$$
This decomposition is inspired by the eigenvalue decomposition of $\pmatrix{1&\frac12\\\frac12&1}$.
This proves
$$
B(z,z) \ge \frac{\alpha_1}4 ( 3\|u+v\|_V^2 + \|u-v\|_V^2).
$$
Since $\|u\| \le \frac12\| (u+v) + (u-v)\|$ and $\|v\|_V\le \frac12\|(u+v)-(u-v)\|_V$,
this proves that $B$ is coercive.
Comment: Now that answer made me happy since I got after some more thinking the same estimate like you stated. But by above its coercive without any restrictions. You stated also that the decomposition is related to the decomposition of $\pmatrix{1&\frac12\\\frac12&1}$, that is $\frac12\pmatrix{-1&1\\1&1}\pmatrix{\frac12&0\\0&\frac32}\pmatrix{-1&1\\1&1}$. Can you maybe explain a bit how I could think about this, so that I can next time come up with such an idea by myself.
Comment: Think of $A$ as a constant number and of $B$ as a quadratic from on $\mathbb R^2$.

Proof that bilinear form is coercive


A solution to the equation $\frac{1}{x}=0$

Question: The number $i$ is defined as a solution to the equation $x^2+1=0$.
How come no one has yet defined a number $j$ as a solution to the equation $\frac{1}{x}=0$?
The purpose of course is to be able to solve different equations, such as $\frac{1}{x^2}=0,\frac{2}{x}=0$, etc.
Another way to look at this, is by using $j$ in order to define different (distinct) values of $\infty$.
Comment: @TomCollinge $\infty$ is not a number.
Comment: I don't think you will get definitions of different infinities out of this. The definition of "division" for infinite cardinals is very restrictive and certainly won't cover a zero case such as yours. See for example the Division section in http://en.wikipedia.org/wiki/Cardinal_number#Division
Answer: The problem with this is that it is simple to prove that $0\cdot x = 0$ for any number $x$. Thus, if $\frac 1x = 0$, that means that $x\cdot \frac1x = x\cdot 0$ meaning that $1=0$ which is not true.
This means that if there exists a number for which $\frac{1}{x}=0$, then some of the standard axioms of multiplication must not hold for such a number.
Comment: Thanks for explaining that :)
Comment: Every time you have $1_A=0_A$ this implies that a ring $A(+,\cdot)$ is consisting only of one element, namely $A=\{0\}$.
Answer: The problem is that you can define all you want, but then you need to figure out what you can do with that number. For example, if j is the solution of 1/x = 0, what would be the solution of 2/x = 0? What are the properties of j?
Of course you can make this a bit clearer and instead of the name "j" you use the name "error", with the understanding that error + x = error - x = error * x = error / x = x - error = x / error = error, whatever real or complex number x is. That's just not very useful. And then you run into trouble when a correct calculation shows you for example that the solutions to a problem are all values x that solve x^2 = 1 or 1/x = 0. So instead of two solutions +1, -1 you suddenly have three solutions +1, -1 and error, which is quite rubbish.
Or, the answer in short: We don't do this because it is a rubbish idea that is in no way helpful.


Vector spaces versus subspaces

Question: I have learned that vector spaces satisfy the 8 properties including $(u+v)+w=u+(v+w)$ or $v+w=w+v$ , etc. but I'm now confused with the following question:
Are vector spaces closed under addition? In other words, if $a, b$ are in vector space $V$, is $a+b$ also in $V$?
Basically why I'm confused is because I've thought that this was a property for a 'subspace' of a vector space...
Comment: The question is meaningless: a vector space is endowed with a group law, which by definition is an *internal* law.
Comment: I'd say this is the very first, basic axiom a set with a binary operation on it must fulfill in order to have any aspiration to a vector space. In fact, the very name "binary operation" many times already includes the meaning of "closed operation" .
Comment: Yes.  Subspace of a vector space is just a vector space inside another vector space, so you have $a, b \in W \implies a+b \in W \subseteq V$
Answer: Closure under addition is a foundamental property for vector spaces and thus also for vector subspaces.
Answer: Usually, when you define a vector space you define addition to be a function of the type $+:V\times V\to V$ (some call this a binary operation on $V$). Since the codomain of $+$ is $V$, it is obvious that for all $v,w\in V$, $v+w$ is also in $V$.
Now, if you consider a subset $W$ of $V$, it is not necessarily true that for all $w_1,w_2\in W$, $w_1+w_2$ lies in $W$ (for it is only guaranteed to lie in $V$).
Answer: A vector space is closed under addition by definition.
A subspace of this is a subset that is also a vector space in its own right. So it too must be closed under addition.

Vector spaces versus subspaces


Is locally completeness a topological property?

Question: I know that completeness itself is not a topological property because a complete and a not complete metric space can be homeomorphic, e.g. $\Bbb R$ and $(0,1)$.
However, both $\Bbb R$ and $(0,1)$ are locally complete (each point has a neighborhood that is complete under the induced metric). As all examples I know of are of this form, the naturally occuring next question is

Question: Is being locally complete a topological property?

Or the other way around: are there metric spaces which are homeomorphic, but one is locally complete and the other one is not?
Comment: @Thompson That terminology is not used in the question.
Comment: How is $(0,1)$ locally complete?
Comment: @ngenisis Any $x\in(0,1)$ has a small closed interval $[x-\epsilon,x+\epsilon]\subset(0,1)$. This interval is complete.
Comment: Ah, I'm accustomed to neighborhoods being open by definition.
Comment: @ngenisis Oh. I learned that a neighborhood just *contains* an open set that contains the point.
Comment: @M.Winter And you've learnt well.
Comment: What is a complete topological space?
Comment: my mistake. Apologies.
Comment: This result https://mathoverflow.net/questions/21954/locally-complete-space-is-topologically-equivalent-to-a-complete-space is a partial answer (the first hit when I googled "locally complete space")
Comment: @Thompson I know of this question. As far as I can tell it does not answer my question, it just says if there is a locally complete metric, then there is a complete one. Maybe I am missing how it can help here. Please explain. I understand this post, so one can refer to it in an answer.
Comment: I see. I'm making a big mess of this so I think I'll bow out of trying to add anything useful!
Comment: @Thompson: maybe the idea in the question https://math.stackexchange.com/questions/1071275/quasi-cauchy-sequences-in-general-topology could be used to define a "complete topological space"?
Answer: The irrational numbers are not locally complete, but they are homeomorphic to the Baire space $\mathbb N^{\mathbb N}$, which can be given a metric turning it into a complete metric space.
(For example, endow $\mathbb N$ with the discrete metric and set $d(s, t) = \sum_{i=0}^\infty\frac{1}{2^i}d(s_i,t_i)$).
Comment: +1. And for the OP, thinking about this counterexample can lead to considering local *compactness*, which is of course a topological property (and one which Baire space lacks).
Comment: It's not obvious (I never used that word), just well known.  Essentially, you map an irrational number to the coefficients in its continued fraction representation.  See the Wikipedia article I linked to for details.
Comment: I would be glad if you can show the "obvious" homeomorphism between the irrationals and $\Bbb N^{\Bbb N}$ (with what topology?). I am a bit confused whether the example below should show me the complete or incomplete metric.
Comment: The topology on $\mathbb N^{\mathbb N}$ is the product topology.  Equivalently, it is the topology induced by the metric I provided, which makes the space into a complete metric space.
Answer: Another way of proving that the irrationals can be made complete with respect to a metric $d$ which is equivalent to the usual one consists in providing such a metric. This can be donne as follows: let $(q_n)_{n\in\mathbb N}$ be an enumeration of the rationals. Then, if $x,y\in\mathbb{R}\setminus\mathbb Q$, define$$d(x,y)=|x-y|+\sum_{k=1}^\infty2^{-k}\inf\left(1,\left|\max_{i\leqslant k}\frac1{|x-q_i|}-\max_{i\leqslant k}\frac1{|y-q_i|}\right|\right).$$


Como se chama este recurso do C#

Question: Eu sempre via isto no c#
var button = new Button(this.ApplicationContext);
button.Text = "New button;

Só que agora vi que da forma abaixo também da, acessando as propriedades diretamente com {, como se chama este recurso?
var button = new Button(this.ApplicationContext)
 {
      Text = "New button"
 };

Answer: Isto é um inicializador de objeto. Na prática, o que o C# faz é transformar a segunda forma na primeira ao compilar seu código.
Veja que isso não é a mesma coisa que um construtor. Este código é executado depois da construção do objeto Button, do seu exemplo.

Como se chama este recurso do C#


How to redirect in WebformHandler after submitting Ajax form

Question: I'm trying to redirect to a results page after a form that uses Ajax is submitted. The form is a semi long multi step form, so Ajax is enabled for the user experience.
I have created a new WebformHandler and I'm using the confirmForm() method, but I'm having difficulties to make the redirect work. The 'Confirmation' setting in my Webform is set to 'None'. I also don't see errors in the logs.
namespace Drupal\burnout_module\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Send values to the matching API and get results back, redirects to results page
 *
 * @WebformHandler(
 *   id = "matching_api_handler",
 *   label = @Translation("Matching API"),
 *   category = @Translation("Webform Handler"),
 *   description = @Translation("Send values to the matching API and get results back, redirects to results page."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class MatchingApiWebformHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */

  public function confirmForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

    // Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // $result = ... code for calculating results with form values

    $url = \Drupal\Core\Url::fromRoute('burnout.match')->setRouteParameters(array('result' => json_encode($result)));
    $form_state->setRedirectUrl($url);

  }

}

I have also tried other possibilities:

Using a RedirectResponse which gave me a 'Headers already sent' error
AjaxResponse with a RedirectCommand, nothing happens, no errors

Hopefully someone can point me in the right direction.
Kind regards
Comment: Does this answer your question? [How to do a hard redirect when in ajaxified form?](https://drupal.stackexchange.com/questions/243587/how-to-do-a-hard-redirect-when-in-ajaxified-form)
Comment: Hi baikho, unfortunately it didn't... I got it working by using an Ajax submit callback, see: https://drupal.stackexchange.com/questions/298443/webform-alter-with-ajax-submit-callback-field-values-are-empty-in-callback
Comment: If you came up with a solution then you should post it as an answer and accept it.
Answer: I got it working with another approach, instead I used the form_alter hook and added an ajax submit callback.
See Webform alter with ajax submit callback - field values are empty in callback


multiple command execution

Question: I have created a installer with innosetup and i wanna use it to create a postgresql database using psql.exe .
I call the psql.exe with this line of code :
Filename: "{app}\PostgreSQL\bin\psql.exe"; Parameters: "-W postgres";
The problem is that psql ask for user password and there is no option to pass it in one call .
Is it possible to simulate the "Enter" key and add the password just after ?
If there is another solution let me know please.
Thanks .
Answer: There is the PGPASSWORD environment variable:

PGPASSWORD behaves the same as the password connection parameter. Use of this environment variable is not recommended for security reasons, as some operating systems allow non-root users to see process environment variables via ps; instead consider using the ~/.pgpass file.

As mentioned, there is also the password file but the environment variable would probably be fine for an installer. In either case you'd drop the -W switch.
You could also build a special purpose tool to talk to PostgreSQL directly rather than go through psql.exe.
Comment: That environment variable can also be set for Inno (and subsequant child processes) by using the [Win32 SetEnvironmentVariable() function](http://msdn.microsoft.com/en-us/library/ms686206(v=vs.85).aspx).
Comment: @Deanna: Thanks, that's useful information. I'm a lot more familiar with PostgreSQL than Inno.
Comment: how can i use the PGPASSWORD to login ?
Comment: @isoman: If you set the `PGPASSWORD` environment variable to the password before running `psql.exe postgres` (no `-W` needed), it should work.

multiple command execution


C / binding multiple sockets [on differnet ports]

Question: I want to bind 4 sockets on different ports. Somehow I get always the : Address already in use error. For the first loop, the case PORT1 it is working, but when coming to the second run I get the above mentioned error. It would be nice, if someone could take a closer look at my code.
The output looks like that:
thread 0 started, pc_packet_receiver
sock_fd[8]
sock_fd[8], fdmax[8]
sock_fd[9]
error: could not bind UDP socket, port2
: Address already in use

As you can see, the first printf in the loop is processed twice and when bind is called for PORT2 the program crashes.

sock_fd is an array of file descriptors
sock_addr_port[1..4] are four different struct sock_addr
the values PORT1/PORT2/PORT3/PORT4 are defined in an enum [1..4]
in the end I want to add all sock_fd[i] into a FD_SET to processing them with select

thank you very much in advance for your help.
for(i = 0; i < 4; i++) {

    if((sock_fd[i] = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("error: could not open UDP socket\n");
        exit(EXIT_FAILURE);
    }

    printf("\tsock_fd[%d]\n", sock_fd[i]);

    switch (i+1) {
        case PORT1:
            bzero(&sock_addr_port1, sock_len_port1);
            sock_addr_port1.sin_family = AF_INET;
            sock_addr_port1.sin_port = htons(ETH_PORT1);
            sock_addr_port1.sin_addr.s_addr = htonl(INADDR_ANY);

            if(bind(sock_fd[i], (struct sockaddr *) &sock_addr_port1, sock_len_port1) < 0) {
                perror("error: could not bind UDP socket, port1\n");
                exit(EXIT_FAILURE);
            }

            break;
        case PORT2:
            bzero(&sock_addr_port2, sock_len_port2);
            sock_addr_port2.sin_family = AF_INET;
            sock_addr_port2.sin_port = htons(ETH_PORT2);
            sock_addr_port2.sin_addr.s_addr = htonl(INADDR_ANY);

            if(bind(sock_fd[i], (struct sockaddr *) &sock_addr_port2, sock_len_port2) < 0) {
                perror("error: could not bind UDP socket, port2\n");
                exit(EXIT_FAILURE);
            }

            break;
        case PORT3:
            bzero(&sock_addr_port3, sock_len_port3);
            sock_addr_port3.sin_family = AF_INET;
            sock_addr_port3.sin_port = htons(ETH_PORT3);
            sock_addr_port3.sin_addr.s_addr = htonl(INADDR_ANY);

            if(bind(sock_fd[i], (struct sockaddr *) &sock_addr_port3, sock_len_port3) < 0) {
                perror("error: could not bind UDP socket, port3\n");
                exit(EXIT_FAILURE);
            }

            break;
        case PORT4:
            bzero(&sock_addr_port4, sock_len_port4);
            sock_addr_port4.sin_family = AF_INET;
            sock_addr_port4.sin_port = htons(ETH_PORT4);
            sock_addr_port4.sin_addr.s_addr = htonl(INADDR_ANY);

            if(bind(sock_fd[i], (struct sockaddr *) &sock_addr_port4, sock_len_port4) < 0) {
                perror("error: could not bind UDP socket, port4\n");
                exit(EXIT_FAILURE);
            }

            break;
        default:
            break;
    }

    FD_SET(sock_fd[i], &read_fds);
    fdmax = sock_fd[i];
    printf("sock_fd[%d], fdmax[%d]\n", sock_fd[i], fdmax);
}

Comment: Unless you defined `ETH_PORT2` to be the same as `ETH_PORT1` it shouldn't be a problem. A small note though: There is lot of duplicated code, in the `switch` statement just set the port to bind to, and do the actual `bind` (together with all other setup) after the `switch` statement.
Comment: What are `ETH_PORT1`, `ETH_PORT2`, etc ?
Comment: guys, thanks so much, I made a "stupid" mistake when copying some lines, of course you are right, `ETH_PORT1` and `ETH_PORT2` were defined with same value :( man!!! now it is working. should I delete that question?!
Answer: There is another process running which uses ETH_PORT2 right now. You should be able to see this when you run netstat -tan (-tn on Windows) on the command line.
Google for "which process uses which port" to see how you can find out the process.


How can I alter bundles of commerce_order_item entity type using custom module

Question: I am trying to alter bundles of commerce_order_item -
core.entity_form_mode.commerce_order_item.add_to_cart_confirmation.yml
langcode: en
status: true
dependencies:
  module:
    - commerce_order
  enforced:
    module:
      - commerce_add_to_cart_confirmation
id: commerce_order_item.add_to_cart_confirmation
label: 'Add to Cart Confirmation'
targetEntityType: commerce_order_item
cache: true

.module file
function commerce_add_to_cart_confirmation_entity_bundle_info_alter(&$bundles){
  $storage = \Drupal::entityTypeManager()->getStorage('entity_form_display');
  foreach ($bundles['commerce_order_item'] as $bundle_key => $bundle_value) {
    if($bundle_key !== 'default'){
      $form_display = $storage->load('commerce_order_item.' . $bundle_key . '.add_to_cart_confirmation');
      if (!$form_display) {
        /** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
        $form_display = $storage->create([
          'targetEntityType' => 'commerce_order_item',
          'bundle' => $bundle_key,
          'mode' => 'add_to_cart_confirmation',
          'status' => TRUE,
        ]);
        // Hide the unit price by default.
        $form_display->removeComponent('unit_price');
        // Hide the quantity by default.
        $form_display->removeComponent('quantity');
        $form_display->save();
        $form_display->enable();
      }
    }
  }
}

But at $form_display->save(); is am getting below error -
Error: Call to a member function getConfigDependencyName() on null in /var/www/drupal/core/lib/Drupal/Core/Entity/EntityDisplayBase.php on line 314 #0 /var/www/drupal/core/lib/Drupal/Core/Config/Entity/ConfigEntityBase.php(346): Drupal\\Core\\Entity\\EntityDisplayBase->calculateDependencies()\n#1 /var/www/drupal/core/lib/Drupal/Core/Entity/EntityDisplayBase.php(266): Drupal\\Core\\Config\\Entity\\ConfigEntityBase->preSave(Object(Drupal\\Core\\Config\\Entity\\ConfigEntityStorage), true)\n#2 /var/www/drupal/core/lib/Drupal/Core/Entity/EntityStorageBase.php(434): Drupal\\Core\\Entity\\EntityDisplayBase->preSave(Object(Drupal\\Core\\Config\\Entity\\ConfigEntityStorage))\n#3 /var/www/drupal/core/lib/Drupal/Core/Entity/EntityStorageBase.php(389): Drupal\\Core\\Entity\\EntityStorageBase->doPreSave(Object(Drupal\\Core\\Entity\\Entity\\EntityFormDisplay))\n#4 /var/www/drupal/core/lib/Drupal/Core/Config/Entity/ConfigEntityStorage.php(259): Drupal\\Core\\Entity\\EntityStorageBase->save(Object(Drupal\\Core\\Entity\\Entity\\EntityFormDisplay))\n#5 /var/www/drupal/core/lib/Drupal/Core/Entity/Entity.php(377): Drupal\\Core\\Config\\Entity\\ConfigEntityStorage->save(Object(Drupal\\Core\\Entity\\Entity\\EntityFormDisplay))\n#6 /var/www/drupal/core/lib/Drupal/Core/Config/Entity/ConfigEntityBase.php(637): Drupal\\Core\\Entity\\Entity->save()\n#7 /var/www/drupal/modules/custom/commerce_add_to_cart_confirmation/commerce_add_to_cart_confirmation.module(116)

This is annoying because same code is running for hook_confirmation_entity_bundle_create($entity_type_id, $bundle). Please advice what should I do to save the bundle.If there is another way to achieve what I am trying to achieve, please tell me.
Thanks Guys
Answer: add_to_cart_confirmation needs to be a a defined entity form mode, that's most likely the error in your case. Provide it as default configuration in your module or check its existence or create it if necessary.
See how node defines the teaser view mode as an example, or user the register form mode.
Comment: I provided form_mode yml file also. But still it gives the same error. I have updated yml file above in the question.


fuel cms of codeigniter not working

Question: I am installing codeigniter based cms FUEL CMS. I followed all the steps. But when I am tring to open http://localhost/ci_cms/fuel on localhost then it is redirecting me to http://localhost/xxamp/
But if typing http://localhost/ci_cms/index.php/fuel/login then it is working
this is what i got in index.php in http://localhost/ci_cms/fuel/
<?php
  header('Location: start');
  exit();

No htaccess file here . Please advise me what I'm missing in my installion setup.
Answer: http://docs.getfuelcms.com/installation/installing
When you downloaded fuelCms after extracting. You have below folder structure
assets -> Folder
fuel   -> Folder
.gitignore
.htaccess
index.php  -> Fuel CMS Master Index File
README.md
robots.txt

Now, in your opencart structure now structure should like
 admin
 catalog
 download
 fuel -> Copied folder from fuel CMS

Now open your fuel folder replace current index.php file with "Fuel CMS Master Index File" then it works. In this index.php make sure INSTALL_ROOT will be correct. remove fuel from end.
So it should be
define('INSTALL_ROOT', str_replace('\\', '/',realpath(dirname(__FILE__))).'/');

Comment: where is the opencart  folder
Comment: You got Welcome to Fuel message? By running localhost//fuel ??
Comment: http://localhost/ci_cms/index.php/fuel/login is working but now how to remove index.php from url ...i followed all the steps now it becoming little bit messy
Comment: That you can do using .htaccess
Comment: now where to put this .htaccess file in  localhost\ci_cms\fuel\modules    or localhost\ci_cms\fuel\     or       localhost\ci_cms\
Comment: Inside fuel folder localhost\ci_cms\fuel\
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/76339/discussion-between-vipul-sharma-and-jack).
Answer: add this to your .htaccess
< IfModule mod_rewrite.c >

    RewriteEngine on
    RewriteCond $0 !^(index\.php|css|js|images|robots\.txt)
    RewriteRule .* index.php/$0 [L]

< /IfModule >

and change in system/application/config/config.php.
$config['index_page'] = "";

Answer: Edit your root .httaccess
then change the value of RewriteBase  to be just a slash. So it should look like this
    RewriteBase /

fuel cms of codeigniter not working


Twig cache won't disable

Question: I've set up my development setup and it works great but for some reason I can't get the twig cache to disable. I tried everything, but I have to run drush cr every time I change anything in twig templates, and it's driving me insane.
settings.php:
if (file_exists(__DIR__ . '/settings.local.php')) {
  include __DIR__ . '/settings.local.php';
}

settings.local.php AND setting.php:
$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;

$settings['cache']['bins']['render'] = 'cache.backend.null';

$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

services.yml AND development.services.yml
parameters:
  http.response.debug_cacheability_headers: true
  twig.config:
    debug: true
    auto_reload: true
    cache: false
services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory

I am running Drupal 8.4
Answer: In Drupal 8.4 you have to set the null cache backend for an additional cache bin, so now there are three:
settings.local.php:
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['page'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

This is because the cached pages for anonymous users moved to a separate cache bin, see the change record The internal page cache now has a dedicated cache bin.
Comment: If you have an error like _You have requested a non-existent service "cache.backend.null"_, see also : [cache.backend.null is defined in development.services.yml](https://drupal.stackexchange.com/questions/303820/drupal9-dev-mode-local-settings-non-existing-cache-backend-null)
Answer: Use the Mix module to disable drupal caches during development by just toggling an "Enable development mode" checkbox, which will saving us a lot of time in settings*.php and services*.yml files.
Comment: Version tags should be used for questions that apply to a version only, not to merely say what version a site is using. Please stop adding tags.

Twig cache won't disable


Verify the limit using the definition of convergence of a sequence

Question: I know that the definition is:
"A sequence $(s_n)$ is said to converge to the real number $s$ provided that for every $\epsilon > 0$ there exists a natural number $N$ such that for all $n \in \mathbb{N}$, $N \leq n$ implies that $|s_n - s | < \epsilon$".
So here is an exercise in the problem section of the chapter:
"Verify the limit using the definition of convergence of a sequence that:
$\lim_{n \to \infty} \frac{\sqrt[]{n}}{n+2} = 0$"
I don't know how to really start. I guess, given any $\epsilon$ we want to make $|\frac{\sqrt[]{n}}{n+2} - 0| < \epsilon$. Looking at:The definition of a sequence converging.
So, lets pick a value for epsilon, $\epsilon = 0.5$. Now we have to find a natural number $N$ s.t. for $n \in \mathbb{N}$, $|s_n - s| < \epsilon$. So, we have to solve for $n$ in $\frac{\sqrt[]{n}}{n+2} < \frac{1}{2}$.
Couldn't that be quite messy with other limit problems? I suppose we could use the fact if $a < b$ and $b < c$, then $a < c$, but i'm not sure how exactly to find something larger than $\frac{\sqrt[]{n}}{n+2}$ .
Comment: It's $n \rightarrow \infty$, not $x \rightarrow \infty$. (Inside the limit).
Comment: whoops, sorry. Edited accordingly
Answer: HINT:
$$\frac{\sqrt{n}}{n+2}<\frac{\sqrt{n}}{n}=\frac{1}{\sqrt{n}}.$$
Now compare
$$\frac{1}{\sqrt{n}}\sim \varepsilon.$$
Comment: My trouble is finding the other $f(n)$ that is larger than my original $f(n)$.
Comment: Why do you want the 'the other $f(n)$' to be larger? You want $\sqrt{n}/n+2$ to be small and clearly we can make it small by taking $n>1/\varepsilon^2$.
Comment: What? We're trying to make another sequence $f_n$ s.t. it is greater than our original sequence but less than epsilon. My trouble is creating/finding that sequence
Comment: Yes this $f_n$ is $\sqrt{n}/n$...
Answer: We want to prove that $\left | \dfrac{\sqrt{n}}{n+2} \right | <\epsilon$ for a sufficiently large $n$. Since $\dfrac{\sqrt{n}}{n+2} > 0$:
$$\dfrac{\sqrt{n}}{n+2} <\epsilon$$
$$\sqrt{n}< \epsilon (n+2)$$
Since both members of the inequality are positive, we can square them and the inequalilty holds:
$$n < \epsilon^2 (n+2)^2$$
$$n - \epsilon^2 n^2 - 4\epsilon^2 n - 4\epsilon ^2 < 0$$
$$-\epsilon^2 n^2 + (1-4\epsilon^2)n - 4\epsilon^2 < 0$$
Which is true for a sufficiently large $n$.


Validação de senha salva no SQLite

Question: Olá eu estou fazendo um projeto pra faculdade e eu sou novo no Android,estou fazendo um aplicativo que o intuito dele é Verificar se a senha está correta pra poder finalizar o aplicativo, porém não estou conseguindo validar a senha, eu não preciso validar outra coisa, apenas a senha.
Eu criei 3 telas uma para cadastro do usuário, onde é cadastrado o e-mail e a senha dele, quando ele cadastra ele vai para outra tela.
A segunda tela onde é pedido a senha para finalizar o app, e é nessa tela que eu preciso que a senha seja validada, para que a senha que ele cadastrou seja a unica que possa finalizar o app.
E a ultima tela é uma para recuperação da senha através do e-mail.
Eu estou usando esse código para o cadastro na primeira tela:
    editEmail = (EditText) findViewById(R.id.editEmail); //Determinando o ID das coisas
    editSenha = (EditText) findViewById(R.id.editSenha);

    db=openOrCreateDatabase("CadastroDB", Context.MODE_PRIVATE, null);
    db.execSQL("CREATE TABLE IF NOT EXISTS cadastro (Email VARCHAR, Senha VARCHAR);");
}

//Botão Cadastrar

public void btnCadastro (View view) {

    if(editEmail.getText().toString().trim().length()==0 || editSenha.getText().toString().trim().length()==0)
    {
        showMessage("Erro", "Preencha os Campos");
    }

    db.execSQL("INSERT INTO cadastro VALUES('"+editEmail.getText()+"','"+editSenha.getText()+"');");
    showMessage("Ok", "Dados Gravados");
    clearText();
    Toast.makeText(getApplicationContext(), "Redirecionando...", Toast.LENGTH_SHORT).show();
    setContentView(R.layout.activity_second);
}

Agora eu só preciso validar na tela 2 essa senha pra o projeto acabar... Se alguem puder ajudar agradeceria.
Comment: Mostre o que você tem na segunda tela.
Answer: Bom se você tem que realizar a validação da senha com o email do usuário você pode usar um método que retorna se a senha e o usuário existem no banco de dados, por exemplo:
private boolean validaSenha(String senha, String email) {

    // O Cursor recebe o resultado do select
    Cursor cursor = db.execSql("SELECT senha, email FROM cadastro WHERE senha = " + senha + " and email = " + email);

    // Retorna se o cursor tem 1 resultado com o email e senha informados
    return cursor != null && cursor.getCount() == 1;

}

Assim você pode fazer a verificação da seguinte forma:
if (validaSenha(senha, email)){

    //Código para fechar o aplicativo

}

Agora se você quiser realizar a validação somente pela senha, basta remover o parâmetro email da função e do select.

Validação de senha salva no SQLite


Poisson and Negative Binomial for safety stock

Question: I am currently an intern working on an inventory/stock policy and there is this particular modeling task on which I am blocked (and I have no statistical supervisor). I have a background mostly in economics with some applied econometrics, and I am out of my depths here.
AS IS:
They use a safety stock formula (the type 1, see wiki) to calculate their service level. This formula gives them a Z value (K in the formulate) that they plug into a standard normal distribution in order to get a theoretical service level (the minimum being 50% when safety stocks are 0 (K = 0)).
https://en.wikipedia.org/wiki/Safety_stock
They apply this for a calculated level of demand per leadtime and they want to apply this formula for demand that is assumed to follow a poisson or negative binomial distribution (low demand (few points), lots of zero demand periods).
So far, I have different ideas.
For example, apply a Johnson transformation on my data to normalise them, but it doesn't always work (using R packages like suppdist or jtrans). And then add the mean of the demand to K (to reach the minimum of 50%). A boxcox transformation could also be considered.
Another idea was to use the data to find the parameters, simulate the distribution (still problematic with small data) and shift the distributions to center at 0. The idea would be to reuse the K above. I did not find how to do such a shift to be honest or how to modify K so that it reaches the right values (min 50%).
Side note: Oracle Inventory Optimization and other APS seem to have a way to calculate the right negative binomial and poisson models, but I can't seem to find their technique...
I kindly ask for criticisms and hopefully improvement ideas. Ideally, I would like to know how to use the same principle used on the normal distribution (formula with K) and apply it to the Negative binomial and Poisson distributions.
Thank you
EDIT:
Problem solved.  As suggested by jbowman, applying the negative binomial on lead time demand works, I had to use the parameters calculated using the variance to mean ratio and the mean of lead time demand. The program (APS) whose results I had to reproduce used a maximum VMR in its parameters. Finally, for the poisson distribution I went with a Hermite distribution (assuming poisson demand and normal lead time).
Comment: Are you asking how to estimate the parameters of a Poisson or Negative Binomial distribution, or...?
Comment: I thought I might not be clear, I would like either the formula/method used (in Oracle or APS: servigistics) for the poisson and negative binomial distributions, or an indication on whether my current ideas are going in the right direction and if so, ideas on how to implement them. Thanks
Comment: You can look those distributions up on Wikipedia, for example, if all you need is the formula for the distribution.
Comment: This is not exactly what I need.  There is this formula parameter that follows a normal distribution ("K" in the safety stock wiki article). I would like to find a formula that I could use in case of poisson/negative binomial demand distribution.  Or a method that would give similar results.
Answer: As an opening comment, which you should not use to try to influence your management (especially given that you are an intern), Type I service level is almost always a terrible objective.  What it measures is the probability that you suffer no stockouts over the leadtime, but, from a business perspective, what you'd like to measure is, far more often, the expected number of stockouts over the order cycle $/$ the expected demand over the order cycle, i.e., the fraction of demands that go unfilled.  In some situations, e.g. stocking a helicopter for rescue missions where an out of stock could mean permanent disability or death, Type I service level is appropriate, but not in the usual business case.  I won't go into more detail, since it's off-topic, but include it here for your future information.
The Type I service level given an order point of $s$ is nothing more than the probability of seeing fewer than $s$ demands over leadtime.  As such, if you have a probability distribution of leadtime demand $F(x)$, and a target service level $\alpha$, the corresponding order point $s_{\alpha}$ is:
$$s_{\alpha} = F^{-1}_{LTD}(\alpha)$$
where $LTD$ refers to "leadtime demand".  In the case of the Normal distribution, it so happens that this is the same as:
$$s_{\alpha} = \mu_{LTD} + \sigma_{LTD}*z_{\alpha}$$
where $\mu$ is the mean demand, and $\sigma$ is the standard deviation of demand.  Where does $z_{\alpha}$ come from?  It's the inverse of the standard Normal distribution's cumulative density function at $\alpha$:
$$z_{\alpha} = F^{-1}(\alpha | \mu=0, \sigma=1)$$
and
$$F^{-1}(\alpha | \mu_{LTD}, \sigma_{LTD}) = \mu_{LTD} + \sigma_{LTD} F^{-1}(\alpha|\mu=0,\sigma=1) $$
So using $z_{\alpha}$ with the Normal distribution is the same as calculating the inverse of the cumulative distribution of leadtime demand, where leadtime demand is Normally distributed.
When you aren't working with the Normal distribution, you won't typically have any equivalent formula to make life appear simpler.  This is true of both the Poisson and Negative Binomial distributions.  In the case of these two distributions, it's most straightforward just to calculate order point from the initial equation, using the appropriate parameters for the leadtime demand distribution in question.
ETA:
For example, assume your daily demand has mean $0.2$ units and standard deviation $0.6$ units, and you have a leadtime of one week.  Then $\mu_{LTD} = 1.4$ and $\sigma_{LTD} = 1.59$.  The parameters of the Negative Binomial distribution are $r = 1.75$ and $p = 0.556$.
If you want to stock to a Type I service level of $95\%$, you'd solve for:
$$s_{\alpha} = F^{-1}_{LTD}(\alpha) = F^{-1}(\alpha=0.95;r=1.75,p=0.556) = 5$$
and your order point would be $5$.
Comment: I've added an edit with an example of how to perform the calculations in the Negative Binomial case.
Comment: Thank, this helped me moving forward with my problem.  I have been able to reproduce their APS' results for the poisson and normal distribution by using the reorder point.  Unfortunately, using the same technique for the negative binomial tends to give consistently higher results for the reorder point than is calculated by their APS.
I have also attempted to calculate the negative binomial assuming Gamma leadtime and poisson demand (by fitting parameters from the known mean and variances), unfortunately it consistantly under estimate the actual reorder point calculated by APS for NB dist.
Comment: There are different ways of parameterizing the negative binomial, so you might want to be careful about which one your tool is using.
Comment: Unfortunately, the code for the inventory management system is not public.  As it is considered the "right" one, we try to reach a similar answer.
With Gamma we find alpha and beta parameters to calculate the negative binomial parameters r=alpha+1 and p=beta/(beta + lambda) (lambda of the demand) and calculate from there.  The other way we use it to calculate r and p directly from the lead time demand'S variance and mean, that last one gives the farthest numbers. Would you be aware of the way industrial sofwares do the calculation ?
Comment: APS is SAP?  I know how it's done, but I can't be sure of the calculations that set up the NB distribution.  There may also be caps, like "no more than +2 std. deviations", or other ad-hoc rules attached to the process.
Comment: APS ("Advanced planning and scheduling") is a type of software used in inventory managemement.  I would expect SAP to have a similar function.  So, if I understood correctly, there is no standard industry way of doing it and each software could have its own specifications ?
Comment: That's correct.  APS is the name of an SAP module, I believe.
Comment: Well thank you, in the end I had access to a file containing some more informations and they parametred a "no more than 2 variance to mean ratio" for the negative binomial distribution.
Comment: Thank you for your answer, it does clarify things a bit about the original formula.

About the reorder point, sα=μLTD+σLTD∗zα  Is this the formula I should use to apply the poisson/negative binomial distrubutions ?

I have not been able to obtain reasonable results with when trying to isolate K and put it in a poisson distribution (I haven't tried for the Negative Binomial as I am not sure what parameters to choose).
Comment: No it is not.  You should just calculate the inverse of the Poisson or Negative Binomial cumulative distribution functions at the $\alpha$ quantile.
Comment: What I am curently doing is calculating the inverse to a "k" value using the formula $SS=z_{\alpha }\times {\sqrt {E(L)\sigma _{D}^{2}+(E(D))^{2}\sigma _{L}^{2}}}$.   It works for the normal (accurate Safety stocks and service level). But it gives back 0 for the rest (Poisson using the daily average demand as lambda and Nbinomial using $r=mu^2/(Sigma^2 - mu)$ and $p=r/(r+mu)$.  I believe the issues are related to my parameters, but since there is no "standard" poisson or negative binomial, I use my part number's average demand and standard deviation. I tend to have very low averages per day.


Data Modeling with Kafka? Topics and Partitions

Question: One of the first things I think about when using a new service (such as a non-RDBMS data store or a message queue) is: "How should I structure my data?".
I've read and watched some introductory materials. In particular, take, for example, Kafka: a Distributed Messaging System for Log Processing, which writes:

"a Topic is the container with which messages are associated"
"the smallest unit of parallelism is the partition of a topic. This implies that all messages that ... belong to a particular partition of a topic will be consumed by a consumer in a consumer group."

Knowing this, what would be a good example that illustrates how to use topics and partitions? When should something be a topic? When should something be a partition?
As an example, let's say my (Clojure) data looks like:
{:user-id 101 :viewed "/page1.html" :at #inst "2013-04-12T23:20:50.22Z"}
{:user-id 102 :viewed "/page2.html" :at #inst "2013-04-12T23:20:55.50Z"}

Should the topic be based on user-id? viewed? at? What about the partition?
How do I decide?
Comment: Strange this talks about topics and partitions, but not necessarily evolution of the data within them. What if you wanted to attach user agents or headers to those "user view" events? How do you evolve and communicate that in a way to downstream consumers?
Comment: @OneCricketeer Sounds like a separate question to me :) Go for it...
Answer: When structuring your data for Kafka it really depends on how it´s meant to be consumed.
In my mind, a topic is a grouping of messages of a similar type that will be consumed by the same type of consumer so in the example above, I would just have a single topic and if you´ll decide to push some other kind of data through Kafka, you can add a new topic for that later.
Topics are registered in ZooKeeper which means that you might run into issues if trying to add too many of them, e.g. the case where you have a million users and have decided to create a topic per user.
Partitions on the other hand is a way to parallelize the consumption of the messages. The total number of partitions in a broker cluster need to be at least the same as the number of consumers in a consumer group to make sense of the partitioning feature. Consumers in a consumer group will split the burden of processing the topic between themselves according to the partitioning so that one consumer will only be concerned with messages in the partition itself is "assigned to".
Partitioning can either be explicitly set using a partition key on the producer side or if not provided, a random partition will be selected for every message.
Comment: @RavindranathAkila
`Kafka is designed to have of the order of few thousands of partitions roughly less than 10,000. And the main bottleneck is zookeeper. A better way to design such a system is to have fewer partitions and use keyed messages to distribute the data over a fixed set of partitions.`

Makes me think the its not the right tool for what you described - but more, the topic would be "Page View Events"? And all page views would be in that "topic". Partitions seem to more about parallelism and replicas and stuff?
Comment: So, instead of using the topics as the way to get data per user id, thereby overwhelming Zookeeper, it is better to partition by user id, and have user id based consumers subscribe to each partition if?
Comment: http://firstname.lastname@example.com%3E
Comment: Thanks :) Finally I have a reply :P
Answer: Once you know how to partition your event stream, the topic name will be easy, so let's answer that question first.
@Ludd is correct - the partition structure you choose will depend largely on how you want to process the event stream. Ideally you want a partition key which means that your event processing is partition-local.
For example:

If you care about users' average time-on-site, then you should partition by :user-id. That way, all the events related to a single user's site activity will be available within the same partition. This means that a stream processing engine such as Apache Samza can calculate average time-on-site for a given user just by looking at the events in a single partition. This avoids having to perform any kind of costly partition-global processing
If you care about the most popular pages on your website, you should partition by the :viewed page. Again, Samza will be able to keep a count of a given page's views just by looking at the events in a single partition

Generally, we are trying to avoid having to rely on global state (such as keeping counts in a remote database like DynamoDB or Cassandra), and instead be able to work using partition-local state. This is because local state is a fundamental primitive in stream processing.
If you need both of the above use-cases, then a common pattern with Kafka is to first partition by say :user-id, and then to re-partition by :viewed ready for the next phase of processing.
On topic names - an obvious one here would be events or user-events. To be more specific you could go with with events-by-user-id and/or events-by-viewed.
Comment: I have seen references where you'd publish the events to two topics: one per worker / intended usage. In this case, there could be two topics, with two different partitioning schemes.
Answer: This is not exactly related to the question, but in case you already have decided upon the logical segregation of records based on topics, and want to optimize the topic/partition count in Kafka, this blog post might come handy.
Key takeaways in a nutshell:

In general, the more partitions there are in a Kafka cluster, the higher the throughput one can achieve. Let the max throughout achievable on a single partition for production be p and consumption be c. Let's say your target throughput is t. Then you need to have at least max(t/p, t/c) partitions.

Currently, in Kafka, each broker opens a file handle of both the index and the data file of every log segment.  So, the more partitions, the higher that one needs to configure the open file handle limit in the underlying operating system. E.g. in our production system, we once saw an error saying too many files are open, while we had around 3600 topic partitions.

When a broker is shut down uncleanly (e.g., kill -9), the observed unavailability could be proportional to the number of partitions.

The end-to-end latency in Kafka is defined by the time from when a message is published by the producer to when the message is read by the consumer. As a rule of thumb, if you care about latency, it's probably a good idea to limit the number of partitions per broker to 100 x b x r, where b is the number of brokers in a Kafka cluster and r is the replication factor.
Answer: I think topic name is a conclusion of a kind of messages, and producer publish message to the topic and consumer subscribe message through subscribe topic.
A topic could have many partitions. partition is good for parallelism. partition is also the unit of replication,so in Kafka, leader and follower is also said at the level of partition. Actually a partition is an ordered queue which the order is the message arrived order. And the topic is composed by one or more queue in a simple word. This is useful for us to model our structure.
Kafka is developed by LinkedIn for log aggregation and delivery. this scene is very good as a example.
The user's events on your web or app can be logged by your Web sever and then sent to Kafka broker through the producer. In producer, you could specific the partition method, for example : event type (different event is saved in different partition) or event time (partition a day into different period according your app logic) or user type or just no logic and balance all logs into many partitions.
About your case in question, you can create one topic called "page-view-event", and create N partitions through hash keys to distribute the logs into all partitions evenly.  Or you could choose a partition logic to make log distributing by your spirit.


Completely empty page

Question: I need to create a page which is completely empty (no HTML returned at all). I need this for a POST callback (when using jEditable).
I would like to still have access to the global variables (such as <code>$user</code>) and the modules that I have installed as I have a module installed which lets me access my REST service.
However, even though there should be not HTML returned per default, I should be able to return a string.
Does anyone know of a way to do this?
Answer: You can do that through a custom module - create a path and instead of returning the output, just print it.
Here's an example:
<code>/**
 * Implements hook_menu().
 */
function YOURMODULE_menu() {
  $items = array();
  $items['custom-url'] = array(
    'page callback' => 'YOURMODULE_blank_page_callback',
    'page arguments' => array(),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Display the content for your blank page.
 */
function YOURMODULE_blank_page_callback() {
  print 'Your string.';
}
</code>

Completely empty page


Installing PGAdmin 3

Question: How can I install pgAdmin3 on RHEL 4?
I've install it but I can't access it. After ./configure, I don't know what I should do.
I want access to the postgresql with a GUI, because from i don't understand the command line.
Comment: I think you really do need to get someone in to help you.
Comment: Please [read this Meta topic](http://meta.serverfault.com/questions/3608/how-can-i-ask-better-questions-on-server-fault) and improve your question. Right now you're essentially saying "It doesn't work! Please give me the exact commands to type in!", which doesn't meet the "professional" requirement of this site -- we expect you to put in some effort and provide a *detailed* description of the problem you're having.
Answer: after configure usually follows a
make

and then
make install

(the last must be done as root)

Installing PGAdmin 3


Batch file conversion and usage

Question: I'm having a problem with a small batch script that I'm writing. The point of the batch script is to run a Javascript file that converts an XML file to a csv file and then run a Python script which will analyze the just created csv file and create another csv file.
The batch script is below.
    start XML-CSV_Converter.js
    python CSV_ANALYZER.py
    exit

I didn't write the XML-CSV converter;
It can be found here. (http://gotochriswest.com/blog/2011/05/05/excel-batch-convert-xls-to-csv/) The only thing I changed was I removed all of the alerts and input prompts so it doesn't wait on any user input. Simply put, all it does it look at every XML file in the current directory and produces a csv file in the same directory.
Whenever I run the batch script, I keep getting an IO error in my Python script because even though it can see the created file, it isn't able to open the file.
The exact error is:
 "IOError: [Errno 2] No such file or directory: 'NAME_OF_FILE.csv'"
The part of the Python script which is causing errors is listed below.
    dirList = os.listdir("C:\FOLDER")
    for fname in dirList:
        if fname.find(".csv") != -1:
            inputFile = open(fname,'r')     <---- Script halts here

Anybody know what could be causing the file not being opened in the Python script?
 If I run the JavaScript file manually, and then the Python script manually, it works perfectly. But when I try to chain them together in a batch file it breaks. I would appreciate any and all ideas!
Thanks in advance!
Comment: Have you verified that the JS script is actually running?
Comment: Yup. It creates the new csv file and I can see it in Windows Explorer after the batch script breaks.
Answer: The start command launches a program (or, in your case, a file) and immediately returns, without waiting for the program to exit. This means that when Python tries to open the file, the JS script is probably still running and has the file open exclusively for writing.
You should run the JS file by directly calling the Windows Scripting Host (cscript.exe). Just replace the start command with:
cscript //nologo XML-CSV_Converter.js

This will ensure that when the Python command is run, the JS script will have completed its job and safely terminated.
Comment: Thanks for the response! Unfortunately, it doesn't seem to fix the problem. It still results in the same IOError in the Python script.
Comment: OK, I've added another answer, but I'm also leaving this because it's a common problem that may affect others.
Comment: If `.js` files are associated with `wscript`, you _can` use a `start` command to execute them and just need to add a `/wait` argument before the filename which will start the application and the wait for it to end.
Answer: You forgot to add the folder name to the file name in the open() call. listdir() returns only the file names, so unless its path argument matches the current directory, you'll have to add it to the returned file names to properly identify them.
As a side note, you should also avoid using backward slashes in normal strings. In this case "C:\FOLDER" happens to work, but "C:\folder" wouldn't, because \f would be converted to \x0c (the linefeed character). You should use either a raw string (r'C:\FOLDER' which doesn't convert escaped characters), an escaped backslash ('C:\\FOLDER'), or the more portable 'C:/FOLDER' (on Windows '/' is the alternative path separator).
Also a simpler way to check for the extension is to test whether the name ends with it (the s.find(t) == -1 is not very Pythonic). All in all, the modified code could look something like this:
folder = "C:/FOLDER"
for fname in os.listdir(folder):
    if fname.endswith(".csv"):
        inputFile = open(os.path.join(folder, fname),'r')

Answer: The root cause is "python CSV_ANALYZER.py" got executed while the  XML-CSV_Converter.js was not finished.
By type "start XML-CSV_Converter.js", it won't wait for this command to finish before executing the next command.
If you have installed js interpreter, you can remove the `start' in the first line, an then it should work.
Comment: JS files are associated with wscript.exe by default, meaning no output will be sent to the console. That's why I recommend to explicitly use cscript.exe instead.

Batch file conversion and usage


How to get firebase key value

Question: I have the below Firebase Database structure and I want to retrieve this value.. see below image... how to do it?
I was able to retrieve the CategoryName & Recipes using the below but unable to get their parent
//create reference for the fire base database
let rootRef = Database.database().reference()
print(rootRef)
//get Category path
let childRef = Database.database().reference(withPath: "Bookmarks")
print(childRef)
let itemsRef = childRef.child(userID)
print(itemsRef)

//retrieve data from firebase database
itemsRef.observe(.value, with: {
    snapshot in
    for child in snapshot.children
    {
        var recipes: String = snap.childSnapshot(forPath: "Recipes").value as !String
        var categoryName: String = snap.childSnapshot(forPath: "CategoryName").value as !String
    }

})

Answer: To get the key inside the for..in loop, you can do the following:
  let key = child.key as String
  print(key)

Check here for more info:
https://firebase.google.com/docs/database/ios/read-and-write
Answer: To get the key from firebase you can try following in your code:
itemsRef.observe(.value, with: {
    snapshot in
    for child in snapshot.children
    {
          if let alldata = child as? DataSnapshot{
         //key value
         guard let keyValue = alldata.key as? String else { return }
         print(keyValue)

         var recipes: String = alldata.childSnapshot(forPath: "Recipes").value as? String
        var categoryName: String = alldata.childSnapshot(forPath: "CategoryName").value as? String
        }
    }

})

How to get firebase key value


How can I apply the McCormick Envelopes to the product of two binary variables?

Question: I've seen the McCormick envelopes applied many times to the product of two continuous variables, but I can't seem to find when both of them are binaries. Also, I applied the restrictions as described bellow, and they don't work because they don't make sense when both of them are 1.
the restrictions:
$$
\begin{align*}
w_{i j} &\geq x_{i}^{L} \cdot x_{j} + x_{i} \cdot x_{j}^{L} - x_{i}^{L} \cdot x_{j}^{L}\\
w_{i j} &\geq x_{i}^{U} \cdot x_{j} + x_{i} \cdot x_{j}^{U} - x_{i}^{U} \cdot x_{j}^{U}\\
w_{i j} &\leq x_{i}^{U} \cdot x_{j} + x_{i} \cdot x_{j}^{L} - x_{i}^{U} \cdot x_{j}^{L}\\
w_{i j} &\leq x_{i} \cdot x_{j}^{U} + x_{i}^{L} \cdot x_{j} - x_{i}^{L} \cdot x_{j}^{U}\\
x^{L} &\leq x \leq x^{U} \qquad~ w^{L} \leq w \leq w^{U}
\end{align*}
$$
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: Please clarify your specific problem and please write something like formulas with "MathJax" in the question and not via link which shows a picture with the formulas.
Comment: Mc Cormick envelopes ? What is it ? Could you give a reference ?
Comment: @Kevin Dietrich Congratulations for having patiently written the formulas !
Comment: Sorry, this was the first time I posted here. I'll be more carefull in the future. I applied the formulas written now (thank you @KevinDietrich) but I got terrible results because I created w as continuous, but changed xi and xj to continuous as well. This created a problem as both xi and xj were comming as random values between 0 and 1.
Answer: Substituting $0$ for $x^L$ and $1$ for $x^U$ yields:
\begin{align}
w_{i j} &\ge 0 \\
w_{i j} &\ge x_j + x_i - 1 \\
w_{i j} &\le x_j \\
w_{i j} &\le x_i
\end{align}
This is the usual linearization of $w_{ij} = x_i x_j$. See https://or.stackexchange.com/questions/37/how-to-linearize-the-product-of-two-binary-variables
Comment: Thank you @RobPratt. I got confused because I assumed that I had to change xi and xj to continuous too and this was giving me weird results.


Shape won't scale

Question: Whenever I try to scale the shape, nothing happens and then the console stops responding to input.
Here is the set scale command:
case 7: do
                         {
                            System.out.println("\nEnter scale factor");
                            scale=input.nextDouble();
                         }
                         while(scale<0);
                         Shape.setScaleFactor(scale);
                         break;

Here is the scale shape command
 case 4: for(i=0; i<s.length; i++)
                         {
                            if(s[i]!=null)
                            {
                              s[i].scaleShape();
                            }
                         }
                         break;

Here is the main method variables:
int i=0;
        int m=0;
        double scale;
        boolean exit=false;
        Shape[] s = new Shape[10];

Here are all the relevant methods in the shape class;
private static double scaleFactor;
public static double getScaleFactor()
    {

        return scaleFactor;
    }
    //Set ScaleFactor
    public static void setScaleFactor(double x)
    {

        scaleFactor=x;
    }

Here is the scaleshape method in the rectangle subclass
private double base;
    private double height;
@Override public void scaleShape()
    {
        base=base*getScaleFactor(); height=height*getScaleFactor();

    }

        public abstract void scaleShape();

Here is the set scale method in the circle class:
private final double pi = Math.PI;
    private double radius;
 @Override public void scaleShape()
    {
         radius*=getScaleFactor();
    }

Answer: My guess is that your problem is here:
do
{
    System.out.println("\nEnter scale factor");
    scale = input.nextDouble();
}
while(scale < 0);

What happens if you add some logging?
do
{
    System.out.println("\nEnter scale factor");
    scale = input.nextDouble();
    System.out.println("Scale entered was: " + scale);
    System.out.println("Is scale < 0? " + (scale < 0));
}
while(scale < 0);

If you don't get what you're expecting, it might be worthwhile to read in a String instead just to see what input you're actually getting. You can always read a String, log it, then use Double.valueOf(String) to convert it.
Another possibility is that it's working, but you never reset scale and this is in some sort of loop, so it just continues scaling the shape forever but never stops to ask for input again.
Comment: @redelman431 Your comment seems to show that it's working fine, but you marked this as accepted. Did you figure out what was wrong?

Shape won't scale


How to render a facet block?

Question: I've created a facet block according to this example Programatically render a block in a twig template
I've created the facet block as follows:
$variables['block_output'] = Drupal::service('plugin.manager.block')->createInstance("facet_block:topic")->build();

That works great, but I'm missing the block template itself on my page (the block around the facet links output). I need a custom suggestion for this block to format it. Unfortunately, the hook_theme_suggestions_alter() doesn't detect this block. How can I add a file name suggestion?
Thank you!
Comment: try \Drupal::entityTypeManager()->getViewBilder('block')->view($block, $view_mode). Also you need the block entity, not plugin. Block entity basically bundles the plugin and configuration for it together. Discard previous, just entity_load('block', $id)->view($view_mode) should work.
Comment: Yes, that works, assuming that you *have* a block. See http://drupal.stackexchange.com/questions/153184/programatically-render-a-block-in-a-twig-template?lq=1. build of the plugin just contains the content of the block. Page manager uses block plugins too and has its own templates. You could build a structure similar to what BlockViewBuilder does or you could simply add your markup around it yourself in your template.
Comment: Thank you for your answers. Berdir, what do you mean with "build a structure similar to what BlockViewBuilder does" exactly? Can you make a example? Thank you very much!
Answer: I'm using the module Twig Tweak, so you don't have to create a block, but you can add in in your twig file.
In my views-view--view-id--page.html.twig file I use it like this:

 {{ drupal_block('facet_block:facet_id') }}

Where the facet_id is the machine name of my facet.

How to render a facet block?