Proposal to make the site more useful for experts (PhDs, academics, professionals)

Question: Problem Description
There aren't enough experts and expert-level questions on the site.
A long-standing criticism of this site is that there are too many non-expert level questions. This makes the site less appealing towards PhD students, academics, and professionals. There are some high level questions here and there, but you have to sift through a lot of lower quality questions to find them. Some others may not feel the same way, but I suspect that many PhD students and academics who are NOT currently regular users don't participate because of this. I suspect those many of those that are regular users begrudgingly accept it. Here are some previous meta posts that cite this problem:

I think the problem this site has is a lack of experts
We need more PHDs/Professionals on this site/why are we not getting them

The anecdote told in the second post is telling:

This week I actively approached a couple of professors and working economists I know and told them about the site. Most of them nodded their heads and said "yeah sure whenever I have time I'll check it out". One of them told me he heard of the site but was not impressed by the content to actively participate.

Past Attempts at a Solution
Here are a few solutions that I believe have been tried or proposed in the past, as indicated by relevant meta posts.

Simply invite more experts to participate: How many experts did $you$ invite today?
Start a separate site for experts only, like Math Overflow is to Math StackExchange: Who are PhDs and PhD candidates on this site?
Create a separate tag for these expert questions (e.g. academic-graduate): Meta filter: Layman/Academic/Real World

I believe that these previous attempt have had a hard time succeeding for the following reasons. Inviting more experts is hard and experts are in relatively short supply relative to, say, undergraduates asking homework-style questions. A separate site for experts would be nice, but seems unlikely unless there is far more participation from experts on the site than there currently is. Maybe this would be viable in the future, but there needs to be a way to attract more experts now. Creating a separate tag for expert-level questions might work, but it takes more buy-in than we currently have. Furthermore, and this brings me to my point, adding a specific tag to these questions puts an additional burden on the person asking the question.
Proposal
Short description: Require that each question that isn't an "expert-level question" be tagged as a beginner question.
Detailed description: We should continue to strictly enforce the policy of closing off-topic questions, poorly crafted questions, and pure homework questions. We should also continue to invite experts, etc. I propose that we also institute a policy that every question that doesn't meet the standards of being considered an expert-level question MUST be tagged as beginner. We would need to decide on what is considered an expert-level question, which is admittedly subjective. However, as a rule of thumb, I would suggest that if it is the kind of question that a PhD student or higher would ask or encounter in a PhD-level class, then it counts. This includes questions about institutional details that might be important to PhD level research as well. Essentially, I would want to exclude questions that an undergraduate would ask or that a student would encounter in an undergraduate-level class.
Why I think this works:

The previous solution of giving expert level questions their own tag put the burden of tagging questions on the author of the question. We want to make this site as friendly as possible towards experts, so the burden should be put on the writer of beginner-level questions.
A question writer only gets 5 tags to apply to their question. This requirement automatically takes away one of them. This burden should be imposed on beginners.
Furthermore, the site provides the ability to hide or "gray-out" questions that belong to a certain tag. You can also add certain tags to you "Watched Tags" list, but this only sends you notifications or emails. If all beginner-level questions were tagged as beginner questions, then you could hide or gray-out all of these questions on the home page. For example, the image below demonstrates what the home page will look like when I choose to gray out all questions tagged "macroeconomics". If I wanted, I could choose to hide them entirely:

This is a low-stakes change to the site policy. It doesn't require us to all-of-the-sudden start closing a lot of questions (though we should likely adopt a more strict policy in this regard at some point). For now, all this requires is adding one simple label to each question. This can be done by any user easily by simply suggesting an edit to a question and it can be undone easily if it was mistakenly applied.

Do you agree?
I believe that adding these tags should be relatively easy to do. It's pretty easy to spot a beginner level question and suggest an edit. It's fairly easy to edit a question for the purposes of adding a tag. We don't necessarily need to update old questions to have this tag, as long as we are strict about requiring it on new questions. If we want, we can slowly update older questions over time.
There may be other solutions out there. Please offer solutions if you have any in the answers to this post below. I will post a copy-pasted excerpt from my above proposal as an answer below. Upvote it if you like my proposal. Suggest another solution or vote on other given answers if you like another solution better. Upvote this question if you believe that at least something needs to be done. Thanks!
Comment: I'd also point out that, per the parameters of Stack Exchanges "Area 51", the site is meant to exclude basic, beginner level questions: "The questions on your site say a lot about the community. To attract experts, you need a site where people are asking very interesting and challenging questions, not the basic questions found on every other Q&A site. Your goal is to make it clear that this is a professional site." https://area51.stackexchange.com/faq
Comment: I really like most of your ideas here, I would like to hear from more people but otherwise I am on board. In addition, I think our community should be more stricter with closing down questions. As a mod I try to always err on the side of caution and hesitate voting to close but I would like to see community voting to close bit more harshly.
Comment: If I were to change only one thing about this proposal, I think some people might not like the idea of tagging their answer as "beginner". Maybe a label like "undergraduate" would be a little nicer. Overall, I'm a big fan of this proposal even as it is though. So I give it my upvote
Comment: Though, we should definitely amend the help page if/when we adopt this rule. The help page should reiterate the point made in https://area51.stackexchange.com/faq that the site is a professional site for experts. It could then also include something to indicate that the label is not meant to be offensive.
Comment: @AdamBailey I myself was a proponent of expanding the scope of the site back then. I have since changed my mind and now believe that it was a mistake. I agree with 1muflon1 in observing that the quality of questions and answers on the site has dropped a lot since the site began. I wish I had really thought about the Area 51 instructions/warnings back then. This one really sticks out to me right now: "Remember, pro sites WILL attract the enthusiasts, but not the other way around!"
Comment: I am sympathetic to what you are trying to achieve, but isn't beginner-expert more of a spectrum than a clear dichotomy?  What about, for example, the sort of question that might be asked by a thoughtful undergraduate who understands the basic material?  And what about questions that might be considered beginner-level within some specialist area of economics, eg housing economics, environmental economics, but which show a good knowledge of general macro and/or micro economics?
Comment: @jmbejara I would not mind narrowing the focus of the site, perhaps this is just survivorship bias but looking back it seems that there were more users providing expert answers and questions were of higher quality
Comment: *"A long-standing criticism of this site is that there are too many non-expert level questions."* - criticism from whom? From people actually asking questions, or from those who don't like certain kinds of questions? Also, doesn't this show that the primary demand is for answers on matters of economics that are broad and simple to ask, and that experts need to concentrate primarily on providing this?
Comment: Thanks @1muflon1 ! Yeah, I should do that. I'll try to start being more careful about adding close-votes.
Comment: you are welcome also consider using this new generic response whenever you see unsourced and not self contained answer. I think this will help to improve level of discourse as well and in addition it encourages participation on more academic level https://economics.meta.stackexchange.com/questions/2084/generic-response-to-unsourced-answers
Comment: @1muflon1 Thanks. That's helpful!
Comment: @AdamBaileyThanks for the comment. Surely, there is a spectrum. The idea is create a cutoff or set of easily interpreted criteria. Naturally, it will be imperfect and fuzzy. The benefit of this approach is that it's just a label---the stakes are low. A person can always petition to add/remove the label. Ultimately, something needs to be done to raise the level of  discourse on the site so that it will attract experts. Again, this is a low-stakes way to do it.
Comment: Also good and from the same place, "Remember, pro sites WILL attract the enthusiasts, but not the other way around!" https://area51.stackexchange.com/faq
Comment: @KitsuneCavalry Thanks! Yeah, I think there's some room for improvement. I don't want to tie the label to academic rank, though. This came up in another comment below. "Non-expert" seems ok, but I don't like that it's hyphenated. It should be a word that immediately comes to mind so that's it's easy to discover (to attract new experts to the site). This means it shouldn't feel strained or overcomplicated. I hope people don't find "beginner" offensive. It should be clear in the help section that it's not meant to be. Other options are "amateur" or "novice."
Comment: @jmbejara  Re your comments referring to Area 51, I think we should also have regard to [this question](https://economics.meta.stackexchange.com/questions/1646/its-identity-crisis-time/1647#1647) in 2016, which received considerable support and led to our broadening our stated purpose to "For those who study, teach, research and apply economics and econometrics".  Keeping that broad purpose is I think quite consistent with your proposed low-stakes change to try to make the site more useful for experts, ie tagging "beginner" questions.
Answer: Tag all beginner questions with beginner tag
My proposed solution, copy-and-pasted from the question.
Short description: Require that each question that isn't an "expert-level question" be tagged as a beginner question.
Detailed description: We should continue to strictly enforce the policy of closing off-topic questions, poorly crafted questions, and pure homework questions. We should also continue to invite experts, etc. I propose that we also institute a policy that every question that doesn't meet the standards of being considered an expert-level question MUST be tagged as beginner. We would need to decide on what is considered an expert-level question, which is admittedly subjective. However, as a rule of thumb, I would suggest that if it is the kind of question that a PhD student or higher would ask or encounter in a PhD-level class, then it counts. This includes questions about institutional details that might be important to PhD level research as well. Essentially, I would want to exclude questions that an undergraduate would ask or that a student would encounter in an undergraduate-level class.
Comment: It may be worth considering alternative wording for the label, albeit with exactly the same purpose.  A possible drawback to "beginner" is that it could be taken by some as labelling the person posting the question rather than or as well as the question itself.  Possibly it's far-fetched to suggest that some might take offence, but I'm not sure.  Anyway, I tried to think of alternatives and came up with  "elementary", for which there is some precedent on Mathematics SE which has heavily-used tags such as "elementary number theory" and "elementary set theory".
Comment: @1muflon1 This sounds like "scope creep" to me. IMO, adding more labels puts more burden on the labeler and doesn't serve the original purpose. The purpose is to attract experts with as little effort as possible. Plus, the academic distinctions feels too narrow. A person can be a Physics PhD but still ask undergraduate econ questions. For this reason, I like beginner (or maybe non-expert).
Comment: @AdamBailey. Thanks. Definitely open to suggestions. Ideas: Elementary, Non-expert, Introductory, Pre-graduate, Undergraduate. I still like "beginner", but I'm open to ideas. "Non-expert" might be good. The help page could make it clear that "beginner" isn't supposed to be offensive.
Comment: @jmbejara I think using academic ranks sound better, we could have even both pre-undergraduate and undergraduate at the same time
Comment: @jmbejara oh I probably wasn't clear enough I did not meant to say we should use ranks based on peoples education, but we could have more labels than just academic-graduate and pre-undergraduate.
Comment: Other options are "amateur" or "novice."
Answer: Tag all beginner questions with nonexpert tag
Short description: Require that each question that isn't an "expert-level question" be tagged as a nonexpert question. Expert-level questions are the kind of questions that are more likely to be asked by PhDs/PhD-students in economics, academic economists, or research professionals in economics. Detailed guidelines are provided below to provide for a more objective-based classification.
Detailed description:
Guidelines: An "expert" question should contain ONE OR MORE the following properties.

Deals with a formal economic or econometric model. This includes questions about mathematical or statistical techniques.
Questions about computational implementation.
The question includes a reference to a peer-reviewed journal or a high-quality working paper series.
The question is about a data standard or data codebook, provided a link to the data codebook or data reference guide is provided. This does NOT include questions about a particular event in a data set. Such questions must satisfy one of the previous three criteria to be considered.

Commentary

The criteria defining an expert-level question is seen as a set of guidelines. This may be modified in the future if it is too inflexible. As a rule of thumb, I would suggest that if it is the kind of question that a PhD student or higher would ask or encounter in a PhD-level class, then it counts.
A question can still be an expert question without having any mathematical rigor as long as it references a research paper (peer-reviewed journal or high-quality working paper). This acts as a way to signal quality of a question. Remember, signals must be costly to be credible!
The set of criteria defining an expert-level question is fairly objective, which should help to resolve concerns about meta-tags.
We should continue to strictly enforce the policy of closing off-topic questions, poorly crafted questions, and pure homework questions. We should also continue to invite experts, etc. I propose that we also institute a policy that every question that doesn't meet the standards of being considered an expert-level question MUST be tagged as nonexpert.

Examples of Expert Questions
The following illustrate questions that satisfy one or more of the above criteria:

This first question is an example of an expert question because it is a question about an econometric technique, satisfying criterion (1). It doesn't specifically reference a particular paper, but deals with a specific econometric technique. Bartik Instrument Intuition
This is also an expert question under criterion (1). It doesn't include a reference to a specific peer-reviewed paper, but it is a question that mathematically describes an economic model. Optimal consumption in Merton-like portfolio choice model with constant wage
This question satisfies (1) because deals with a mathematical technique. It doesn't include questions and doesn't outline a specific model. However, it does reference a mathematical concept. For this reason, it's an expert question. Note that it does include a reference to a textbook, but this book is NOT a peer-reviewed journal article as required by criterion (3). Intuition of the Kolmogorov Equations
This question is an expert question because it concerns the computational implementation of an econometric model. It provides some example code and a description of what they are trying to accomplish. This qualifies under (2). Extract residuals from Uhlig's rejection method - Lag selection
This question somewhat broad and does not include equations or a specific model. It's a somewhat "chatty" question. However, it does reference a specific result from a peer-reviewed paper. Admittedly, it could be improved by providing a reference to the specific paper---but it DOES include a link to the Wikipedia page about the specific set of papers.. This is an expert question under (3). The Sonnenschein-Mantel-Debreu results, what are the implications for macroeconomics?
This question doesn't pertain to a specific model nor does it include a reference to a peer-reviewed journal article. However, the question regards interpreting a commonly used data set/data standard and it does includes a reference to the data guidebook. This qualifies as an expert question under (4). What's the difference (if any) between "fixed assets" and "fixed capital" in the UN SNA?

Acknowledgment: This proposal was formulated in conjunction with @1muflon1. It is a slight modification of the other proposal about the "beginner" tag.
Answer: I support the idea of using tagging as a low-stakes way to make the site more useful for experts.  I wasn't previously aware of the facility for a user to have questions with selected tags greyed out or hidden altogether, but having tried it (it's on the right hand side of the site's home page) I find it's easy to use (and has improved my experience by hiding certain topics in which I am less interested).
In order to a) comply with the SE policy of discouraging meta-tags, and b) avoid a tag which could be taken to label the person asking a question and not the question itself, I propose adding two new tags elementary macroeconomics and elementary microeconomics.  This follows precedent on Mathematics SE which has tags such as "elementary number theory" and "elementary set theory" which are heavily used and seem to work well. Those two tags might not cover all beginner-level questions, but they would cover a very high proportion, and others could be added later if necessary.
With up to 5 tags per question allowed, there would still be plenty of scope to indicate more precisely the topic of a question within the broad categories of macroeconomics and microeconomics.
Edit (in response to comment by @1muflon1).
My suggestions for descriptions for the tags are:
Elementary macroeconomics
For questions on topics commonly found in introductory or first degree courses in macroeconomics including GDP and its components, the determination of national income, the business cycle, inflation, the balance of payments, fiscal and monetary policy, and economic growth.  Also questions about particular countries or real world situations to which such topics are relevant.
Elementary microeconomics
For questions on topics commonly found in introductory or first degree courses in microeconomics including consumer and firm behaviour, supply and demand, market structures, international trade, welfare, market failure and policy responses.  Also questions about particular markets or real world situations to which such topics are relevant.
These are just a first stab: I'm sure others will have improvements.
Comment: I would be happy to add these as well, could you please propose description for these tags as well? Naturally, there will be some degree of subjectivity here but it would be best if the description could have some sort of litmus test. The elementary number theory is from Math.se is good example of proper tag for this as it clearly defines what is elementary number theory https://math.stackexchange.com/questions/tagged/elementary-number-theory
Comment: This uses $N$ new tags to accomplish the same thing that you could accomplish with 1 new tag: "elementary." You achieve the same result by labelling a question with the two words individually, e.g., "elementary" and "macroeconomics." What if you want to filter out elementary macro but not elementary micro? You can do this using the "custom filter" button on the right-hand side of the screen.
Comment: @jmbejara  Agreed on your first point, but I'm trying to offer an approach which addresses SE's discouragement of meta-tags.  And yes, it would be easy to filter out elementary macro but not elementary micro or vice versa if desired.  That's a small benefit isn't it?
Comment: Thanks. I see your point. Though, IMO, the benefit of having only one tag is that it makes it easy for incoming experts to easily filter out all the nonexpert questions. I want to make it as easy as possible for newcomers to the site to filter out these questions---there's just use one tag you need to worry about. Plus, we don't want proliferation of "elementary [insert_topic_here]" tags.
Comment: @jmbejara I agree with you that enforcing too many elementary tags would become cumbersome, however, I think we can strictly enforce the nonexpert tag and have these tags as additional tags, as a matter of fact with these tags, I had look at math SE where these tags seem to work and even be used by the people who ask questions, I think I can see even a bsc. student asking question here wanting to use such tag to indicate that the answer should also be appropriate.
Comment: @1muflon1 This solution tries to solve one problem by creating another. Ppl in the community seem to dislike "compound tags". See https://meta.stackexchange.com/questions/93607/how-should-compound-tags-be-handled and this comment on it: "These are such a pain... You can't just merge 'em, 'cause there are questions with nothing but this tag - and a lot more with neither [jquery] or [ajax]. See also: [javascript-events]" The fact is that the two parts of this proposed tag can live separately. If they can, they should.
Comment: @1muflon1 Also, I don't think that math SE is a very good comparison for this site. Just because they do it, doesn't mean that we should. (1) Math SE has a separate site for experts in Math Overflow. (2) Math SE has no problem attracting enough experts and is not in Beta. This site is dying for more experts. (3) Economics tends to attract cranks. In Math SE, each question has to involve math and thus has a built-in way to increase the quality of questions. I think we need to "tighten the belt" and be more strict about what questions we allow.
Answer: I like the idea, and it seem to be well received on the net basis, so I think we should move forward in this direction,  but at the same time it needs some modifying.
For better or worse, current policy of SE is to explicitly discourage meta tags.

From this point on, meta-tagging is explicitly discouraged.

How can you tell you're using a meta-tag? It's easier than you might think.

If the tag can't work as the only tag on a question, it's probably a meta-tag. Every tag you use should be able to work, more or less, as the only tag on a question. Meta-tags, like [beginner], [subjective], and [best-practices], are useless by themselves — they tell you nothing at all about the content of the question.

If the tag commonly means different things to different people, it's probably a meta-tag. In a cruel, ironic twist, the meaning of the tag [subjective] itself … is actually subjective. Ditto for [best-practices] and [beginner]. Best practices to whom? Beginner by what criteria? These tags are impossible to define by anything remotely resembling an objective metric. In comparison, the the meaning of tags like [java], [c#], and [javascript] are crystal clear to all but the nuttiest of nutbags.

My Proposed Alternative
My proposal would be to have tag:
nonacademic
With the following tag description:
For questions that are not about formal economic or econometric models and techniques, their implementations using programs and languages or do not include references to, or are not based on academic sources.
(by the way suggestions to improve the tag description above are welcome).
Advantage of this tag are in my opinion following:

The tag is fairly objective, it has clear unambiguous criteria for what is nonacademic question.
The tag has less negative connotation, beginner could be considered offensive by someone who takes the tag personally. While, I think most people would be reasonable enough not to take offense it is better for us to cover all bases.
I do not believe the tag would qualify as meta-tag. The tag can stand on its own in the same way as a self-study/homework question tags can. Self-study/homework question tags are common across science stack exchanges. The nonacademic tag is informative about the fact that the question contains nonacademic content, in same way as self-study/homework tag is informative about the fact that question contains homework exercises, even if further tags should be used to clarify nature of that nonacademic content.
I think it is fully in line with the spirit of the proposal here. The tag effectively applies to any laymen question. It might not apply to beginner level science questions, but those usually fall under self-study, and we can simply start to enforce the self-study tag as well. This is actually already being done on other science stacks such as Physics.se where their homework and exercises tag is more strictly enforced.

Alternatively, we could have tag:
nonexpert
with the same description:
For questions that are not about formal economic or econometric models and techniques, their implementations using programs and languages or do not include references to, or are not based on academic sources.
Per suggestions this might be better as word academic can suggest that it has something to do with workings of academia.
PS: In comments there was complaint that Non-expert is hyphenated, nonacademic does not suffer from that issue :) (Apparently, nonexpert is not hyphenated as well).

After discussions between mods and also @jmbejara and other community members the nonexpert was now added.
Comment: @jmbejara we could do that as well but that would actually require additional meta because then we should also change the scope of a site and people who upvoted your post and answer who were on board with just adding tag might not be on board with going this far (or add another answer to this post).
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/120527/discussion-on-answer-by-1muflon1-proposal-to-make-the-site-more-useful-for-exper).
Comment: Thanks for pointing this out. This certainly does pose a problem for my original proposal.
Comment: How about another approach? We can write it up in a separate meta post, but I thought I'd run it by you here first. Suppose we add another custom close reason, as done here: https://economics.meta.stackexchange.com/questions/1464/proposal-for-custom-off-topic-close-reason The new close reason would state "This question does qualify as an expert-level question. For more information on what kind of questions are accepted on this site, see the help page here." (There would then be a link to the help page that describes that this site only accepts expert, professional-level questions.)
Comment: @jmbejara  Also, I am not sure if you read the whole answer or only first half of it - I think we can start with your tagging proposal right away, my point was rather just that the name 'beginner' is problematic when tagging because it is too subjective. This is why I proposed the nonacademic tag name instead but from the above it would work very closely to what you intended. Given how well was your Q and A received I think that  if we settle on right tag-name and description we can start using it. Non-expert tag would in my opinion work as well, laymen would be problematic in my opinion
Comment: I agree with what you say in the comment starting with "we could do that as well...". Just wanted to get first impressions from you before creating any new meta posts.
Comment: Regarding the comment starting "Also, I am not sure...": Your critique that "beginner" is subjective doesn't seem to be a problem. Site policy should strive to be objective, but I believe that at some point subjective rules cannot be avoided. As described in Area 51, the site should be for experts and professional level questions. There doesn't seem like a great way to objectively determine what expert and professional level questions. I see it like this: if we recruit a critical mass of experts on the site, then they can subjectively decide this democratically.
Comment: @jmbejara I agree with you completely here, but there is always a place for subjectivity. Tags are supposed to avoid the problems mentioned in the first 1/2 my A. Of course, voting is great way to express subjective opinion, and even voting to close. For example, if we would add to the rules that non-expert/beginner questions should be voted to close, it would be fine to have that as a rule for closing even if it is subjective - it is just bad rule for *tags*.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/120550/discussion-between-jmbejara-and-1muflon1).
Answer: Disclaimer - I'm only a casual user of this site and no economist.
My recommendation is to do nothing.
As someone with an interest in economics, but no formal education, it's really helpful that a forum like this exists. While I can read up on things online, it can be hard to know the right search terms, or to piece multiple sources together when no single source directly answers the question. It seems that some experts are willing to answer beginner questions, and I feel we'd lose this if the site was segregated by a "beginner" tag. This works both ways - some of my answers have been well received, suggesting there's merit a in layman's answer that strikes a different tone to a formalised academic one.


An example of r.v.s such that their distribution has more (conditional) independencies than their directed graphical model

Question: I was trying to form an example where I had 3 r.v.s such that the distribution describing them had more conditional independencies or independencies than the directed graphical model corresponding to it.
I was told that if we let $X_1, X_2$ be two independent fair coin flips (WLOG 1 indicating heads, 0 indicating tails) and then define $X_3 = X_1 \oplus X_2$ i.e. be the XOR of the result of the coins. Consider its directed graphical model:

I believe that the directed graphical model has less (conditional and marginal) independencies than its distribution. Does someone understand why is this case? Can someone provide me with a rigorous explanation of why this example works? If this is not the case, can someone provide me with a different example? Its ok if it has more than 3 r.vs. If it only involves fair coins that would be even better!
In general, how do you form this kind of example? What is the intuition behind it? Its not 100% intuitive for me why this should work or why its obvious or how do you come up with it.
Answer: Your example works.  In the distribution, $X_1$ is marginally independent of $X_3$.  That is, knowing the value of $X_3$ (but not $X_2$) does not change the distribution of $X_1$, and vice versa.  But the diagram does not show this.  According to the diagram, knowing $X_3$ could change the distribution of $X_1$.
To see this mathematically:
$$
p(X_1=1) = 0.5 \qquad
p(X_3=1) = 0.5
\\
p(X_1=1, X_3=1) = p(X_1=1,X_2=0,X_3=1) = 0.5^2
\\
p(X_1=1 | X_3=1) = \frac{p(X_1=1, X_3=1)}{p(X_3=1)} = 0.5 = p(X_1=1)
$$
and similarly for all values of $X_1$ and $X_3$.  The key step is realizing that $X_2$ can only have one value once $X_1,X_3$ are specified, so that $p(X_1,X_3)$ is always $0.5^2$.
Comment: what I was looking for was more of a **why** this example worked. Do you mind provide some of the details? Knowing just if its true or false was not really what I was looking for.
Comment: Sure, I've added the details.


How to integrate Chromecast APIs in iOS?

Question: I am going to integrate chromecast SDK into iOS, but here I am bit a confuse with receiver.html and whitelist email that exactly how to go with them.
So anyone please explain me regarding same.
Also tell me if it is compatible with any iOS Simulator instead of device.
Comment: look at doc https://developers.google.com/cast/chrome_sender
Comment: I have tried on simulator, it works as expect. You should build your iOS as sender and create one html app on Chromecast device as reciever
Answer: Many developers successfully use the iOS simulator.  https://developers.google.com/cast/cast_2nd-screen_app_tutorial  for iOS and Android.
The Receiver is the HTML5 application that you create that runs on the Chromecast device.  Your iOS application talks to the Receiver, the Receiver will fetch your content from the internet based on the information that comes from your iOS application.


Como mostrar postagem completa ao clicar no botão ler tudo?

Question: Eu estou criando um blog e gostaria de saber como fazer o seguinte.:
Na página inicial eu exibo o titulo, uma imagem e um resumo da postagem, e ao clicar no botão "Ler Tudo", a postagem seja aberta por completo em outra janela do navegador, como em blogs da internet.
Estou desenvolvendo da seguinte forma: Fiz todo o layout de um site para um negócio da minha cidade, mais exatamente uma loja de materiais para construção, e também foi pedido um portal de notícias.
Eu apenas estou realizando testes em um projeto externo, antes de incorporar ao código do site. Vou postar o código para que vocês possam ver. Sou muito leigo com PHP,estou utilizando o Notepad++ para desenvolver meu código.
<?php require( 'conectar.php') ?>
<!doctype html>

        <meta charset="utf-8">
        <title>Blog</title>

        <?php $sql=m ysql_query( " SELECT * FROM postagem ORDER BY data DESC"); $conta=m ysql_num_rows($sql); if($conta <=0 ){ echo '
Nenhuma postagem encontrada.
'; }else{ while($res=m ysql_fetch_array($sql)){ ?>

<?php echo $res['titulo']; ?>

<?php echo $res['postagem']; ?>

        <?php }} ?>

Encontrei a seguinte função.:
function new_excerpt_more($more) {
global $post;
return '… ID) . '">' . 'Ler matéria completa »' . '';
}
add_filter('excerpt_more', 'new_excerpt_more');

Eu conseguiria aplicá-la a minha necessidade?
Comment: Luis, a sua pergunta não é relacionada com php, pelo menos não somente. Pode explicar melhor que blog têm e como pode alterar/criar HTML nessa página? ou quer fazer o redirecionamento no php mudando o `header`?
Comment: Luis, precisamos de mais informações para poder ajuda-lo. Você está fazendo esse blog todo do zero, sem framework? Já tentou alguma coisa? Se sim poste o código.
Comment: Estou desenvolvendo da seguinte forma. Fiz todo o layout de um site para um negócio da minha cidade, mais exatamente uma loja de materiais para construção, e também foi pedido um portal de notícias. Eu apenas estou realizando testes em um projeto externo, antes de incorporar ao código do site. Vou postar o código para que vocês possam ver.
Sou muito leigo com PHP,estou utilizando o Notepad++ para desenvolver meu código.
Sérgio, fui incapaz de compreender sobre esse redirecionamento como disse e sobre a mudança no header.
Nem criei o botão Ler tudo, por não saber a estrutura necessária em PHP.
Comment: Obrigado Sérgio, sou iniciante aqui no stackoverflow, fico grato pelas instruções.
Comment: Você está utilizando WordPress ou encontrou esta função pesquisando no Google?
Comment: @lfarroco, pensei que iria funcionar adaptando, encontrei no google, não uso wordpress.
Não está funcionando ainda, não consigo abrir a postagem completa. Poderia me ajudar com isso?
Encontrei este tutorial, mas não fui capaz de entender nada que foi explicado nele, apenas quero fazer como foi feito ai, quero mostrar todas as postagens resumidas no meu index.php, e abri-las quando clicado no botão Ler Tudo, em uma janela _blank com o mesmo design, só que com a postagem completa.
Answer: Não conheço a estrutura de seu projeto, mais vou tentar explicar.
Você possuí uma página onde exibe todas as postagens, nesta página, no título de cada postagem como em seu código, você adicionou um link que pode levar para outra página, passando como parâmetro o id da postagem que deve ser exibida, exemplo:

     <a href="lerPostagem.php?id=<?php echo $res['id'];?>" title="ler postagem completa">
        <?php echo $res['titulo']; ?>

Na página lerPostagem.php, você deve pegar o parâmetro id via GET e selecionar a postagem em seu Banco de dados:
$id = $_GET['id'];
$sql = mysql_query("SELECT * FROM postagem WHERE postagem.id = $id");

Com a postagem selecionada você pode exibi-la complemente nesta página.
Obs: É necessário tomar cuidados para evitar injeção de SQL, considere utilizar prepare statements com PDO ou Mysqli.
Obs 2: Esta é apenas uma explicação didática, existem N maneiras de fazer, seria preciso conhecer melhor seu projeto para aconselhá-lo melhor.
Comment: Funcionou perfeitamente! Obrigado, consegui compreender o que deve ser feito, eu sabia que isso devia ser feito, mas eu não sabia como fazer.


Finding permutation with a condition

Question: Let $a$ be a permutation in $S_6$. I'm asked whether there is an $a$ so that $a^2 = (123)(456)$
I'm quite confused about where to start. I do know the $a$ must consist of $3$ elements (right?).
How do I proceed?
Comment: What do you mean by an "element" of a permutation?
Comment: @arctictern ugh.. didn't know how to call it, english is not my native language. In my mind, if a=(123) then it has 3 elements.
Comment: The full cycle structure of (123) would be (123)(4)(5)(6). You're essentially talking about non-fixed-points.
Answer: Hints:

What order can $a$ have?
What kind of permutations have that order? (Think cycle structure.)
Now figure out what squaring does to those permutations.

More complete answer.
The order of $(123)(456)$ is $3$, that is $(a^2)^3=e$, or $a^6=e$. Therefore the order of $a$ must be one of the divisors of $6$. It can't be $1$, and it can't be $2$ (since then $a^2$ would be $e$). Can it be $3$ or $6$?
If it has order $3$ then it has cycle structure either $(xyz)$ or $(xyz)(pqr)$. In the former case, the square of a $3$-cycle is another $3$-cycle, so cannot be a product of disjoint $3$-cycles. That leaves the possibility $a=(xyz)(pqr)$. Squaring yields $a^2=(xzy)(prq)=(123)(456)$. See what to do?
If it has order $6$ then $a=(\color{Blue}{q}\color{Green}{r}\color{Blue}{s}\color{Green}{t}\color{Blue}{u}\color{Green}{v})$ and $a^2=(\color{Blue}{qsu})(\color{Green}{rtv})=(123)(456)$. See what to do here?
Comment: Very impressive. Thank you!
Comment: You wrote that if a has order 3 then it could be either (xyz) or (xyz)(pqr). I understand how you negated (xyz), but why can't a be of order 3 and a= (xyz)(pqr)?
Comment: @Matam It can be. I never said it couldn't be of the form (xyz)(pqr).
Comment: Yeah, I miss-read it. So a could be of order 3 and 6?
Comment: Yes. Well, order 3 *or* order 6, not order 3 "and" order 6.
Comment: Much appreciated. Yeah, I meant or :)

Finding permutation with a condition


Confusion in the answers given by mathematica

Question: When I typed in

6^-1 mod 49 in Wolfram|Alpha, it gave me an answer of 41. Link here
If I type the same thing as (1/6) mod 49 , I don't see 41 any more. Why is this happening ?Link here

A Related question :

How is the answer to  6^-1 mod 49 , 41 in the first place ?

A small change in the above question :
If the question is find , 9^-2 mod 49, what are the steps to find the answer ?
Comment: $6\times41=246=245+1=(5)(49)+1\equiv1\pmod{49}$
Comment: You can use the extended Euclidean algorithm to find the modular inverse of $81$, $\bmod 49$. See [this](http://en.wikipedia.org/wiki/Modular_multiplicative_inverse).
Answer: The $41$ is because $6\times 41=246=1\bmod 49$.
I assume that what's happening is that if you type $(1/6)$ instead, it assumes that you're happy to work with rational numbers rather than just integers and gives you back $1/6$.
Comment: In short: `Mod[1/6, 49]` and `PowerMod[6, -1, 49]` are two different things.


Can't start mongod service on Ubuntu

Question: I'm running the latest Mongo release build on Ubuntu 16.04.  I can run it with this command:
mongod --sslMode requireSSL --sslPEMKeyFile /etc/ssl/mongodb.pem

but whenever I run it with:
sudo service mongod start

It exist with a code of 2 (invalid arguments).  This is my mongod configuration in /etc/mongod.conf
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1
  mode: requireSSL
  PEMKeyFile: /etc/ssl/mongodb.pem

I followed the installation instructions and added
ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf

to
/lib/systemd/system/mongod.service

In the /etc/mongod.conf, if I comment out PEMKeyFile and mode, then mongod does start up with ssl.
Comment: Did you find a solution for this?
Answer: You need to have the ssl: section nested under the net: section, or it is at the wrong level and hence an invalid argument. Something like:
net:
   port: 27017
   bindIp: 127.0.0.1
   ssl:
      mode: requireSSL
      PEMKeyFile: /etc/ssl/mongodb.pem

Can't start mongod service on Ubuntu


Is there a concise analytical solution to this system of polynomial equations?

Question: I have a system of equations given by
$$\frac{n_1^3}{3}-\frac{n_1^2}{\mu}+\frac{1}{3k_1}=0 \\
\frac{n_2^3}{3}-\frac{n_2^2}{\mu}+\frac{1}{3k_2}=0 \\
\vdots \\
\frac{n_i^3}{3}-\frac{n_i^2}{\mu}+\frac{1}{3k_i}=0 \\
n_1+n_2+...+n_i=N
$$
where the $k$'s and the $N$ are known, while the $\mu$ and the $n$'s are unknown. I believe that I could solve for the unknowns by using Buchberger's algorithm to find a Groebner Basis, but that gets messy fast. Is there some way to simplify this problem so that a Groebner Basis is not needed and I can find a more manageable analytical solution?
Answer: You can solve the $i$ cubic equations and express the $n_i$ as a function of $\mu$. Then the last identity gives you a single equation in $\mu$.
If you are unlucky, the cubics can have three real solutions, for a possible total of $3^i$. This means that if the problem can be reduced to a univariate polynomial, it will be of degree at least $3^i$, not really concise.
The little monster is
$$\sum_{j=1}^i\left(\sqrt[3]{\sqrt{l_j^2-2l_j\nu^3}-l_j+\nu^3}+\sqrt[3]{-\sqrt{l_j^2-2l_j\nu^3}-l_j+\nu^3}+\nu\right)=N$$
where we used $l_j:=1/{2k_j}$ and $\nu=1/\mu$, for convenience.
If $l_j<2\nu^3$, the $j^{th}$ equation has three real roots.


Sample ACF and PACF of a random walk

Question: Suppose $X_n$are iid $N(0,1)$ random variables. Define $S_n := \sum_{i=1}^n X_n$. Then $S_n$ is a random walk.
Since $Var(S_n) = n$ and $Cov(S_n, S_m) = \min(n,m)$, $S_n$ is not stationary in the first two moments.
Following is a R plot of a sample path of $S_n$, its "sample ACF" (although it is not stationary), and its "sample PACF" (although it is not stationary).
Why does its "sample ACF" decrease linearly?
Why does its "sample PACF" become zero after lag 1? Thanks!
Comment: i have a doubt - 'Sn is not stationary in the first two moments'. Isnt the unconditional mean of random walk constant? when we talk about stationarity of moment do we mean conditional or unconditional moment?
Answer:
Sample ACF is not decreasing linearly. You will get the idea of the pattern by calculating corr($S_n, S_m$)
The answer is followed from the definition of PACF. The above random walk you can express as follows.
$$S_n = S_{n-1} +X_n \qquad n=1,2,\ldots,N, \text{ where } S_0=0 $$

You can take the second PACF expression as correlation between
$$S_{t+2} − \mathcal P (S_{t+2} \mid S_{t+1}) \text{ and } S_{t} − \mathcal P (S_t \mid S_{t+1} ),$$
where $ \mathcal P(W\mid Z)$ is the best linear projection of $ W$ on $ Z$.
$S_{t+2} − \mathcal P (S_{t+2} \mid S_{t+1}) =X_{t+2}$ and second term will be linear function of $X_{i}, i=1,2,\ldots,t+1 $. Since $X_{n}$'s are iid hence, correlation (second order PACF) is zero. Similar way you could prove higher order PACF are zeros.
Comment: For large $N$ and small lags, sample ACF decreases close to linearly, but to see the bigger picture, try something like `acf(S, lag.max=N)` and you will probably see a curve which falls from almost $1$ and heads towards $0$, but where the pattern is rather unpredictable at least on the right hand side and which will change if you run it again with a different seed the $S_n$.

Sample ACF and PACF of a random walk


Error deserializing JSON Cannot deserialize JSON object into type 'System.String'

Question: I have the following JSON:
{"workspace": {
  "name":"Dallas",
   "dataStores":"http://.....:8080/geoserver/rest/workspaces/Dallas/datastores.json",
   "coverageStores":"http://.....:8080/geoserver/rest/workspaces/Dallas/coveragestores.json",
   "wmsStores":"http://....:8080/geoserver/rest/workspaces/Dallas/wmsstores.json"}}

And I´m trying to deserialize int this class:
 class objSON {
        public string workspace { get; set; }
        public string name { get; set; }
        public string dataStores { get; set; }
        public string coverageStores { get; set; }
        public string wmsStores { get; set; }}

 objWS_JSON deserContWS = JsonConvert.DeserializeObject<objWS_JSON>(data);
           var coberturas = deserContWS.coverageStores;
           var almacenesDatos = deserContWS.dataStores;
           var almacenesWMS = deserContWS.wmsStores;
           var nombre = deserContWS.name;

And I get the following error:
Cannot deserialize JSON object into type 'System.String'.
Any ideas? Thanks
Answer: your json is incorrect for the class structure you've provided.  The json implies that name, dataStores, coverageStores and wmsSTores are children of a workspace class.  I think the class structure you want is this:
public class workspace
{
    public string name { get; set; }
    public string dataStores { get; set;}
    public string coverageStores { get; set;}
    public string wmsStores {get; set;}
}

public class objSON
{
    public workspace workspace {get; set;}
}

try that, if that data structure is not what you are after then you need to change your json.
Ok I've just tried in a sample app and seems to work fine.  Here is the code I used:
    class Program
    {
            static void Main(string[] args)
            {

               string str = @"{""workspace"": {
                  ""name"":""Dallas"",
                  ""dataStores"":""http://.....:8080/geoserver/rest/workspaces/Dallas/datastores.json"",
                  ""coverageStores"":""http://.....:8080/geoserver/rest/workspaces/Dallas/coveragestores.json      "",
                  ""wmsStores"":""http://....:8080/geoserver/rest/workspaces/Dallas/wmsstores.json""}}";

                 var obj = JsonConvert.DeserializeObject<objSON>(str);

    }

}

public class workspace
{
    public string name { get; set; }
    public string dataStores { get; set; }
    public string coverageStores { get; set; }
    public string wmsStores { get; set; }
}

public class objSON
{
    public workspace workspace { get; set; }
}

Comment: Thanks for your answer I solve the error but my elements are null
Comment: objWS_JSON deserContWS = JsonConvert.DeserializeObject(data);
           var coberturas = deserContWS.coverageStores;
           var almacenesDatos = deserContWS.dataStores;
           var almacenesWMS = deserContWS.wmsStores;
           var nombre = deserContWS.name;
Comment: Sorry Kevin I was failed with the deserialization I forget change, now is working!. Thanks
Answer: In the JSON, workspace contains all the rest, so you should have something like:
class Container {
    public Workspace workspace { get; set; }
}

class Workspace {
    public string name { get; set; }
    public string dataStores { get; set; }
    public string coverageStores { get; set; }
    public string wmsStores { get; set; }
}

At the very least that matches the structure of the JSON - whether it'll work or not is another matter :)
Comment: so `JsonConvert.DeserializeObject(data);` ?
Comment: @RoyiNamir: Yup, I'd expect so.
Comment: Thanks, in data I change the slash \ of my JSON by this /
Comment: Yes, because data is the JSON clean whithout backslashes
Comment: @JMG: So where do the backslashes come into it at all? It's unclear why you've suddenly brought them up... you shouldn't need to replace anything.
Answer: If you look at the JSON object (it is perhaps better if you laid out your { and } a little more clearly), you'll see that it is trying to serialize all that data in to the workspace field, and not the other properties.  I would expect your object to look something more like:
{
   "workspace": "whatever",
   "name":"Dallas",
   "dataStores":"http://.....:8080/geoserver/rest/workspaces/Dallas/datastores.json",
   "coverageStores":"http://.....:8080/geoserver/rest/workspaces/Madrid/coveragestores.json",
   "wmsStores":"http://....:8080/geoserver/rest/workspaces/Madrid/wmsstores.json"
}


Java: Exception Handling not working

Question: i have a program that I am trying to add exception handling to. The problem is, the exception that i wrote up still exits the program. Basically i offer the user to enter in any int, if they throw me a char, the exception says that they cant do that and lets them enter another int. But it isn't working giving me this error:
<code>Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:909)
    at java.util.Scanner.next(Scanner.java:1530)
    at java.util.Scanner.nextInt(Scanner.java:2160)
    at java.util.Scanner.nextInt(Scanner.java:2119)
    at cit130_hw10_q3.Cit130_hw10_q3.main(Cit130_hw10_q3.java:29)
</code>
Java Result: 1
Here's some code. Thanks for any help you might offer.
<code>   Scanner input = new Scanner(System.in);
   System.out.println("Enter a series of integers." +
           "When finished enter 999");
   int userInput = 0;
   int inputCount = 0;
   do{
       try{
           System.out.println("Enter an integer: ");
           userInput = input.nextInt();
           addToArray(userInput, inputCount);
       }
       catch(Exception e){
           System.out.println("Only integer values are accepted. Please try again");

       }
       inputCount++;
   }while (userInput != 999);

public static void addToArray(int nextInt , int inputCount){
    integerArray[inputCount] = nextInt;
}
</code>
Comment: Clear the project, recompile it and retry. Also ensure `Exception` is `java.lang.Exception` not something else
Comment: Also, note that if `nextInt` throws `InputMismatchException`, it will _not_ advance the scanner. Calling `nextInt` again will just try to re-read the same non-`int` again. You need to invoke `next()` in the `catch` block to advance the token. With that additional tweak, your code works fine on my computer. I think RC has it right.
Comment: Your `addToArray` function might throw some more light on the problem you are facing.. Please show that code..
Comment: I guess you mean **while (inputCount != 999)** ?
Comment: @VikasV that would show up in the stack trace though. The stack trace is indicating a problem in main, not in a function.
Comment: @yshavit was correct with his comment. I added the "next()" in the catch statement and now it works fine. The program was getting stuck on that mismatched input
Comment: @yshavit You should post that as an answer
Comment: @nfoggia this still doesn't explain the stack trace. That must've been from some other version of code.
Comment: @MistressDavid That would just be taking credit for RC's answer, which is the real one. :) I just added color commentary on the next bug the OP is likely to face, once they do recompile.
Comment: well in my code that i didn't include here, i had a input.nextInt() in the catch, i removed that and got rid of the trace
Comment: @nfoggia It needs to be just `input.next()`, not `input.nextInt()`. That way it will succeed (and advance the token) no matter what the input is.
Comment: @yshavit yup, thanks for the help =) if you want to put it in answer form id be happy to accept it so others can see what i did wrong. and learn from your correction. haha. thanks everyone
Answer: I suspect you forgot to recompile in-between or are running some other version of the code, maybe a different file than this. If you have java.lang.Exception catched like you show, this will ot happen.
Other option is that you have input.nextInt(); somewhere else, too, in a part that you did not paste here. Reconfirm line 29.
Answer: Excpetion class is the base class for all exceptions and if you are unsure of exception type you can catch it through java.lang.Excpetion and this works perfectly. In your case please put a break point in the try catch block and then confirm the point where exception is thrown. This will give an insight as why it is not getting catched at the place you mentioned
Comment: That would be better posted as a comment
Comment: Ya you are correct as per stack overflow guidelines this was suppose to be a comment

Java: Exception Handling not working


Hiding mysql connection datas on Git repository

Question: I have a public repository on Github. It's an online web service. We just want to share source codes of our web service. We are storing all connections datas and functions on connect.php file. And including it to other files, when necessary. We want to hide this file from all visitors except collaborators of repository.
Is it possible? Or are there other way?
Answer: What you want to do is stop Git from tracking the file changes.

Move any sensitive strings from connect.php into a new file called config.php
Fill in with sample string
Include config.php in connect.php
Commit to Git
Use git update-index --assume-unchanged <file> to stop tracking updates to this file.
Update the file with your production strings
If you ever need to track changes again use git update-index --no-assume-unchanged <file>
Comment: We are storing it on a `connect.php` file and including it to other files, when necessary. I can add `connect.php` file to `.gitignore` but this will ignore it for commit. I mean, our connect.php file will NOT committed and pushed to GitHub. So, other collaborators can't see that file.
Comment: you could break out any sensitive strings to a new include file.  Upload a sample version of this file to Git so people know how to configure it for their server.  Afterwords you just don't commit your production version
Comment: `git update-index --assume-unchanged ` This is exactly what i need ! Thank you @NSjonas.
Answer: Put a file called .gitignore inside your folder that contains the name of the file you want to ignore !
Comment: But this will ignore it for commit. I mean, our connect.php file will NOT committed and pushed to GitHub. So, other collaborators can't see that file.
Comment: I see your point. I don't know then, but I think my approach is still valid. As NSjonas said, you would commit a template for the config file and your developers would have a static version of the file. After all, it is probably never gonna change.


Sass não compila caracter especial

Question: Tenho um ::after no meu código sass com o content "m²", a questão é que depois de compilado o ² vira erro:
Ele está imprimindo em UTF-8 (@charset "UTF-8";), realmente não entendo o motivo do erro.
Comment: Eu estava com dificuldade de encontrar o código do caracter especial, ai achei um conversor de caracteres especiais online. Segue o link, caso seja útil pra mais alguém: http://www.evotech.net/articles/testjsentities.html
Answer: Tenho uma resposta que pode te ajudar. Ela não resolve o bug de compilação, mas resolve a questão do número sobrescrito no content.
Repare o content:"" do elemento ::after pode receber caracteres em unicode, mas para resolver isso vc pode usar o código unicode do caractere substituindo o "m²" por "m\00B2". Assim vc evita o caractere especial e usa o apenas o código unicode do caractere.
Veja como fica executando o exemplo. E teste para ver se passa no compilador do SASS (acredito que vai funcionar!)

span::after {
    content: "m\00B2" ;
}
num:

Aqui tem uma tabela de caracteres sobrescrito e subscrito unicode que pode te interessar: https://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts#Superscripts_and_subscripts_block
Comment: @ThaviLang legal que resolveu, se vc quiser usar o 3 por exemplo o código é `\00B3`, mas vc pode consultar a tabela do link que lá tem mais algumas opções! Boa sorte ai []´s
Comment: Caaara, funcionou. Pra mim já é o bastante!! hahaha' Eu tinha tentado por o código do caracter, mas acho peguei de uma tabela errada. Obrigada! :)

Sass não compila caracter especial


is there a place in the .info file to set a url to check for updates?

Question: I created a custom theme to serve as the base for all my company's future drupal projects, that includes all of our base requirements. The sites will live on different servers, and each site will have it's own subtheme.
Drupal themes compare versions w/ the drupal projects server to check for updates.
I do not want to submit my company's theme to the drupal.org, as it has company specific features.
The goal is to be be able to update the theme in a "local" central repository, and have the various drupal sites check for version updates.

is there a place in the .info file to set a url to check for updates?

The version number is pretty easy to set.
Answer: Yes, you can use project status url:

Allows module maintainers to define a URL to check for updates to their module using the Update status module. No module released on drupal.org should define this parameter. URL should point to an XML feed that accepts requests in the form of http://my.domain.com/projects/{project}/{core}. In that example, project status url should be set to http://my.domain.com/projects.

See Writing module .info files (Drupal 7.x) for full details.
Comment: There must have been like....2 seconds in this -_-
Comment: Heh, I'm getting infinity on friday, my line must be getting quicker already ;)
Answer: Have you read the docs?

project status url (Only used for custom modules not submitted to
  drupal.org)
Allows module maintainers to define a URL to check for
  updates to their module using the Update status module. No module
  released on drupal.org should define this parameter. URL should point
  to an XML feed that accepts requests in the form of
  http://my.domain.com/projects/{project}/{core}. In that example,
  project status url should be set to http://my.domain.com/projects.


Como visualizar através do breakpoint quais valores foram passados para o meu método?

Question: Gostaria de saber se é possível sem usar o Debug.WriteLine visualizar os valores passados para o meu método através do Visual studio utilizando um BreakPoint, seja por algum recurso externo ou não.
Comment: Eai, jovem. A resposta atendeu o que você precisava?
Comment: Atendeu sim LINQ, desculpa a demora para marcar como correta ! Obrigado c: +1 para ti(como sempre mandando boas respostas).
Comment: De boa, eu sei que você já é experiente no site e sabe como usá-lo, então nem fico grilado com a não-aceitação. Eu só queria saber se eu realmente tinha entendido bem a tua pergunta. Enfim, que bom que consegui te ajudar =D
Answer: É só pôr um ponto de interrupção (breakpoint) no método e passar o mouse sobre os parâmetros.

Ou colocar as variáveis na janela watch


Postgres alleviate update lock contention while maintaining nonce

Question: I have a balance table which is being updated each time a client request is registered. The balance   account will be updated, and a corresponding transaction record inserted. A transaction record will keep a nonce field which increments sequentially. Essentially a transaction will look like below, where , and  are pull out of the previous UPDATE result.
BEGIN;

UPDATE client_balances SET nonce = nonce + 1, balance_amount = balance_amount - 100 WHERE client_id = 100 RETURNING *;

INSERT INTO transaction_records (date, client_id, nonce, balance_changed, balance_amount) VALUES (TIMESTAMPTZ '2023-01-01-XXX', 100, <nonce>, -100, <balance_amount> RETURNING *;

COMMIT;

When concurrent requests reaches ~200/seconds to a single client balance account, the UPDATE clause will reach its performance limit, and will take around 400ms on average to complete on a moderately performant Linux box. This is due to lock contention from the ~80 concurrent connections to the database which all tries to update the same balance record.
To alleviate the problem, I decided to divide the client_balance record into 32 bins for each client, so concurrent updates can be distributed evenly and randomly into those bins. What this means in code is:
BEGIN;

UPDATE client_balances SET nonce = nonce + 1, balance_amount = balance_amount - 100 WHERE client_id = 100 AND bin = <rand_int_from (0,31)> RETURNING *;

SELECT SUM (nonce) AS nonce_aggr, SUM (balance_amount_aggr) AS balance_amount FROM client_balances WHERE client_id = 100 returning *;

INSERT INTO transaction_records (date, client_id, nonce, balance_changed, balance_amount) VALUES (TIMESTAMPTZ '2023-01-01-XXX', 100, <nonce_aggr>, -100, <balance_amount_aggr> RETURNING *;

COMMIT;

Now each time a client balance is used, it is aggregated from the 32 bins. <nonce_aggr> and <balnce_amount_aggr> are also from the aggr in the postgres transation. The balance seems to be correct, however, nonce in the records will not be: instead of being sequential like 1, 2, 3, 4..., it will now become 1, 2, 2, 2, 5, 6..., although the total count is correct. This is totally understandable because the UPDATE clause only locks one of the 32 bins.
To correct the nonce, is it advisable to take 32 locks on all the 32 bins? Or is there a better way of doing this?
I will need the nonce field in the records to be in sync with the balance record. So a balance change like below
   nonce.     change.      balance
   1001.                            20000.    (initial)
   1002.       +10              20010
   1003.       +30.            20030

Should generate two transaction records 1002 and 1003, as such. Postgres's builtin sequence will not be in sync under such
Comment: The better way is not to do it.  Why are you doing this at all? You could use a sequence to get a nonce.
Comment: I edited the content to describe the requirement for the nonce to be in sync with the balance record. Nevermind issue is solved.
Answer: The lock on client_balances will be held until the end of the transaction. So to improve concurrency as much as possible:

update client_balances as the last statement in the transaction, so that the row will be locked as briefly as possible

use a prepared statement for the UPDATE, so that the execution time will be as fast as possible
Comment: Thanks for the answer. The planning phase is fast enough so prepared statement will not help too much. Also client_balances cannot be hte last statement in the transaction - I will need its updated nonce to be populated in the records. Anyways the performance issue is solved using a separate aggregator step instead. Thanks anyway.


Proof for $HK = \operatorname{grp}\{H \cup K\} \iff HK \text{ is a subgroup of } G$

Question: If $H$ and $K$ are subgroups of a group $G,*$, how can one proof that:
$$HK = \operatorname{grp}\{H \cup K\} \iff HK \text{ is a subgroup of } G$$
I've seen similar proofs on the internet, but there the subgroups $H$ and $K$ were normal subgroups. I think it is also possible to prove with subgroups, but can't figure out how to prove it without the condition of normal subgroups.
Comment: I assume $grp\{X\}$ denotes the subgroup of $G$ generated by the set $X$?
Comment: @Belgium_Physics And in Group Theory one denotes this as $\langle X \rangle$.
Answer: If $HK$ is the subgroup generated by $H\cup K$, then it is of course a subgroup.
On the other hand, if $HK$ is a subgroup of $G$, then it is clearly the smallest subgroup containing both $H$ and $K$ (as any such subgroup must contain all $hk$ with $h\in H$, $k\in K$).


How to get OSGiScriptEngineManager running

Question: I'm not quite a total newbie to OSGi, but apparently newbie enough.
What I want to do is write an OSGi (Apache Felix) bundle and use the Java scripting API (JSR-223) with for example Groovy. For this I installed groovy 2.4.12, which already is an OSGi bundle, and I see the Groovy Runtime (2.4.12) as an active service in Felix's Remote Shell Console.
I also understand the conflict between Java's ServiceLoader API and OSGi's bundles. This Is OSGi fundamentally incompatible with JSR-223 Scripting Language Discovery? refers to a blog stating that Felix has found a workaround already.
All good. But then. What do I need to import to use that OSGiScriptEngineManager sniplet?
Answer: If you use Maven, something like this could work:
<code> <dependency>
     <groupId>org.apache.felix</groupId>
     <artifactId>org.apache.felix.mishell</artifactId>
     <version>1.0.0</version>
 </dependency>
</code>
But I think this package was never released, probably a dead project. Well, you can try to compile it yourself from https://github.com/Dexels/apachecon/tree/master/org.apache.felix.mishell
I try to avoid ServiceLoaders, and if you say they offer Groovy as OSGi Service, then you really should use that.
If you just want to use Groovy, I suggest this:
<code>import org.codehaus.groovy.jsr223.GroovyScriptEngineFactory;
import javax.script.ScriptEngine;

public class Test {

    public static void main(String[] args) {
        ScriptEngine e = new GroovyScriptEngineFactory().getScriptEngine();
    }
}
</code>


Como bloquear a 'scrollbar' quando estiver navegado em um aparelho desktop?

Question: Estou utilizando Bootstrap 4. Como bloquear a 'scrollbar' (a barra lateral de rolagem) quando estiver navegado em um aparelho desktop?
Comment: Vc quer saber se está num "desktop" de verdade ou saber pela resolução da tela? Pela resolução da tela é difícil porque existem tablets e smartphones de alta resolução.
Answer: Você pode utilizar media-queries para remover o scrollbar. No exemplo abaixo, filtramos o media type screen e a largura min-width para caracterizar um Desktop.
Isso nos permite remover o scroll considerando apenas para as características selecionadas.
    /* Medium Devices, Desktops */
    @media only screen and (min-width : 992px) {
      html {
             overflow: hidden;
           }
    }


Create Python string placeholder (%s) n times

Question: I am looking to automatically generate the following string in Python 2.7 using a loop based on the number of columns in a Pandas DataFrame:
INSERT INTO table_name (firstname, lastname) VALUES (534737, 100.115)

This assumes that the DataFrame has 2 columns.
Here is what I have:
# Generate test numbers for table:
df = pd.DataFrame(np.random.rand(5,2), columns=['firstname','lastname'])

# Create list of tuples from numbers in each row of DataFrame:
list_of_tuples = [tuple(x) for x in df.values]

Now, I create the string:
Manually - this works:
add_SQL = INSERT INTO table_name (firstname, lastname) VALUES %s" % (list_of_tuples[4])

In this example, I only used 2 column names - 'firstname' and 'lastname'. But I must do this with a loop since I have 156 column names - I cannot do this manually.
What I need:

I need to automatically generate the placeholder %s the same
number of times as the number of columns in the Pandas DataFrame.
Here, the DataFrame has 2 columns so I need an automatic way to
generate %s twice.
Then I need to create a tuple with 2 entries,
without the ''.

My attempt:
sss = ['%s' for x in range(0,len(list(df)))]
add_SQL = "INSERT INTO table_name (" + sss + ") VALUES %s" % (len(df), list_of_tuples[4])

But this is not working.
Is there a way for me to generate this string automatically?
Comment: But in any event, if you just want `%s` placeholders, we can build that string first: `placeholder = ",".join(["%s"]*len(df))`, and then `add_SQL = "INSERT INTO table_name (%s) VALUES (%s)" % (placeholder, placeholder)`. If you actually want column names and values, make two initial strings: `column_names = ",".join(columns)` and `values = ",".join(values)` and use them instead of placeholder appropriately, where `columns` and `values` are lists you have lying around (`values = list_of_tuples[i]`, for example).
Comment: I'm not really clear on how your attempt is supposed to match what you have above: above, you have `(firstname, lastname)`, but in your attempt, it looks like you just want `(%s, %s)`, though you're using `len(df)` which is just going to give you a number... do you want column names, or do you want literal `%s`?
Comment: With parts of your solution, I posted a reply below as the "answer", but there is still a question since I can't seem to get your exact layout in one line. See the post ("Answer") below and let me know what you think in the comments below it.
Answer: Here is what I came up with - it is based on dwanderson's approach in the 2nd comment of the original post (question):
table_name = name_a #name of table

# Loop through all columns of dataframe and generate one string per column:
cols_n = df.columns.tolist()
placeholder = ",".join(["%s"]*df.shape[1]) #df.shape[1] gives # of columns
column_names = ",".join(cols_n)
insrt = "INSERT INTO %s " % table_name
for qrt in range(0,df.shape[0]):
   add_SQL_a_1 = insrt + "(" + column_names + ") VALUES (" + placeholder + ")" #part 1/2
   add_SQL_a_2 = add_SQL_a_1 % list_of_tuples[qrt] #part 2/2

This way, the final string is in part 2/2.
For some reason, it would not let me do this all in one line and I can't figure out why.
Comment: dwanderson, any thoughts as to why the string could not be assembled in one line?


C# Dice game, Sum returns only sum of last 2 rolls not whole game

Question: I'm creating a dice game with 2 dice, i have got it working but only problem is i cant seam to get the Sum from all the rolls(whole game), i only get the sum of last 2 rolls if i use the Sum method, how do i find the Sum of all the rolls? Here's my code:
        Console.BufferHeight = 500;
        Random x = new Random();
        int throw_times = 1;

        int[] dice = new int[2];
        dice[0] = x.Next(1, 7);
        dice[1] = x.Next(1, 7);

        for (int i = 1; i <= 100; i++)
        {
            dice[0] = x.Next(1, 7);
            dice[1] = x.Next(1, 7);

            int total_var = dice[0] + dice[1];
            int[] total_array = {dice[0] + dice[1]};//total in array

            Console.Write("Throw " + throw_times + ": " + dice[0] + " and " + dice[1] + " = ");
            Console.WriteLine(total_var);
            throw_times++;

            Array.Sort(dice);

            for (int a = dice.Length - 1; a >= 0; a--)
            {
                int s = dice[a];
                Console.WriteLine("#" + s);
            }
        }

        Console.WriteLine("Total sum: " + dice.Sum());//only returns sum of last 2 rolls
        Console.WriteLine("Average: " + dice.Average());//only return average of last 2 rolls

If anyone has any idea how i can get the total roll sum please answer, greatly appreciated.
Comment: If p.s.w.g answer is correct and helped you please mark it as the real answer..
Answer: The Sum and Average extension methods will compute the sum and average of what's currently in the array, and because you're re-setting the array with every trial, it will only ever contain the last two items.
To get the sum or average of all the dice rolls, you'd either have to expand your array so that it records all the dice rolls made throughout your program, or just keep a running total (which seems a lot simpler):
int[] dice = new int[2];
int sum = 0;

for (int i = 1; i <= 100; i++)
{
    dice[0] = x.Next(1, 7);
    dice[1] = x.Next(1, 7);
    sum += dice[0] + dice[1];

    ...
}

Console.WriteLine("Total sum: " + sum);

Now it's not entirely clear from your question if you also want the average of all the dice rolls, or just the last two, but since you know the sum and you know the total (because that's hard coded in your app), you can compute the average of all dice rolls pretty easily:
Console.WriteLine("Total sum: " + (sum / 200)); // 200 because you roll 2 dice in 100 trials

Comment: Thank you for this answer, i should've seen that tho. Thanks again!


Setting up Coordinates system in OpenGL

Question: I am using OpenGL with the LWJGL library in java. As I understand it, you can use glFrustum to set up the top, bottom, left, right, near and far coordinates and you then use glViewport to relate those coordinates to the screen, is this correct ?
I assume this because nothing I have read has said otherwise and this is how it worked when I was using orthographic mode.
To expand on my question, I set up my application like this (in c syntax)
glFrustum(-100, 100, -100, 100, -100, 100);
glViewport(0, 0, 800, 600); // the screen size is 800 by 600

. . .

glBegin(GL_QUADS); //draw a rectangle
glVertex2f(-0.25f, -0.25f);
glVertex2f(0.25f, -0.25f);
glVertex2f(0.25f, 0.25f);
glVertex2f(-0.25f, 0.25f);
glEnd();

How is it possible that with a coordinates system of -100-----0-----100 on the x and y axis, that I get a rectangle of a size that looks like that the coordinates i supplied have been multiplied by 10 ?
Answer:
As I understand it, you can use glFrustum to set up the top, bottom, left, right, near and far coordinates

Not quite. glFrustum creates a affine perspective projection matrix, having the shape of a pyramid with the tip cut of – a frustum. If you'd extend that pyramid to the tip, the tip was at the coordinates (0,0,0), the near parameter defines the distance of the XY plane to the tip in Z direction as where to "cut" that pyramid. The far plane gives the distance to the pyramids base. The left, right, top and bottom parameters define, where the sides of the pyramid intersect with the near plane, which means, that the pyramid is not required to be symmetric. It can be shifted as well.

and you then use glViewport to relate those coordinates to the screen, is this correct?

OpenGL is a state machine. The order in which you call set those states doesn't matter. You can change each state anytime, anyhow. The order is only important then, if the previous state contributes to the data/parameters setting the new state. The matrix operations are an example, because the operate on the previous state. But glViewport is independent of this.

How is it possible that with a coordinates system of -100-----0-----100 on the x and y axis, that I get a rectangle of a size that looks like that the coordinates i supplied have been multiplied by 10?

Because you're not building a valid frustum. The near and far planes of a frustum projection must not have opposite signs. Usually you want them to be both positive. Also the near plane distance must be nonzero.
The way you defined your "frustum" is is shaped like an hourglass. Also your vertices are at Z=0, so they're in the singularity of that frustum and anything may happen there.
I think you actually wanted a ortho projection.
Comment: @lilroo: Well, that depends on your modelview and projection matrices and the viewport. It's explained in detail here: http://www.opengl.org/wiki/Viewing_and_Transformations
Comment: Hmm; [`glFrustum`](http://www.opengl.org/sdk/docs/man/xhtml/glFrustum.xml) shouldn't change anything but generate an error. The quad then contains exactly a quarter of the screen in both x and y.
Comment: Your answer was very usefull and has added to my understanding, however how do I orient the coordinates of vertices ? For instance how do i know where the coordinate 5,5,5 is ?

Setting up Coordinates system in OpenGL


SEO plugin doesn't work in Hippo CMS

Question: I'm using Hippo CMS and trying to implement SEO plugin. I did everything by manual but I don't see any changes and meta tags in rendered results.
My basic layout is:

<#include "/WEB-INF/freemarker/include/imports.ftl">

    <meta charset="utf-8"/>
    <@hst.headContributions/>
    <link rel="stylesheet" href="<@hst.link  path="/css/bootstrap.css"/>" type="text/css"/>
    <@hst.defineObjects/>
    <#if hstRequest.requestContext.cmsRequest>
      <link rel="stylesheet" href="<@hst.link  path="/css/cms-request.css"/>" type="text/css"/>
    </#if>

And I just enable plugin over Hippo Setup -> features. And sure then rebuild and run all again.
Then I'm going to Channel Editor -> Edit Page -> Add Component. The drag n drop component on page.
I did all changes by clicking on component. But anyway I don't see any changes on published page.
I didn't find any documentation about that, but maybe somebody resolve this issue and can help to me!
Thanks
Comment: Do you get any exceptions or does it 'just not' work?
Answer: I tried it out as well. It indeed does not work out of the box as you would expect. The component uses a template specific of the Setup feature, the seo.ftl. This makes it work as a draggable component in the channel manager. What it does not do is add the configured data to the html head.
If you check the seohelper.ftl [1] of the forge plugin, there you see the code that does this job. What you can do to make it work in your project is add the headcontribution tags as in [1] to seo.ftl. Also make sure you have a <@hst.headcontributions/> tag in the html head section of the base-layout.ftl of your project.
I will create a jira issue for this so.
[1] http://forge.onehippo.org/gf/project/hst-seo-support/scmsvn/?action=browse&path=%2Fcheckout%2Fhst-seo-support%2Fbranches%2Fhst-seo-support-1.01.xx%2Fsrc%2Fmain%2Fjava%2Forg%2Fonehippo%2Fforge%2Fseo%2Fsupport%2Fseohelper.ftl&revision=157
Comment: This is the issue that you may track for progress: https://issues.onehippo.com/browse/ESSENTIALS-572

SEO plugin doesn't work in Hippo CMS


Como fazer progresso de etapas utilizando gráfico de rosca?

Question: Estou desenvolvendo uma tela utilizando o progresso do aluno, por exemplo, ele tem 10 atividades para serem completadas, e está na atividade 2, então isso representa 20% do total da atividade.
Gostaria de representar isso através de um gráfico de rosca, um botão para próximo exercício, algo assim:

Conforme clico em próximo, a barra de progresso se move para a direita a fim de completar a rotação do circulo, e o número de dentro sobe de 1/7 para 2/7.
Seria muito interessante a resposta em somente CSS e JavaScript, ou algo assim.
Obrigado
Answer: Fiz esse modelo usando um circulo em SVG com contorne e dasharray para controlar o tamanho do contorno, e css variable que vou mudar com JS para fazer o contorno no SVG crescer completando o gráfico a cada clique.
Sobre o círculo feito com SVG nessa forma de gráfico vc pode ler mais aqui: Desenhar circulo no Html5
Sobre CSS variables vc pode ler mais aqui: O que significa o -- especificado no :root do css do bootstrap?

O valor total da circunferência do dasharray é 255, logo, divido 255 por 7 e tenho 36.42 que é o valor de cada step. No JS eu vou fazendo esse incremento até o counter chegar em 7, ao mesmo tempo que eu pego a variável --size declarada no :root e vou diminuindo as frações de 7.
Segue o código da imagem acima:

var btn1 = document.getElementById("button1");
var counters = document.querySelectorAll(".counter");
let root = document.documentElement;
var size = 36.42;

btn1.addEventListener("click", btn1Count);

function btn1Count(event) {
    let atual = parseInt(counters[0].innerHTML);

    if (atual == 7) return;

    counters[0].innerHTML = atual + 1;
    root.style.setProperty('--size', 255 + 36.42 - (size += 36.42));
}
.graph {
    text-align: center;
    width: 100px;
    height: 100px;
    line-height: 60px;
    text-transform: uppercase;
    font-family: sans-serif;
    text-decoration: none;
    font-size: 14px;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
}

svg {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    fill: transparent;
    stroke-width: 12px;
    stroke: #ddd;
}

:root {
    --size: 255;
}

.graph svg.cor {
    stroke: green;
    stroke-dasharray: 255;
    stroke-dashoffset: calc(var(--size) - 36.42);
    transform: rotate(-90deg);
    transform-origin: center;
}

    <svg>
        <circle cx="50" cy="50" r="40" />
    </svg>
    <svg class="cor">
        <circle cx="50" cy="50" r="40" />
    </svg>
    1/7

<button id="button1">próxima</button>
Comment: @David valeu meu caro! a vantagem é que não tem praticamente nada de código comparado com plugins e outras bibliotecas, assim é mais fácil de vc manter o controle do que tem no seu projeto etc... E sim, é bem fácil de editar customizar etc, assim como no JS no CSS vc pode criar quantas --var quiser e usar onde o número de tarefas for diferente. []´s
Comment: Hugo, gostei muito da forma que você exemplificou, as vezes o total de atividades pode mudar, mas é facil alterar isso, parabéns !
Answer: Uma sugestão é criar barras de progresso com JavaScript e mostrar as barras de acordo com o progresso, proporcional ao máximo de passos, sem uso de bibliotecas ou jQuery, com JavaScript puro.
O código puxa o valor da div para determinar o número de passos. Por exemplo, se a div possui o texto 1/7, o código puxa o 7:
HTML:

1/7

JS:
var maximo = +prog.textContent.trim().split("/")[1]; // 7

Ou seja, não precisa mudar nada no CSS ou no código, porque o valor dos passos é capturado de forma automática de acordo com o texto na div.
A medida que o botão Próximo é clicado, vai incrementando os passos e mostrando proporcionalmente as barras de progresso.
Vou deixar 3 exemplos com valores diferentes:
Exemplo com 7 passos:

document.addEventListener("DOMContentLoaded", function(){

   const p_ = document.getElementById("progresso");
   var b_ = '';
   for(let x=0; x < 360; x++){
      b_ += '';
   }
   p_.innerHTML += b_;

   var prog = document.querySelector("#progresso div");
   var maximo = +prog.textContent.trim().split("/")[1];
   var atual = 1;
   var bar_step = Math.floor(360/maximo);
   var bars = document.querySelectorAll("#progresso span");

   function passos(atual){
      var limit = atual == maximo ? bars.length : atual*bar_step;

      prog.innerHTML = atual + "/" + maximo;
      for(let b = 0; b < limit; b++){
         bars[b].style.display = "inline-block";
      }
   }
   passos(atual);

   document.getElementById("next").onclick = function(){
      if(atual < maximo){
         atual++;
         passos(atual);
      }
   }

});
#progresso, #progresso div{
   width: 100px;
   height: 100px;
   border: 2px solid #000;
   border-radius: 50%;
   background: #fff;
   display: flex;
   justify-content: center;
   align-items: center;
   position: relative;
}

#progresso div{
   position: absolute;
   width: 60%;
   height: 60%;
   z-index: 1;
}

#progresso span{
   display: inline-block;
   width: 2px;
   height: 50%;
   background: red;
   position: absolute;
   left: 50%;
   margin-left: -1px;
   top: 0;
   transform-origin: bottom;
   display: none;
}

1/7

<button id="next">Próximo</button>

Exemplo com 3 passos:

document.addEventListener("DOMContentLoaded", function(){

   const p_ = document.getElementById("progresso");
   var b_ = '';
   for(let x=0; x < 360; x++){
      b_ += '';
   }
   p_.innerHTML += b_;

   var prog = document.querySelector("#progresso div");
   var maximo = +prog.textContent.trim().split("/")[1];
   var atual = 1;
   var bar_step = Math.floor(360/maximo);
   var bars = document.querySelectorAll("#progresso span");

   function passos(atual){
      var limit = atual == maximo ? bars.length : atual*bar_step;

      prog.innerHTML = atual + "/" + maximo;
      for(let b = 0; b < limit; b++){
         bars[b].style.display = "inline-block";
      }
   }
   passos(atual);

   document.getElementById("next").onclick = function(){
      if(atual < maximo){
         atual++;
         passos(atual);
      }
   }

});
#progresso, #progresso div{
   width: 100px;
   height: 100px;
   border: 2px solid #000;
   border-radius: 50%;
   background: #fff;
   display: flex;
   justify-content: center;
   align-items: center;
   position: relative;
}

#progresso div{
   position: absolute;
   width: 60%;
   height: 60%;
   z-index: 1;
}

#progresso span{
   display: inline-block;
   width: 2px;
   height: 50%;
   background: red;
   position: absolute;
   left: 50%;
   margin-left: -1px;
   top: 0;
   transform-origin: bottom;
   display: none;
}

1/3

<button id="next">Próximo</button>

Exemplo com 5 passos:

document.addEventListener("DOMContentLoaded", function(){

   const p_ = document.getElementById("progresso");
   var b_ = '';
   for(let x=0; x < 360; x++){
      b_ += '';
   }
   p_.innerHTML += b_;

   var prog = document.querySelector("#progresso div");
   var maximo = +prog.textContent.trim().split("/")[1];
   var atual = 1;
   var bar_step = Math.floor(360/maximo);
   var bars = document.querySelectorAll("#progresso span");

   function passos(atual){
      var limit = atual == maximo ? bars.length : atual*bar_step;

      prog.innerHTML = atual + "/" + maximo;
      for(let b = 0; b < limit; b++){
         bars[b].style.display = "inline-block";
      }
   }
   passos(atual);

   document.getElementById("next").onclick = function(){
      if(atual < maximo){
         atual++;
         passos(atual);
      }
   }

});
#progresso, #progresso div{
   width: 100px;
   height: 100px;
   border: 2px solid #000;
   border-radius: 50%;
   background: #fff;
   display: flex;
   justify-content: center;
   align-items: center;
   position: relative;
}

#progresso div{
   position: absolute;
   width: 60%;
   height: 60%;
   z-index: 1;
}

#progresso span{
   display: inline-block;
   width: 2px;
   height: 50%;
   background: red;
   position: absolute;
   left: 50%;
   margin-left: -1px;
   top: 0;
   transform-origin: bottom;
   display: none;
}

1/5

<button id="next">Próximo</button>
Comment: É isso mesmo produção, temos aqui javascript puro e CSS <3 ficou foda @Sam, parabéns !
Comment: Assim não da para competir
Comment: @hugocsl rsrs.. é nóis!
Answer: Quando precisei usar um contador assim eu usei o Circliful. É um plugin jQuery muito fácil de usar e customizar, tem uns 20 atributos pra alterar se quiser e ele funciona muito bem.
Única dificuldade que eu encontrei nele foi que toda vez que queria mudar a quantidade dentro do circulo (passar de 1 pra 2 por exemplo como vc disse), voce precisa esvaziar a div que contem o elemento circliful e gerar de novo com o novo numero. Meio gambiarra mas funciona.
$("#test-circle5").circliful({
    animationStep: 5,
    foregroundBorderWidth: 5,
    backgroundBorderWidth: 15,
    percent: 80,
    halfCircle: 1,
});

Um exemplo de uso.
Comment: O problema é que eu preciso inserir mais texto dentro, e ao invés de % ter os valores do passo, mas obrigado
Answer: Existem diversas bibliotecas em javascript que podem te ajudar nessa situação, vou deixar dois exemplos, um com uma biblioteca javascript e outro somente com css. Seguem:
Percircle
Com ele você consegue manipular de forma mais simples os valores, tornando os saltos dinâmicos e com implementações ajax para salvar o progresso dos alunos.
Github para referencia futura

$(document).ready(function() {
  $("#fif").percircle({
    percent: 30,
    text: "30"
  });
  $('#pular').click(function(e) {
    e.preventDefault();
    mudar();
  });
});

function mudar() {
  $("#fif").percircle({
    text: "50",
    percent: 50,
    progressBarColor: "#1ec0b0"
  });
}

<link rel="stylesheet" href="https://thodorisbais.github.io/percircle/dist/css/percircle.css">

<button id="pular">Pular para 50</button>

Exemplo em CSS, mais simples porém também extensível.
Github para referência futura

.progress {
  width: 150px!important;
  height: 150px!important;
  line-height: 150px;
  background: none;
  margin: 0 auto;
  box-shadow: none;
  position: relative;
}

.progress:after {
  content: "";
  width: 100%;
  height: 100%;
  border-radius: 50%;
  border: 12px solid #fff;
  position: absolute;
  top: 0;
  left: 0;
}

.progress>span {
  width: 50%;
  height: 100%;
  overflow: hidden;
  position: absolute;
  top: 0;
  z-index: 1;
}

.progress .progress-left {
  left: 0;
}

.progress .progress-bar {
  width: 100%;
  height: 100%;
  background: none;
  border-width: 12px;
  border-style: solid;
  position: absolute;
  top: 0;
}

.progress .progress-left .progress-bar {
  left: 100%;
  border-top-right-radius: 80px;
  border-bottom-right-radius: 80px;
  border-left: 0;
  -webkit-transform-origin: center left;
  transform-origin: center left;
}

.progress .progress-right {
  right: 0;
}

.progress .progress-right .progress-bar {
  left: -100%;
  border-top-left-radius: 80px;
  border-bottom-left-radius: 80px;
  border-right: 0;
  -webkit-transform-origin: center right;
  transform-origin: center right;
  animation: loading-1 1.8s linear forwards;
}

.progress .progress-value {
  width: 90%;
  height: 90%;
  border-radius: 50%;
  background: #44484b;
  font-size: 24px;
  color: #fff;
  line-height: 135px;
  text-align: center;
  position: absolute;
  top: 5%;
  left: 5%;
}

.progress.blue .progress-bar {
  border-color: #049dff;
}

.progress.blue .progress-left .progress-bar {
  animation: loading-2 1.5s linear forwards 1.8s;
}

.progress.yellow .progress-bar {
  border-color: #fdba04;
}

.progress.yellow .progress-left .progress-bar {
  animation: loading-3 1s linear forwards 1.8s;
}

.progress.pink .progress-bar {
  border-color: #ed687c;
}

.progress.pink .progress-left .progress-bar {
  animation: loading-4 0.4s linear forwards 1.8s;
}

.progress.green .progress-bar {
  border-color: #1abc9c;
}

.progress.green .progress-left .progress-bar {
  animation: loading-5 1.2s linear forwards 1.8s;
}

@keyframes loading-1 {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(180deg);
    transform: rotate(180deg);
  }
}

@keyframes loading-2 {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(144deg);
    transform: rotate(144deg);
  }
}

@keyframes loading-3 {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(90deg);
    transform: rotate(90deg);
  }
}

@keyframes loading-4 {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(36deg);
    transform: rotate(36deg);
  }
}

@keyframes loading-5 {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(126deg);
    transform: rotate(126deg);
  }
}

@media only screen and (max-width: 990px) {
  .progress {
    margin-bottom: 20px;
  }
}
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" />

90%

75%

Answer: Você pode tentar utilizar o HighCharts, é a biblioteca mais completa atualmente e vastamente personalizável. Eu lembro de ter customizado as coisas dentro de um chart uma vez, mas era em barras, acredito que seja possível com gráficos nesse formato também.
Outra biblioteca bacana e simples é ProgressCircle.js. Com ele acho que você conseguiria fazer essa customização.

var progresso = 0;
var texto = "";

function addProgress() {
  progresso += 0.25;
  if (progresso === 0.25) {
      texto = "1/4";
  } else if (progresso === 0.50) {
      texto = "2/4";
  } else if (progresso === 0.75){
      texto = "3/4";
  } else if (progresso === 1) {
      texto = "4/4";
}
};

var myCanvas = document.getElementById('my_canvas');

var circle = new ProgressCircle({
    canvas: myCanvas,
    minRadius: 30
});

circle.addEntry({
    fillColor: 'rgba(152, 155, 225, 1)',
    progressListener: function() {
        return progresso;
    },
    infoListener: function() {return texto;},
});

circle.start(33);

<canvas id="my_canvas" width="400" height="160"></canvas>

<button onClick="addProgress()">
Add Progresso
</button>
Comment: Vc não acha que isso deveria ser um comentário!?
Comment: Não, resposta é resposta.
Comment: Apenas um link não é resposta de acordo com o site. Mas agora que vc editou virou resposta
Comment: Era esperado ele gerar alguns traços no interior do círculo quando passa do 4/4?
Comment: Sim, era pra ter um limitador, mas ai fica por conta de quem for usar


Is $x^k$ in a polynomial subspace $\mathcal{P}_n$ where $n>k$?

Question: So I'm pretty confused about polynomial subspaces. Say I have a polynomial $ p(x) = x^3 + 2x^2 + 3x + 4 $, whose highest degree is 3, would this be in $\mathcal{P}_4$? I have been reading other answers on this site saying that since the largest degree in $ x^3 + 2x^2 + 3x + 4 $ is 3, it is not in $\mathcal{P}_4$, however, my teacher has told me that any polynomial of a degree smaller than the subspace in question is in fact in that subspace because the coefficient in front of the largest degree could be 0, for example
$ p(x) = x^3 $ is in $\mathcal{P}_5$ because $ p(x) $ could be $ x^3 + 0x^4 + 0x^5 $.
From answers on here, for example, proving that $\mathcal{P}_n$ is not a subspace:
Let $ p(x) = x^3 + x^2 $ and $ q(x) = -x^3 + x^2$, then $ p(x) + q(x) = 2x^2$ which is not of degree 3, therefore it is not $\mathcal{P}_n$ as it is not closed under addition. But couldn't you express $ p(x) + q(x) $ as $ 2x^2 + 0x^3 $?
Could I get some clarification on this? Thanks!
Comment: The answer depends on how **exactly** you define $\mathcal{P}_n$. The $\mathcal{P}_n$ symbol is not standard. So it can be $\mathcal{P}_n=\{f\in k[X]\ |\ \deg f=n\}$. Or maybe $\mathcal{P}_n=\{f\in k[X]\ |\ \deg f\leq n\}$? We can't know that, but you should know that. Once you read the definition it will most likely become clear.
Comment: Hi @sk2000. Yes it is possible for a polynomial with degree less than n be in Pn (lazy notation sorry). And a straightforward reason of why is that possible, is because one basis for Pn is 1,x,x^2,....,x^n. (Yes 1 is a possible vector in the basis of Pn). So as you said, the coefficient in front of a vector can equal zero when taking a linear combination of the vectors in the basis of Pn.
Answer: $\mathcal P_n$ is the space of polynomials with degree $\leq n$. Otherwise it would not be a vector space. The reason is that you can take a polynomial $f=X^n+a_{n-1}X^{n-1}+\dots+a_0$ and subtract the polynomial $X^n$ to get
$$a_{n-1}X^{n-1}+\dots+a_0=f-X^n,$$
which has to be in $\mathcal P_n$ for it to be a vector space. You can construct polynomials of lower degree in a similar way to find that a vector space containing all polynomials of degree $n$ must also contain all polynomials of lower degree than $n$. Also keep in mind that while you can express a polynomial as $2X^2$ or as $0X^3+2X^2$, taking that to mean that the degree depends on how we write it down really defeats the purpose of defining a degree. The degree of a polynomial is the highest exponent of $X$ with non-zero coefficient.
Of course, you could define $\mathcal P_n$ differently if you're not interested in it being a vector space, but I've only seen this notation for vector spaces of polynomials.
Comment: Yes, you could, if there are no other restrictions.
Comment: Your point about $ \mathcal{P}_n $ being the space of polynomials with degree $  \leq n $ cleared things up! So if, for example, I was to find a polynomial $ p(x) $ in $ \mathcal{P}_5 $ such that $ p(2) = 2$, could I just say $ p(x) = x $?
Answer: $\mathcal{P}_{n}$ is vector space of dimension $(n+1)$ over any field $\mathbb{F}$ with the basis $\{1,x,x^2,\cdot\cdot\cdot,x^n\}$.
That means, any polynomial $a_{n}x^{n}+a_{n-1}x^{n-1}+\cdot\cdot\cdot+a_0$ over the field $\mathbb{F}$ are the elements of the vector space $\mathcal{P}_{n}$.
So, any polynomial of degree $\le n $ over $\mathbb{F}$  belong into $\mathcal{P}_{n}$.


How to dpm() the Drupal.settings.basePath var

Question: For debugging purposes I need to use dpm to output the value of Drupal.settings.basePath. I tried this (but not working):
dpm(Drupal.settings.basePath); // not working

Answer: Drupal.settings.basePath is a javascript variable, not PHP...you can't access it on the server side like that.
I imagine the output you're getting in the message area is 'DrupalsettingsbasePath', which is how PHP would interpret Drupal.settings.basePath, along with a few PHP Notices complaining about the use of an undefined constant.
Assuming you're using a browser that supports console.log, to debug the base path just add the following in a javascript file that's included in your page:
console.log(Drupal.settings.basePath);

The variable will then be printed to your browser's console area.
Answer: Drupal.settings.basePath is a value available from JavaScript, as Clive said, while dpm() is a PHP function. If you look at drupal_add_js(), you will notice that value is set using the following code.
  $javascript = array(
    'settings' => array(
      'data' => array(
        array('basePath' => base_path()),
        array('pathPrefix' => empty($prefix) ? '' : $prefix),
      ),
      'type' => 'setting',
      'scope' => 'header',
      'group' => JS_LIBRARY,
      'every_page' => TRUE,
      'weight' => 0,
    ),
    'misc/drupal.js' => array(
      'data' => 'misc/drupal.js',
      'type' => 'file',
      'scope' => 'header',
      'group' => JS_LIBRARY,
      'every_page' => TRUE,
      'weight' => -1,
      'preprocess' => TRUE,
      'cache' => TRUE,
      'defer' => FALSE,
    ),
  );

If you want to get in PHP the value assigned to Drupal.settings.basePath in JavaScript, you just use dpm(base_path()). Clive's answer already tells you how to print the JavaScript value from JavaScript.