text:
Q: Coding standard for clarity: comment every line of code? I've worked in shops that produce life critical software and I've dealt with commenting rules that were meant to keep the code readable and potentially save lives.  In my experience though the requirement becomes a brain dead chore to be ticked off of a checklist and doesn't help me stay focused on writing understandable code.  It also distracts my peer reviewer from having a more meaningful conversation with me about how to make the code easier to understand.
I've also graded student code that had no comments and seen why they should be marked down for neglecting them.
I understand that using good names, keeping structures simple, functions short, and modules focused will keep the code understandable enough that comments can be minimized.
I also understand that comments should explain why the code does what it does, not how.
Given all this is it even possible to write good coding standards that capture this idea? Ones that will be relevant in a peer review but won't turn into a mindless checklist activity that produces notes no more helpful than: "You forgot to comment on line 42".
An example of the kind of code this rule might require when treated as a line in a checklist:
/* Display an error message */
function display_error_message( $error_message )
{
    /* Display the error message */
    echo $error_message;

    /* Exit the application */
    exit();
}

/* -------------------------------------------------------------------- */

/* Check if the configuration file does not exist, then display an error */
/* message */
if ( !file_exists( 'C:/xampp/htdocs/essentials/configuration.ini' ) ) {
    /* Display an error message */
    display_error_message( 'Error: Configuration file not found. Application has stopped');
}

If it is possible to express this properly in a standards document, and it might simply not be, I'd like to capture an idea along these lines:
Consider a comment for every line, sequence, statement, section, structure, function, method, class, package, component, ... of code. Next consider renaming and simplifying to eliminate any need for that comment so you can delete it. Check in while comments are rare. Repeat until deadline. Then repeat some more

A: Comment every line of code? No.
The purpose of the others rules you talk about is precisely to avoid that.
Comments to a readable code are at best redundant, and at worst will throw a reader off looking for the non-existent purpose of the comment.
If you comment whole code which is self-explanatory, you double the amount of reading with out giving any additional information. I am not sure if such redundancy would pay off. One can imagine a reviewer saying that 42 says "display_error" while the comment says "displays warning". But imagine a change in the code. You have two places to correct now. It becomes clear this style has copy-paste negatives.
I would say that optimally the code should not need any comments, other than documentation.
There are styles which go total opposite, if you have doubts about line it's either:

*

*The code is too complicated and should be refactored into a function with a name with a semantic meaning for the portion of code. Be it a complex if or a portion of an algorithm. (Or a clever LINQ one-liner)

*If it cannot be simplified, you don't know enough idioms of language.
(I personally am not a fanatic of strict no-comments rule, but I find it as a good initial mindset to go by.)
Given all this is it even possible to write good coding standards that capture this idea?
As for the process. Our standard gave quite much credit to the reviewer. Assuming they are not malicious this works good.
When he asks "What is variable o?", you rename it. If he asks what does this block do, either refactor or comment. If there was a debate whether something is clear or not, if the reviewer did not get it, then by definition it is not. On very rare occasions there was something like 2nd opinion from few friends.
On average, you should get a code understandable by the average programmer in the team. IMO it keeps off the redundant information, and ensures that the code is understandable by at least one other member of the team, which we found a good optimum.
Also, there were no absolutes. Though we were a small group. It's easy to find consensus in group of 5.

A: The question:

Given all this is it even possible to write good coding standards that capture this idea? Ones that will be relevant in a peer review but won't turn into a mindless checklist activity that produce notes no more helpful than: "You forgot to comment on line 42".

Comments should not seek to educate the reader on the language. A reader should be assumed to know the language better than the writer, but with much less context than the writer.
A reader of this code, from your example, should know that exit() will exit the application - thus making the comment redundant:
/* Exit the application */
exit();

Redundant comments are a violation of DRY, and changes to the code do not necessarily propagate to the comments, leaving comments that do not reflect what the code is actually doing.
However, comments that explain why you're doing something may be valuable - especially if you can't easily communicate the meaning in the code itself.
Python's PEP 8 (the style guide for Python in the CPython standard library) provides the following guideline for inline comments:

Use inline comments sparingly.
An inline comment is a comment on the same line as a statement. Inline
  comments should be separated by at least two spaces from the
  statement. They should start with a # and a single space.
Inline comments are unnecessary and in fact distracting if they state
  the obvious. Don't do this:
x = x + 1                 # Increment x

But sometimes, this is useful:
x = x + 1                 # Compensate for border

Given such an example, I personally prefer to go a step further and would try to eliminate this comment as well. For example, I might arrive at:
border_compensation = 1
compensated_x = x + border_compensation

Making your code self-documenting is not a new idea.
Back to the actual question:

Given all this is it even possible to write good coding standards that capture this idea?

I believe that the PEP 8 guidance and example demonstrates a good coding standard that captures this idea. So yes, I believe it is possible.

A: I think when you see this kind of commenting, and I write this way myself occasionally, It's because the author is writing the spec out in the comments and then going through and implementing each comment.
If we are challenged to write a coding standard which produces code which is understandable in terms of its required functionality rather than its actually functionality (so that errors can be spotted) then are we really talking about how the specifications are defined, documented and linked to the final product?
edit ----
Just to clarify. I'm not getting into comments vs tdd vs unit tests which best. Or suggesting a comment per line is a good/bad
I'm just suggesting a reason you might see the style of commenting talked about in the example.
And from that questioning whether a coding standard about commenting would actualy be better written as a specification document requirement of some kind.
ie comments are for explaining the purpose the code, which is also what a spec is

A:
Given all this is it even possible to write good coding standards that capture this idea? Ones that will be relevant in a peer review but won't turn into a mindless checklist activity that produce notes no more helpful than: "You forgot to comment on line 42".

This obviously goes above and beyond documentation - this touches how the code is structured, which algorithms are chosen, etc.  It may even touch on requirements analysis and design.
My #1 rule is "Don't document the obvious."  The #2 rule is "Write obvious code".
For safety-critical code (which I've never had to work on, thank God), this is  a necessary but nowhere near sufficient first step.  It may even have to come down to mandating what language features must be avoided (I've seen more than one standard mandating "Thou shalt not use scanf( "%s", input ); for any reason").

A: IMHO it should do both. Commenting every line is silly, because you wind up with lines like
  i++;    /* Increment i */

with absolutely no clue as to why you'd want to increment i. Expand on that a bit, and you have the typical Doxygen style of comments, which produce a large amount of verbiage without supplying any idea of what the code is for, or how it works. (At least as far as I have ever seen: I admit that it might be possible to write useful documentation using a system like that, but I'm not holding my breath.)
OTOH, if you write a good comment block at the head of the function (or whatever grouping is logical), describing both what is to be accomplished, and how, if it's less than obvious, you have something that's useful. If you're me, you might even include LaTeX code for relevant equations, or references to papers, e.g. "This implements a WENO scheme for solving Hamilton-Jacobi equations, as discussed in..."

A: The self-documenting code best practice is not a mainstream consensus - while it is widely acceptable that easy-to-understand code is better than cryptic code, not everyone agrees on whether or not complicated code must always be refactored or if it's OK to comment it.
But this debate is about pieces of code that are difficult to understand - and you are talking about commenting each and every line of code. Lines of code that are difficult to understand should be very rare - if most of your lines are complicated like this than you are overusing smart-ass one-liners and you should stop! Sure, a line's role may be a bit hard to understand sometimes, but that's it's role in the context of a bigger piece of code - what the line itself does is almost always straightforward.
So, you should not be commenting lines - you should be commenting pieces of code. Specific comments may be placed near the lines they refer to, but these comments are still referring to the bigger code. They do not describe what/why the line does - they describe what it does in that code and/or why is it needed in that code.
So, it is not lines that should be commented but bigger pieces of code. Should every piece of code be commented? No. Harold Abelson said that "Programs must be written for people to read, and only incidentally for machines to execute". But comments are only for people to read - the machine does not execute them. If your coding standards force writing redundant comments on every line/piece-of-code you are not just burdening the developer who needs to write them - you are also burdening the developers who will have to read them!
This is a problem, because when most of the comments you read are redundant, you stop paying attention to them(because you know they'll just be redundant junk), and then you'll miss out the important comments. So I say - write only the important comment, so that when someone see a comment in the code they'll know it's worth to read it in order to understand the code.

A: I don't think a coding standards document is the place to specify what is already common sense. The purpose of a coding standard is to guarantee consistence (and avoid arguments) about issues where reasonable people might disagree and there is no single obvious right answer, e.g. naming conventions, indentation etc.
Such commenting as in your example is objectively useless and might be due to an inexperienced developer, or a developer used to work with a build system which mechanically checks for the the presence of comments (a really bad idea, but it exists). In both cases the solution is education, possibly through code reviews.
If you start adding all kinds of "best practices" to the coding standard, you will just end up repeating which is already stated in multiple books. Just buy "Clean Code", "Code Complete" and "The Pragmatic Programmer" to the developer in question, and keep your coding standard lean.

A: It is not possible. What you are essentially trying to do is nearly to mechanize good judgment.
When writing critical software such as for life supporting medical systems, huge amounts of checklists and whatnot are virtually inevitable. Not only do even smart people make mistakes, a lot of the software for these devices is written by people that aren't very good at their jobs, so the 'system' has to be able to safeguard against sloppy work, making it safe at the expense of marketability.
Your best option is to leave out the rigorous Coding Standard for commenting and  lead the team by example. Show other's what good comments look like by striving to produce good quality code that is appropriately commented. Instead of trying to find the ultimate way of describing how to write comments (which are themselves more often than not a judgement call) show the others what you mean on a daily basis with your own code reviews. As the other members read your code they'll follow suit if they feel it's useful. And if they can't then no Standard would help them write better comments to begin with.

A: It's time to bring back flow charts! (not really but hang on a minute)
The other day I found my old flowcharting template. I have only used it for homework and jokes (you gotta love a good silly flowchart). But even by this time most commercial programmers that were still using flow charts were generating them automatically from the code (which completely undermines the original purpose of the flowchart, which was to be an aide in writing better code and was quite useful in machine code. However with higher level languages the flowchart changed from being a crutch to a hoble. Why? the abstraction of the flowchart was the same as the code. The comments shown are a hobble in that they are at the same level of abstraction as the code. Good comments are at a different level of abstraction than the code. The easiest way to do this is to use comments for why while the code handles what. Other ways are to breakdown complicated steps to simpler alternates or to have manager level abstracts.

A: Michael Durrant's answer is IMHO not bad, but it is not literally answering the question (as he admitted by himself), so I'll try to give an answer which does:

I also understand that comments should explain why the code does what it does, not how.
Given all this is it even possible to write good coding standards that capture this idea?

Obviously you can write a checklist for your code reviews, containing questions like

*

*"if there is a comment, does it explain why the code does what it does?"

*"is each line of the code - in its context - either self-explanatory enough that it does not need a comment, or if not, is it accompanied by a comment which closes that gap? Or (preferably) can the code be changed so it does not need a comment any more?"

If you like, you can call this a "coding standard" (or not, if you think the term coding standard should be reserved for a list of braindead rules, easy to answer if they are fulfilled or not, how the formatting of the code should look like, or where to declare variables). No one hinders you to have the focus of your checklist on semantical questions, instead of going the easy route and put only formal rules into it.
At the end of the day, you should be sure your team needs such a checklist. To apply such questions you need programmers with some experience as reviewers, and you need to find out if it will really improve the readability of the code in a team of experts. But that is something you have to work out together with your team.

A: Major anti-pattern leading to poor quality code with less clarity
btw readers, the title was originally "comment every line of code?" and you can imagine the instinctive reaction of many of us, myself included.  I later retitled to the longer more accurate title.
At first, reading your question I thought, yuch duplicate stuff in comments , but ok, maybe if you have enough strictures on reviews by multiple people... but then again: people makes mistakes, fail to notice inconsistencies, etc. and over time there will end up being differences.  On reflection I think the problem is much larger:
Developers will tend to write worse code.  They will use more cryptic names and structures because 'its explained in the comment - see!'.
Consider:
living_room_set = tables + chairs.
Now consider:
set = tbls+chrs # Make the set equal to the table plus the chairs
You not only have both more cryptic names and more to read, you also have to look back-and-forth, look at code, what is a set? look left at code, look right at comments, what are tbls, look left at code, look right at comments, what are chrs, look right at comment.  Yuch!
Summary
Develop or enhance a commenting standard if you are forced to in your current position as a developer (As a former COBOL programming I've sure seen big ones!) but spent as much of your time, energy and passion arguing against the commenting anti-pattern using the arguments:

*

*Code and Comments get out of sync with each other when only one is changed

*Comments may describe what one person thinks but may be wrong and thus cover up bugs

*Code becomes harder to read

*Good code becomes harder to write

*Tendency to have use more cryptic names

*Excessive characters to read in code and comments

*Different editors use different styles

*Requires higher English language proficiency than just coding

*Takes time and resources and subtracts from long-term value  *
Plus argue for better code without such comments,-  in fact have a standard(!) - all variable names must be full_english_words - there's one!  So use that 'standards' energy towards the standards of well written code and tests.
One of the two hard problems is naming things - don't side skip the problem with comments.
Given that one of the other problems is premature optimization and that optimization in general can leads to obscure 'why this way' code, this is one area where explanatory comments for apparently poor code may be beneficial although the above caveats still apply.
* tomorrows code

A: Update
My response in quotes for emphasis:

It is my belief the answer that states the comments should not be addressed in Coding Standards and then lists a set of defensive questions to fight it, is the only correct answer.
The issue here is that a Coding Standard is just that, a Standard. Extremely subjective ideas should not be in a Coding Standard. It can be a in a Best Practices guide, but that guide cannot be used against a developer during Code Review. In my personal opinion, a Coding Standard should be as close to Automated as possible. There is so much time wasted in Code Reviews arguing over naming, spacing, tabs, brackets, comments, etc. etc. when ALL of it can be automated. Even the answer about tables and chairs can be automated. LINT'ers allow for dictionaries, Capitalization Checks per concept (Variable, Function, Method, Class, etc.).
Even JavaDoc checking can be implemented by a Robot LINT'er before a Pull Request is accepted. A lot of Open Source projects do this exact thing. You submit your Pull Request, the code is built with a Travis-CI file, including Static Analysis, and it must pass all the Coding Standards which can be objectively expressed. No human chimes in about 'doing it incorrectly' or not 'providing value' with a comment, or the wrong way to name variables, et el. Those discussions provide no value and are best left to a third-party robot which can take the brunt of our emotional coding.
To actually answer the question we would have to address how to write a Standard which addresses how to answer the following question: Did this comment provide value? A Coding Standard can't possibly dictate the 'value' of a comment. Therefor it becomes necessary for a human to go through that checklist. The mere mentioning of comments in a Coding Standard creates a checklist which the Original Poster is wanting to avoid.
That's why comments are usually not processed by the compiler and stripped out. Their value cannot be determined. Is the comment in question valuable; yes or no?. Answering this question is NP-hard. Only humans stand a chance at properly answering it, and even then it can only be answered at the time it's read, by the person who is reading it; where the value of that comment is affected by the weather, his or her home life, the last meeting they just attended and did not end well, the time of day, amount of coffee they've had. I trust the picture is becoming more clear.
How can it ever possibly be expressed properly in any Standard? A Standard isn't useful unless it can be applied consistently and fairly, where fair is more about objectiveness not emotional.

I contest that a Coding Standard should remain as Objective as possible. The way variables are named IS objective. They can easily be checked against a dictionary for proper spelling, grammatical structure, and casing. Anything beyond that is a "pissing match" that is won by the person with the most power or by "brow beating". Something I, personally, struggle with NOT doing.
When I comment, I always comment talking to my future self in the third person. If I come back to this code in 5 years, what would I need to know? What would be helpful, what would be confusing, and what would be out of date with the code? There's a different between documenting code to generate a searchable public API and commenting code which provides value to an unknown third-party, even if that third-party is yourself.
Here is a good litmus test. If you were the ONLY one on the project. You knew you'd be the only one on the project. What would be in your coding standard? You'd want your code to be clean, self explanatory, and understandable to yourself in the future. Would you have a code review with yourself about why you didn't put a comment on every line? Would you review every single comment you created on the 100 files you checked in? If not, then why force others?
Something I believe is missed in these discussions is that the Future You is also a developer on this project. When asking about value, tomorrow's you is also a person that can derive value from the comment. So team size, in my opinion doesn't matter. Team experience doesn't matter, it changes too often.
No amount of comment code reviewing this stop a pace maker from crashing and killing a patient. Once you talk about a comment which affects code, you're now talking about the code not the comment. If all it takes is a missing comment to kill someone, there is something else that smells in the process.

The solution to this type of rigorous way of coding has already been provided as a methodology to writing software itself. And it has nothing to do with comments. The problem with comments is that they have NO impact on the way the product ultimately works. The best comments in the world cannot keep software from crashing when embedded within a pace maker. Or when measuring the electrical signals with a portable EKG.
We have two types of comments:
Machine Readable Comments
Comment styles such as Javadoc, JSDoc, Doxygen, etc. are all ways of commenting the public interface a set of code provides. That interface may only be used by  single other developer (Proprietary code for a two person team), an unknown number of developers (e.g. JMS), or for an entire department. This code can be read by an automated process which then produces a different way of reading those comments, ala HTML, PDF, and such.
This type of comment is easy to create a standard for. It becomes an objective process of ensuring every publically invoke-able method, function, class contains the required comments. Headers, parameters, description et. el. This is to ensure that it's easy for another team to find and use the code.
I'm doing something that looks crazy, but it's really not
These comments are here to help other's see WHY this code was written a certain way. Perhaps there is a numerical error in the processors the code is running on and it always rounds down, yet developers typically deal with code which rounds up. So, we comment to ensure that a developer touching the code understands why the current context is doing something would normally seem unreasonable, but in reality was written that way on purpose.
This type of code is what causes so many problems. It typically goes uncommented and is later found by a new developer and 'fixed.' Thus breaking everything. Even then, the comments are only there to explain the WHY not to actually prevent anything from breaking.
Comments cannot be relied upon
Comments are ultimately useless and cannot be trusted. Comments do not normally change the way programs run. And if they do, then your process is causing more problems then it should. Comments are afterthoughts and can never be anything but. The code is all that matters as that is all that's processed by the computer.
This may sound asinine, but bear with me. Which of these two lines really matters?
// We don't divide by 0 in order to stop crashes.
return 1 / n;
In this example all that matters is that we have no idea what 'n' is, there isn't any check for n being 0 AND even if there was, nothing stops a developer from putting n = 0 AFTER the check for 0. Thus, the comment is useless and nothing automated can ever catch this. No standard can catch this. The comment, while pretty (to some) has no bearing on the outcome of the product.
Test Driven Development
What does have an outcome on the product? Industries in which the code being written can literally save or kill someone has to be rigorously checked. This is done through code reviews, code reviews, testing, testing, code reviews, unit tests, integration tests, trials, staging, months of testing, code reviews, and single person trials, staging, code reviews, testing, and then maybe finally going into production. Comments have nothing to do with any of this.
I would rather code that had NO comments, had a specification, had unit tests which verified the spec, studies of the outcomes of running the code on the production device, then well documented code that had never been tested, nor had anything to compare the code against.
Documentation is nice when you're trying to figure out WHY someone did something a certain way, however, I've found through the years that documentation is typically used to explain why something 'clever' was done, when it really didn't need to be written that way.
Conclusion
If you work at a company which REQUIRES every line be commented I GUARANTEE at least two of the software engineers on the project have already written an auto-document program in Perl, Lisp, or Python which determines the general idea of what the line is doing, then adds a comment above that line. Because this is possible to do, it means the comments are useless. Find the engineers who have written these scripts to automatically document the code and use them as evidence to why the 'Comment on Every Line' is wasting time, providing no value, and potentially hurting.
On an aside, I was helping a close friend with a programming assignment. His teacher had set a requirement that every line had to be documented. So I can see where this thought process would come from. Just ask yourself, what are you trying to do, and is this the right thing? Then ask yourself; Is there any way to 'game' the system with this process? If there is, then is it really adding any value? One cannot automatically write unit tests which tests that code meets a certain specification, and if they possibly could, that wouldn't be a bad thing.
If a device has to work under certain conditions because it'll be inside a human, the only way of ensuring it's not going to kill them is years of testing, peer review, trials, and then NEVER EVER changing the code again. This is why NASA is / was still using such old hardware and software. When it comes to life or death you don't just 'make a little change and check it in.'
Comments have nothing to do with saving lives. Comments are for humans, humans make mistakes, even when writing comments. Don't trust the humans. Ergo, don't trust the comments. Comments are not your solution.

A: There are two different things you allude to when you talk about comments. They're not the same, and the distinction is important.
Documentation tells you about the outward-facing bits of a piece of code - its interface.
Typically tooling will allow you to read them in a 'standalone' fashion, i.e. you're not looking at the underlying code at the same time.
All the interface should be documented (e.g. each method, excluding private methods), and it should describe inputs, outputs, and any other expectations, limitations, etc., especially things which can't be expressed through constraints, tests, etc. (Exactly how much detail and where it goes depends on the project).
Good documentation allows the potential consumer to decide whether, when, and how to use the code.
Comments in source code have a different purpose. They are there for people looking at the source code. They primarily describe the implementation.
Comments are always read in amongst the underlying code.
Comments should explain surprising decisions or complex algorithms, or of options not taken (and reasoning). They are there so future developers can understand the thought processes of their predecessors, and have at hand information which they otherwise might overlook or spend much time seeking, e.g.
# 'map' outperforms 'for' here by a factor of 10

// This line works around an obscure bug in IE10, see issue #12053

-- We are going to recursively find the parents up to and including the root node.
-- We will then calculate the number of steps from leaf node to root node.
-- We first use a WITH clause to get the ID of the root node.

You cannot infer anything from the absence of a comment, and the comment may of course be as wrong as the surrounding code or more so. Judgement must be exercised both on the part of the author and on the part of the reader.
Commenting every line is clearly more work of questionable additional value, which comes with an opportunity cost. If you have a rule that says every line must be commented, you will get that, but at the expense of important parts being commented well.
But it's worse than that: the purpose of a comment is defeated if every line is commented. Comments become noise which make code hard to read: obscuring rather than clarifying. Moreover, indiscriminate commenting makes the truly important comments harder to spot.
Neither comments nor documentation provide any sort of measure or guarantee of the quality of code they describe; they are not a replacement for genuine QA. Their purpose is forward-looking, i.e. in the hope that they will help those who interact with it avoid making mistakes.
In summary, your coding standards can and should require documentation (automated checks help spot undocumented functions/methods, but humans still need to check if the documentation is any good). Comments are a judgement call, and your style guide should acknowledge this. Those who never comment, and those who comment without thinking should expect to be challenged.

A: You can't codify a commenting standard, because you can't know what the important comment will be in advance.
But you still want to make sure the code is commented correctly, since this is life critical code. The solution is to have a standard for the code review - require that code review comments on understandability.
This won't guarantee that it won't turn into a meaningless check list, but it will at least keep it from making the code harder to read. And has the possibility of making it better.
This requires a culture where a code review isn't itself a meaningless gesture, where getting your code sent back as hard to read is a good thing, and not an insult or annoyance. Just as important, one where saying it was unclear, isn't seen as a failure of the reader.
Unreadable code is, to a certain extent, unavoidable. Because the writer is immersed in the context, and will see something as obvious when it's only obvious if you know x, y, or z.
So, you won't be able to have a rule that says give good feedback, but you can spot check the reviews. Even a non-programmer manager could do so -- because the real question isn't was the code written to be readable, but was the code actually readable, which can only be decided by someone who read it.

A: I'll answer the question as stated:

Given all this is it even possible to write good coding standards that capture this idea?

Yes. WYSIWYG. A good coding standard is literally "is is clear to the reader what the following code does and why".
In other words, my code review comments about code readability literally, 1-1, arise out of my mental state of

I, as a reader, (better yet, as a minimal standard, a mental model of a less-experienced but reasonable reader), would not understand the following code's purpose, or method of working

Generally, people are easy to get on board "this needs more readability" when they hear "I, as a senior developer who you hopefully respect as not being dumb, didn't at first read understand this code or why it's there or what it does, so it needs to be explained".
This shifts the discourse from "you didn't follow meaningless standard" to "your code has a specific readability deficiency leading to practical problem".
A second standard that needs to be made explicit is "2am emergency test".

Can your backup, who's not experienced with this code, figure out what the issue is with the code when debugging it during 2am production emergency bridge call, when you're on vacation in Chilean Andes with no cell phone?

This may sound subjective but is actually easy to practically measure: call up a random junior team member who would be expected to be the one debugging at night in production emergency, and ask them to explain how the particular un-commented code works and why it's there.

A: This answer covered most issues, however there is one important thing.

I'd like to capture an idea along the lines of: consider a comment
  for every line, sequence, statement, section, structure, function,
  method, class, package, component, ... of code.

There are tools to generate documentation from code, like for example doxygen. If you use such tools, then it makes sense to comment files, functions, classes, etc. Even if the function's name is self explanatory, I am still doing it for consistency, because people reading the documentation will be be grateful.

A: Many of the existing answers are well detailed, but I felt it important to answer:

...[comments] that will be relevant in a peer review but won't turn into a mindless checklist activity...

To me the only comments that could be a standard can be answered by asking what comments are noticed when they're missing. In other words: comments used by IDEs or documentation software.
That being said, this is subjective to what tools are used by the developers, and not all comments used by such software are as useful as each other.


text:
Q: angular 2 same component in multiple places with different business logic Sorry for the length of the question. I have some design issues.
I have a component which takes roomView array as @Input and displays them in HTML page.
export class RoomView {
"id": string,
"name": string,
"markerIcon": string,
"backgroundColorClass": string
}

room-browser.component.ts
@Component({
    selector: 'room-browser',
    templateUrl: 'room-browser.component.html',
})
export class RoomBrowserComponent {
    @Input() roomsList: RoomView[]: = [];
}

room-browser.component.html

    {{room.name}}

my generic room component provides roomView to room-browser
generic-room.component.ts
@Component({
    selector: 'room',
    templateUrl: 'room.html',
})
export class GenericRoomComponent implements OnInit {

    @Input() source: string;

    private roomView: RoomView[] = [];

    ngOnInit() {
        this.roomView = // i am getting this from backed successfully
        // here I need to decide marker icon and background color class based on some criteria which differs from page to page
        // I have different sections like space, energy, maintenance etc...
        // for space, needs to get space usage for rooms from backend and then decide color
        // for energy, needs to get energy usage and decide the colors
        // for maintenance, needs get devices information of rooms and decide color

    //I want to avoid something like this
    if (this.source === 'space') {
         // get space usage
    } else if (this.source === 'energy') {
         // get space usage
    } else if (this.source === 'maintenance') {
         // get device info and decide color
    }
    }

}

room.html
<room-browser [roomsList]="roomView"></room-browser>

space.html
<room [source]="space"></room>

energy.html
<room [source]="energy"></room>

maintenance.html
<room [source]="maintenance"></room>

I need to decide marker icon and background color class based on some criteria which differs from page to page.
I have different sections like space, energy, maintenance etc... for space, needs to get space usage for rooms from backend and then decide color, for energy needs to get energy usage and decide the color and for maintenance needs get devices information of rooms and decide color
So how and where can I implement this use case specific logic inside a generic component?

A: I'm not sure I completely understand your scenario, but you can add color properties to the GenericRoomComponent for each of these colors and pass them to the child component via additional @Input properties.
OR you can build a service that retains those values and have each of the child components read those values.

A: If you want to use a component across multiple modules, you'll need to create a "shared" module and add that component the shared module's exports. Then you add that shared module into your other modules imports.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make Powershell Extract Metadata script run faster? I have a script that I use to extract metadata from files in a network directory.  It originates here, and I modified it in order to obtain additional metadata (size of file, filehash, date created,and lastwritetime), but these additions appear to slow down the script to the point that it takes weeks to complete when the number of files is more than 10000.
To illustrate the impact of the script additions on the speed, I ran the script on a folder containing five documents:

*

*original script (no get-item or get-file hash lines): 2.9794699 seconds

*with 'get-item' lines (size, filehash, created, lastwritetime):  7.6295035 seconds

*with 'get-filehash' line : 6.9363834 seconds

*with 'get-item' lines and 'get-filehash' lines: 12.4516334 seconds

I tried putting all the get-item lines together in a for-loop thinking that it would be faster to retrieve the file once from the network, then extract the metadata.  While this modified script runs at a much faster 8.6488492 seconds, the metadata fields are not included in the output.
Here's the original script:
#Works on Powershell version 5.1
#The filepath of the folder being printed and the filepath where the output file will be placed need to be specified in the last line of script.
Function Get-FolderItem {

    [cmdletbinding(DefaultParameterSetName='Filter')]
    Param (
        [parameter(Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
        [Alias('FullName')]
        [string[]]$Path = $PWD,
        [parameter(ParameterSetName='Filter')]
        [string[]]$Filter = '*.*',
        [parameter(ParameterSetName='Exclude')]
        [string[]]$ExcludeFile,
        [parameter()]
        [int]$MaxAge,
        [parameter()]
        [int]$MinAge
    )
    Begin {
        $params = New-Object System.Collections.Arraylist
        $params.AddRange(@("/L","/E","/NJH","/NDL","/BYTES","/FP","/NC","/XJ","/R:0","/W:0","T:W"))
        If ($PSBoundParameters['MaxAge']) {
            $params.Add("/MaxAge:$MaxAge") | Out-Null
        }
        If ($PSBoundParameters['MinAge']) {
            $params.Add("/MinAge:$MinAge") | Out-Null
        }
    }
    Process {
        ForEach ($item in $Path) {
            Try {
                $item = (Resolve-Path -LiteralPath $item -ErrorAction Stop).ProviderPath
                If (-Not (Test-Path -LiteralPath $item -Type Container -ErrorAction Stop)) {
                    Write-Warning ("{0} is not a directory and will be skipped" -f $item)
                    Return
                }
                If ($PSBoundParameters['ExcludeFile']) {
                    $Script = "robocopy `"$item`" NULL $Filter $params /XF $($ExcludeFile  -join ',')"
                } Else {
                    $Script = "robocopy `"$item`" NULL $Filter $params"
                }
                Write-Verbose ("Scanning {0}" -f $item)
                Invoke-Expression $Script | ForEach {
                    Try {
                        If ($_.Trim() -match "^(?<Children>\d+)\s+(?<FullName>.*)") {
                           $object = New-Object PSObject -Property @{
                                FullName = $matches.FullName
                                Extension = $matches.fullname -replace '.*\.(.*)','$1'
                                FullPathLength = [int] $matches.FullName.Length
                                Stuff = foreach {$matches in $match}Length = (Get-Item $matches.FullName).length
                                FileHash = Get-FileHash -Path "\\?\$($matches.FullName)" |Select -Expand Hash
                                Created = (Get-Item $matches.FullName).creationtime
                                LastWriteTime = (Get-Item $matches.FullName).LastWriteTime
                                Owner = (Get-ACL $matches.Fullname).Owner
                            }
                            $object.pstypenames.insert(0,'System.IO.RobocopyDirectoryInfo')
                            Write-Output $object
                        } Else {
                            Write-Verbose ("Not matched: {0}" -f $_)
                        }
                    } Catch {
                        Write-Warning ("{0}" -f $_.Exception.Message)
                        Return
                    }
                }
            } Catch {
                Write-Warning ("{0}" -f $_.Exception.Message)
                Return
            }
        }
    }
}

Get-FolderItem "O:\directory\to\files" | Export-Csv -Path C:\output.csv

Does anyone know how to make the script run faster?

A: Rather than (Get-Item $matches.FullName).length you could do ([System.IO.FileInfo]$Matches.FullName).length. I see much better performance from that (Get-Item taking about 3.5x longer). Same for LastWriteTime.


text:
Q: How to set footer in android How to set footer in android on each page
I have used:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
   android:background="@color/mcolor"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:layout_gravity="fill">

<ImageButton android:id="@+id/iconbtn"
           android:layout_height="wrap_content"
           android:src="@drawable/all_icon_138"
           android:layout_marginRight="4px"
           android:layout_gravity="fill"
           android:clickable="true"
            android:layout_width="wrap_content"
            android:background="@color/mcolor"
             android:layout_marginLeft="60px"
             android:layout_marginTop="12px" android:saveEnabled="true">
</ImageButton>
<TextView android:text="@+id/TextView01"
     android:id="@+id/label"
     android:textColor="@color/mbcolor"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:layout_gravity="center"
     android:scrollbars="vertical"
     android:layout_marginBottom="30px"
     android:layout_marginTop="30px"
     android:textSize="12px"
     android:layout_marginRight="30px"
     android:layout_marginLeft="130px"></TextView>
<LinearLayout android:layout_marginTop="50dip"
    android:gravity="bottom"
     android:layout_height="wrap_content"
     android:layout_width="fill_parent"
     android:layout_alignParentBottom="true">
     <ImageButton android:id="@+id/previous"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/newfox_footer_320"
            android:layout_alignParentBottom="true"
             android:layout_alignParentRight="false"
              android:layout_alignParentLeft="false" android:layout_marginLeft="190px" android:layout_marginRight="2px">
            </ImageButton></LinearLayout>
</RelativeLayout>

It is showing 6 images of footer after each TextView.
How do I set it?

A: its is not clear what do you exactly want but i assume you want a footer in a layout.
use a framelayout as you main layout with
width = fillparent
height = fillparent

take another framelayout set the gravity to bottom.
add views to this framelayout.
this is your footer.

A: Make the root view of your xml Layout a RelativeLayout.
Then the view you want as footer, or his parent (the one who is direct child of the root view element: RelativeLayout) needs to have this attribute:
android:layout_alignParentBottom="true"

A: You've used LinearLayout for footer, so you can check out stackoverflow: footer for linear layout in android


text:
Q: Laravel artisan cannot access ENV variables (causing: db connection refused) I'm aware that there are many questions that look like this, but usually they have obvious solutions (stopped mysql server, errors in the .env file and stuff like that). This is different.
My app is working fine in the dev environment.
Instead in production, whenever it tries to use the DB, it produces a 500 error, and it shows an alternance of these two errors in the logs:
[previous exception] [object] (PDOException(code: 2002): SQLSTATE[HY000] [2002] Connection refused at /var/www/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70)

[2022-07-26 15:52:44] local.ERROR: SQLSTATE[HY000] [2002] Connection refused (SQL: select * from `users` where `email` = my@email.com limit 1) {"exception":"[object] (Illuminate\\Database\\QueryException(code: 2002): SQLSTATE[HY000] [2002] Connection refused (SQL: select * from `users` where `email` = my@email.com limit 1) at /var/www/vendor/laravel/framework/src/Illuminate/Database/Connection.php:759)

That seems very odd, since if I docker exec into the container, I can see that all the environmental variables are set correctly, that the mysql client can connect to the db:
mysql -h $DB_HOST -u $DB_USERNAME -p

and that also tinker works, and that I can run artisan command:mycommands without any issues.
What could it be?
I already ran
php artisan config:clear
php artisan route:clear

and also
php artisan config:cache
php artisan route:cache

without any luck.
It might be interesting that here the PDO construct appears to be empty:
[previous exception] [object] (PDOException(code: 2002): SQLSTATE[HY000] [2002] Connection refused at /var/www/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70)
[stacktrace]
#0 /var/www/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php(70): PDO->__construct()

Both my dev and production environments have PDO and pdo_mysql PHP extensions installed.
But I'm not supplying any value for this env variable MYSQL_ATTR_SSL_CA. Should I??
It appears here in the config/database.php file:
'mysql' => [
    'driver' => 'mysql',
    'url' => env('DATABASE_URL'),
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'prefix_indexes' => true,
    'strict' => true,
    'engine' => null,
    'options' => extension_loaded('pdo_mysql') ? array_filter([
        PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
    ]) : [],
],

DATABASE_URL and DB_SOCKET are also null. Is that ok?

UPDATE: answers to the comments:

What is host and port in .env?
That depends on the environment. In production testing I have:

DB_HOST=mariadb (name of the maria db docker service, the same I use for the dev environment)
DB_PORT=3306

While in actual production (Fargate service + serverless RDS), I have:
DB_HOST=url.of.the.rds.resource
DB_PORT=3306

Both environments show the same behavior.

can you restart you appache

This is what happens in production-testing. /var/www is a bind mount of docker composer.
root@abb0b3cf202c:/var/www# service apache2 restart
Restarting Apache httpd web server: apache2AH00112: Warning: DocumentRoot [/var/www/html] does not exist
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.23.0.3. Set the 'ServerName' directive globally to suppress this message
(98)Address already in use: AH00072: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
AH00015: Unable to open logs
Action 'start' failed.
The Apache error log may have more information.
 failed!

and this after fixing the document root path:
root@abb0b3cf202c:/var/www# service apache2 restart
Restarting Apache httpd web server: apache2AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.23.0.3. Set the 'ServerName' directive globally to suppress this message
(98)Address already in use: AH00072: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
AH00015: Unable to open logs
Action 'start' failed.
The Apache error log may have more information.
 failed!

I start the webserver with php artisan serve.

UPDATE
this UI test fails https://ralphjsmit.com/check-laravel-database-connection
(and artisan says that Command "dump-server" is not defined.)

UPDATE
I think it's relevant to list the things that differ between the dev environment, where things work, and the production environment, where they do not:

*

*I'm not copying over the Vendors folder. The Storage folder is also emptied

*I'm rebuilding the Vendors folder with composer install --no-dev --optimize-autoloads and npm install --omit-dev

*When the image is started, I run

php artisan config:clear
php artisan config:cache
php artisan route:clear
php artisan route:cache
php artisan view:clear
php artisan view:cache

UPDATE
I found a clue!
If I run docker exec I can see that PHP can access ENV variables correctly:
root@7f904d0a469a:/var/www# echo $DB_HOST
mariadb

root@7f904d0a469a:/var/www# php -a
Interactive shell

php > var_dump(getenv('DB_HOST'));
string(7) "mariadb"

But if in a laravel blade I put:

DB HOST: <?php var_dump(getenv('DB_HOST'), $_ENV['DB_HOST']); ?>

Then I get
ErrorException
PHP 8.1.8
9.21.6
Undefined array key "DB_HOST"

Therefore the real problem is that Artisan cannot access ENV variables. I'm changing the title.

UPDATE: nevermind. It does read the ENV variables, just not if you use cache. Strange "feature" of Laravel...
So, when not using config:cache, this snippet of code:
Database Connected:
<?php
    try {
        \DB::connection()->getPDO();
        echo \DB::connection()->getDatabaseName();
    } catch (\Exception $e) {
        echo 'None';
    }
?>

DB HOST: <?php var_dump(getenv('DB_HOST'), $_ENV['DB_HOST']); ?>

results in:
Database Connected: None
DB HOST: string(7) "mariadb" string(7) "mariadb"

A: This issue arised from my misunderstanding of the use of the .env file.
I thought that the variables set in the .env file could be overwritten by actual environment variables set in the OS.
I also thought that it was bad practice to use .env files in production.
Therefore, the only variable I had set in my env file was APP_KEY and nothing else, and I was setting everything else in Fargate (or docker compose for testing).
It turns out that instead Laravel requires an .env file, and ignores the actual environment variables.
My testing configuration was half working because it was using cached settings, causing a great deal of confusion for me.
SOLUTION: use the env file in production.


text:
Q: How can I convert colors to grayscale?
I want to change the above colored plot into a grayscale plot. I have tried this:
CCGray[pic_?ImageQ] := Module[{}, ColorConvert[pic, "GrayScale"]];

but it doesn't give me the degree of differentiation I would like.

A: Here's an idea to post-process the grayscale image to increase the differentiation between shades. The image values (excluding pure black and white) are fed to HistogramTransformInterpolation which provides a transform function that approximately flattens the image histogram.
bc = BubbleChart[RandomReal[{-1, 1}, {10, 5, 3}]] ~ColorConvert~ "Grayscale"

ImageApply[HistogramTransformInterpolation @
  DeleteCases[ImageData[bc] ~Flatten~ 1, 1. | 0.], bc]

While this seems to work okay on an uncompressed image, it is not so good with the OP's original image due to the jpeg compression:

Better results can be had by removing near-white values from the image data before computing the histogram transform, but there are still visible artefacts.
ImageApply[HistogramTransformInterpolation@
  Select[ImageData[bc]~Flatten~1, 0 < # < 0.95 &], bc]

A: I assume you've rejected this option:
BubbleChart[RandomReal[{-1, 1}, {10, 5, 3}],
  ColorFunction -> "GrayTones"]

A: First, there is no need to use Module in your sample code above.  You could write simply:
CCGray[pic_?ImageQ] := ColorConvert[pic,"GrayScale"]

Now, if you want to manage the channel mixing manually you can use ImageApply and Dot:
customGray[img_?ImageQ, ker_?VectorQ] := ImageApply[ker.# &, img]

img = Import["http://i.stack.imgur.com/wtlqF.jpg"];

customGray[img, {0.8, 0.5, -0.3}]

You'll notice that my three values add to one; this is typically necessary to preserve white as white.  If you want to make this automatic just divide by the total:
customGray2[img_?ImageQ, ker_?VectorQ] := With[{k = ker/Tr@ker}, ImageApply[k.# &, img]]

Or with normalization control as an Option:
Options[customGray2] = {Normalize -> True};

customGray2[img_?ImageQ, ker_?VectorQ, OptionsPattern[]] :=
  With[{k = If[OptionValue[Normalize], ker/Tr@ker, ker]},
    ImageApply[k.# &, img]
  ]

This makes it easy to Manipulate:
Manipulate[
 customGray2[img, {a, b, c}],
 {a, -5, 5}, {b, -5, 5}, {c, -5, 5}
]


text:
Q: Can a whole program be immutable?

*

*I am familiar with immutability and can design immutable classes, but I have mostly academic knowledge and lacking hands on experience

*Please refer to the linked image above (not allowed to embed yet)

*Looking at it from the bottom up

*Student needs a new address

*Instead of really changing student, we create a new student which incorporates the new address

*The mutator method returns this new object

Question: What do do with this new object, presuming the mutator call came from an immutable object?

*

*The new student can't be saved in Lecture, because Lecture is immutable as well

*So we need a new Lecture as well, which incorporates the new Student

*But where to save the new Lecture?

*In a new Semester, of course, but where does it end?

*The chain can be broken at least, by using the component facade pattern, which handles the creation of all the new objects, without having to forward the call through the whole chain

Question: Where does this stop? Doesn't there have to be a mutable object somewhere to at least save the topmost instance?

A: This is the idea of functional programming. Everything is immutable, no function call is allowed to have side-effects. The only way to mutate complex objects, like in your example, is to re-create the parent objects.
Now the question is how to alter the program state. Therefore, we first think about the stack. It contains the values of all local variables as well as the value of all parameters to the called functions. We can create new values by calling new functions. We can discard values by returning from a function. Thus, we can mutate the program state by calling functions. However, it is not always possible to return from the function to discard its local variables, because we might want to only discard some of the local variables, but need to keep the value of others for further operations. In this case, we simply cannot return, but we need to call another function and pass only some of the local variables to it. Now, to prevent a stack overflow, functional languages have a feature which is called tail call optimization, which is able to remove unnecessary entries from the call stack. An entry of the call stack is unnecessary if the only thing that is left to do for the associated function is to return the value of the function that was called by itself. In this case, there is no point in keeping the call stack entry. By removing the unnecessary call stack entry, the values of the otherwise unused local variables is discarded. You might want to read about it here. Also, tail recursion is related to this.
Again, this is the idea of purely functional programming languages like Haskell. It is really nice that everything is immutable, however these languages have their only issues and their own ways to handle these. For example, Monads (and therefore higher kinded types) are available in these languages, but are rarely seen in imperative/object oriented programming languages.
I like to have immutable values at the leaves of my program memory. However, the code to compose these immutable values, which actually forms the application logic does contain mutable state. For me, this combines the advantages of both worlds. However, this seems to be a matter of preference.

A: With your existing structure this would be quite difficult, and this is probably what you are supposed to learn with this exercise.
I would remove all relationships between the objects from the objects and implement those relationships using Map and Set.
Something like this would be a good starting point.
// Make sure all objects can be uniquely identified.
interface Id {
    public Long getId();
}

class HasId implements Id {
    private final Long id;

    // Normal constructor.
    public HasId(Long id) {
        this.id = id;
    }

    // Copy constructor.
    public HasId(HasId copyFrom) {
        this(copyFrom.id);
    }

    @Override
    public Long getId() {
        return id;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        HasId hasId = (HasId) o;
        return Objects.equals(id, hasId.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}

class Semester extends HasId {
    public Semester(Long id) {
        super(id);
    }

    public Semester(Semester copyFrom) {
        super(copyFrom);
        // TODO: Copy all the other fields of Semester to mine.
    }
    // Do NOT hold a list of Lectures for this semester.
}

class Lecture extends HasId {
    // ...
    // Do NOT hold a list of Students for this lecture.
}

class Student extends HasId {
    // ...
}

// Core structures.
Map<Id, List<Lecture>> semesters = new HashMap<>();
Map<Id, List<Student>> lectures = new HashMap<>();
Set<Id> students = new HashSet<>();
// Utility structures that need to be maintained.
Map<Id, Lecture> studentsInLecture = new HashMap<>();
Map<Id, Semester> lecturesInSemester = new HashMap<>();

In this way you can isolate the objects and keep them immutable but if you do need to change any student's details you can clone the original student and steal it's identity.
This is clearly not a complete solution yet but I hope the concept I am trying to suggest is clear.


text:
Q: Fullcalendar : How to reliably get reference to HTML element for date box on which external element was dropped I would like a way to obtain an HTML element or CSS selector (or a reference to the droppable object itself) for the date on which an external draggable element was dropped.  I tried using the following within the drop() callback to get the node for the date box using the coordinates of the drop event:
var pageX = jsEvent.originalEvent.pageX;
var pageY = jsEvent.originalEvent.pageY;
var domElem = document.elementFromPoint(pageX, pageY);
var node = Y.one(domElem).ancestor('#calendar > .fc-content table.fc-border-separate tr > td', true);

(I'm using the YUI 3 Y.one() and ancestor() methods above to get the node I want, but other methods could be used.)
The above does correctly locate the node of the date box as long as the drop does NOT land on top of an event cell rendered on that date.  If the drop does happen to land on an event cell, however, domElem ends up being the event cell, which is an absolutely positioned element outside of the calendar, and the ancestor() methodology above does not work.
I have also tried getting a reference to the droppable obj by way of the draggable element revert property:
revert: function(droppableObj) {
    if(droppableObj === false) {
        alert('No droppableObj');
        return true;
    }
    else {
        alert(Y.dump({droppableObj: droppableObj}));
        return false;
    }
},

Unfortunately, the above does not work.  Even though the external element does drop correctly, the revert function does not recognize the calendar as droppable.  (For details, see my earlier stackoverflow post at: Fullcalendar: draggable object rejects fullcalendar as droppable even though fullcalendar accepts drop )
The only alternative I can think of is to use the date object in the drop() callback, and with that find the correct fc-dayXX element, but that seems pretty cumbersome.  I have searched on this already, but not found anything so far.  If anyone has a suggestion, please let me know.

A: Here is what I came up with for the fullcalendar drop callback:
function getSelectorForDroppedOnDate(date, allDay, jsEvent, ui) {
    if (! date) return;
    var displayedDate = $('#calendar').fullCalendar('getDate');
    var displayedMonth = displayedDate.getMonth(); // 0 - 11
    var displayedYear = displayedDate.getFullYear();
    var droppedOnYear = date.getFullYear();
    var droppedOnMonth = date.getMonth(); // 0 - 11
    var droppedOnDate = date.getDate(); // 1 - 31
    var droppedOnDayOfWeek = date.getDay(); // 0 - 6 no matter what week of the month

    // Get values related to the last day of the month before the month the event was dropped on
    // so that the grid location of the drop can be determined
    var lastDayOfMonthBeforeDroppedOnMonth = new Date(droppedOnYear, droppedOnMonth, 0); // This is actually correct
    var dateOfLastDayOfMonthBeforeDroppedOnMonth = lastDayOfMonthBeforeDroppedOnMonth.getDate(); // 1 - 31
    var dayOfWeekOfLastDayOfMonthBeforeDroppedOnMonth = lastDayOfMonthBeforeDroppedOnMonth.getDay(); // 0 - 6

    var i;
    var gridLocationOfDrop; // 0 - 41 to cover 42 days of six weeks always shown

    if (droppedOnMonth === displayedMonth) { // dropped on month is same as currently displayed month
        i = 0;
        // adjust droppedOnDayOfWeek by 1 to account for 0-based index
        while ((droppedOnDayOfWeek + 1) + i*7  < droppedOnDate) {
            i++;
        }
        gridLocationOfDrop = droppedOnDayOfWeek + i*7;
    }
    else {
        // if dropped on date is in month previous to currently displayed month (need to compare years since inequality will reverse at year boundary)
        if ((droppedOnMonth < displayedMonth && droppedOnYear === displayedYear) || (droppedOnMonth > displayedMonth && droppedOnYear < displayedYear)) {
            gridLocationOfDrop = droppedOnDayOfWeek;
        }
        // else if dropped on date is in month after currently displayed month (need to compare years since inequality will reverse at year boundary)
        else if ((droppedOnMonth > displayedMonth && droppedOnYear === displayedYear) || (droppedOnMonth < displayedMonth && droppedOnYear > displayedYear)) {
            i = 0;
            // adjust dayOfWeekOfLastDayOfMonthBeforeDroppedOnMonth by 1 to account for 0-based index
            while ((dayOfWeekOfLastDayOfMonthBeforeDroppedOnMonth + 1) + i*7 < dateOfLastDayOfMonthBeforeDroppedOnMonth) {
                i++;
            }
            gridLocationOfDrop = (dayOfWeekOfLastDayOfMonthBeforeDroppedOnMonth + i*7 + droppedOnDate);
        }
    }

    selector = '#calendar > .fc-content table tr > td.fc-day' + gridLocationOfDrop;
    return selector;
}

Works for me!


text:
Q: get already loggedin user information form facebook in android I want to fetch information form facebook i know it can be done by using facebook sdk easily but I have a list using intent chooser and from that popup if user click on facebook and they are already logged in, from there I want to fetch user information, form device I want to fetch information.how to do that?
EDIT
I already get user email id from account manager but i want user name as well how to retrive that?
Edit
         AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
          Account[] list = manager.getAccounts();

    Log.v("tag", "data is "+list);

    String possibleEmail="";

       try{
               possibleEmail += " Gmail Account \n\n";
               Account[] accounts = AccountManager.get(this).getAccountsByType("com.google");

               for (Account account : accounts) {

                 possibleEmail += " - "+account.name+" : "+account.type+" , \n";
                 possibleEmail += " \n\n";

               }
          }
          catch(Exception e)
          {
               Log.i("Exception", "Exception:"+e) ;
          }

          try{
               possibleEmail += "All Accounts \n\n";

               Account[] accounts = AccountManager.get(this).getAccounts();
               for (Account account : accounts) {

                  possibleEmail += " - "+account.name+" : "+account.type+" , \n";
                  possibleEmail += " \n";

               }
          }
          catch(Exception e)
          {
               Log.i("Exception", "Exception:"+e) ;
          }

       // Show on screen
       accountsData.setText(possibleEmail);

       Log.i("Exception", "mails:"+possibleEmail) ;
}

from this code i am able to get user id of all accounts but it is giving only id's i tried for user name but it's not working with that.any one can help me with this?

A: As per my understanding you can achieve those two functionalities by this way.
For twitter you should use twitter4j-core-android2.2.3.jar and here is the code snippet to get the user information
    accessToken = twitterConnection.getOAuthAccessToken
(requestToken,editPinCode.getText().toString());

 oHelper.storeAccessToken(accessToken);

Log.i("Access Token:", accessToken.getToken());

Log.i("Access Secret:", accessToken.getTokenSecret());

long userID = accessToken.getUserId();

User user = twitterConnection.showUser(userID);

 user.getName();

and for gplus integration & implementation just follow this tutorial
http://ankitthakkar90.blogspot.in/2013/05/google-plus-integration-in-android.html
https://developers.google.com/+/mobile/android/people
code snippet is here
Use the Plus.PeopleApi.getCurrentPerson method to request profile information the currently signed in user.
You can call the getCurrentPerson method after the GoogleApiClient is connected:
@Override
public void onConnected() {
 ...
    if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
    Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
    String personName = currentPerson.getDisplayName();
    String personPhoto = currentPerson.getImage();
    String personGooglePlusProfile = currentPerson.getUrl();
  }
  }


text:
Q: Apply CSS to a unique li inside ng-repeat I want to change CSS properties for a specific li inside ng-repeat, the loop:

{{comment.text | limitTo: 100 }}

           =10"> {{moreLessText}}

the ng-click="changeEm('cmmnt'+$index)" need to change the height(style.maxHeight) of the liby ID.
here is the function:
$scope.changeEm = function(liElement){ document.getElementById("'liElement'").style.maxHeight ="1em;!important";}

In the console.log() for 'liElement' is just a string and I cant find it by document.getElementById("'liElement'")
Thanks.

A: You are using a string as variable instead of the variable you pass into the function. I wouldn't recommend this approach, but you can fix it by changing this:
document.getElementById("'liElement'")

to this:
document.getElementById(liElement)

The approach I would recommend is to use ng-class instead:

{{comment.text | limitTo: 100 }}

        =10"> {{moreLessText}}

and in your changeEm function:
$scope.changeEm = function(comment) {
    comment.clicked = true;
}

Then you can use the 'active' class in your css:
/* the 'p' in non-clicked 'li' */
li p.commentText {
    max-height: 10px;
}
/* the 'p' in a clicked 'li' */
li.active p.commentText {
    max-height: auto;
}

A: The answer was very simple, I just add ng-class:

{{comment.text}}

and the function :
$scope.changeEm = function(comment){
                    console.log(comment);
                    comment.active = true;
                }

finally the match CSS:
.visable {
    height: 6.5em !important;
    overflow: visible!important;
}
.notVisable{
    overflow: hidden!important;
}

Hopes that helps someone!


text:
Q: Spring MVC map xDomainRequest You can only use GET and POST for xDomainRequests. Is there a way I can create a mapping that can also take an optional param to determine which webmethod to use? For example I have:
@RequestMapping(method = RequestMethod.PUT)
@ResponseBody
public SomeObject someUpdateFunction(@RequestBody SomeObject objectToUpdate)
{
    ...
}

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public SomeObject someCreateFunction(@RequestBody SomeObject objectToUpdate)
{
    ...
}

Is there a way that I can somehow map an XDR to the PUT method? I obviously don't want to add the POST option to someUpdateFunction().

A: The O'Reilly book "RESTful Web Services" describes a convention where the intended method is included in a "_method" parameter, either via the query string or the request body.  This is particularly useful when you are dealing with cross-domain ajax requests in IE9 and older, where only GET and POST are allowed.  In that case, you would include a _method param with a value of "PUT".
So, if you follow the convention I just described, perhaps you could do something like this:
private SomeObject processPut(objectToUpdate)
{
    ...
}

@RequestMapping(method = RequestMethod.PUT)
@ResponseBody
public SomeObject someUpdateFunction(@RequestBody SomeObject objectToUpdate)
{
    return processPut(objectToUpdate);
}

@RequestMapping(method = RequestMethod.POST, params = "_method=PUT")
@ResponseBody
public SomeObject someUpdateFunction(@RequestBody SomeObject objectToUpdate)
{
    return processPut(objectToUpdate);
}

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public SomeObject someCreateFunction(@RequestBody SomeObject objectToUpdate)
{
    ...
}

Perhaps there is a better way to do this in Spring, as I have very little experience with this framework, but the concept should hold up.


text:
Q: Selenium : xpath following-sibling where siblings have more children I hope I describe my problem/question in a comprehensible way.
I have and html that looks like this:

  AAAA

  <textarea class="class-textarea">
  </textarea>

  BBBB

  <textarea class="class-textarea">
  </textarea>

I want the Xpath for the TextArea where the value of the Label is AAAA to populate it with a value in Selenium.
So somelike like this...
wait.Until(ExpectedConditions.ElementIsVisible(
    By.XPath("//div[@class='class-div']/label[@class='class-label'][span[@class='class-span' and text()='AAAA']]/following-sibling::div[@class='class-div-a']/textarea[@class='class-textarea']"))).SendKeys(valueTextArea);

A: Problem could be in this waiter condition, ExpectedConditions.ElementIsVisible
The thing is that your <textarea> is not 'visible' in selenium context, visibility means that element is present in DOM (which is true) and it's size is greater then 0px which could be false for your <textarea> element. In java you would use ExpectedConditions.presenceOfElement() instead of ExpectedConditions.visibilityOfElement(), not sure how it goes in C# but you get the picture.
Try and see if it solves your problem.

A: Let me quickly rephrase the question to make sure I understand, you need an xpath to find the textbox associated with the label where the text is AAAA.
You'll have to go back up the tree in this case, here are a couple of ways I might do that, although your xpath looks correct:
Using ancestor to be clear about which element you're moving up to (better IMO)
By.XPath("//label/span[text()='AAAA']/ancestor::div[@class='class-div']//textarea");

Or just moving back up the tree with ..
By.XPath("//label/span[text()='AAAA']/../../..//textarea");

If your xpath exists, use asikojevics answer. The C# method is ExpectedConditions.ElementExists(By)
****UPDATE****
Based on your comment of a trailing space after the text value, here is another xpath that should find the textarea in that case, using contains instead of text()=.
By.XPath("//label/span[contains(text(),'AAAA')]/ancestor::div[@class='class-div']//textarea");


text:
Q: Vuetify vflex align-self-end doesnot work I am working on vuetifyjs and currently stuck while trying to achieve this(below) in a vuetify way.
,
Please correct me if i am wrong, align-self-end must align v-flex to the end of the v-layout?
This is what I have tried.
Any suggestions would be helpful
https://jsfiddle.net/fierce_trailblazer/bp3f1wct/5/

A: It is at the end of v-layout, but v-layout is only as big as it needs to be because you didn't set a height attribute on it nor v-container.
Also, because v-flex items have a flex-grow property of 1, they will fill all the remaining space, meaning that there is no empty space left to 'align' the separate items.
Finally, you're working with Vuetify 0.16.6 (in your fiddle), which doesn't have the align-self-xxxxx props according to the v1 Vuetify docs.

What you can do in your situation, is use the flex-grow: 1 property of the first v-flex item, and replace the thing you want at the bottom with a normal div (which has flex:grow: 0) so it's automatically pushed to the bottom.
Alternatively: get rid of the v-flex altogether, because you're not using the column as a grid, so you don't need the subdivisions. Then use justify-space-between on the column layout.

  <v-container fluid style="height: 400px;">
    <v-layout class="fill-height layout" column>
      <v-flex shrink class="topitem">
        <v-layout class="layout" row>
          <v-flex xs12>
            <v-btn primary dark>Normal vflex 1</v-btn>
          </v-flex>
          <v-flex xs12>
            <v-btn primary dark>Normal vflex 2</v-btn>
          </v-flex>
        </v-layout>
      </v-flex>

        <v-btn primary dark>Should be fixed to bottom</v-btn>

    </v-layout>
  </v-container>

Here's a working fiddle that achieves what you want: https://jsfiddle.net/q69wuk28/13/
Here's an article about flexbox, which is used by vuetify's v-layout/v-flex components: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

A:

 <v-container fluid pa-0 ma-0 style="backgroundColor:yellow">
    <v-layout class='page' pa-0 ma-0 style="backgroundColor:red;height:100vh" column >
      <v-flex xs12 pa-0 ma-0>
        <v-layout pa-0 ma-0 row>
             <v-flex xs12 pa-0 ma-0><v-btn primary dark>Normal vflex 1</v-btn></v-flex>
             <v-flex xs12 pa-0 ma-0 ><v-btn primary dark>Normal vflex 2</v-btn></v-flex>
        </v-layout>
      </v-flex>
      <v-flex xs12 pa-0 ma-0 style="display:flex">
            <v-btn style="align-self:flex-end" primary dark>Should be fixed to bottom</v-btn></v-flex>
    </v-layout>
   </v-container>

Your problems:

*

*container was not on a full page

*Vuetify deprecate v-flex block, now you can add to classes '.d-flex', position too writing in a class like "justify-space-between"


text:
Q: How to simulate click in span using Mechanize Ruby? I have a webpage with list of pages:

  1
  2
  3
  4
  5
  6
  7
  8
  9
  10
  11

How can I click on the span using mechanize?

A: According to this ASCIIcasts you can perform searches and findings:

There are two methods on the page object that we can use to extract
  elements from a page using Nokogiri. The first of these is called at
  and will return a single element that matches a selector.
agent.page.at(".edit_item")

The second method is search. This is similar, but returns an array of
  all of the elements that match.
agent.page.search(".edit_item")

http://asciicasts.com/episodes/191-mechanize
So doing something like:
agent.page.at(".page")

Will return the array of spans. And then you will be able to work with them and just do the #click action.
EDITED:
As long as the span is a non interactive element, and click is a Link action, you will have to find a workaround:
How to click link in Mechanize and Nokogiri?


text:
Q: FreeBSD: Samba performance over GBit-Ethernet I'm using a FreeBSD NAS with RAID-Z.
I can read ~300MB/s from the ZFS disks to /dev/null on the box, but only get about 50MB/s over GBit-Ethernet with SMB to Windows 7 (Samba 3.5.6). Both systems have Intel-PCIe-NICs and are connected directly.
Samba is configured to use AIO and I already tried to tune TCP/IP:
kern.ipc.maxsockbuf=16777216
net.inet.tcp.sendspace=1048576
net.inet.tcp.recvspace=1048576
net.inet.tcp.sendbuf_max=8388608
net.inet.tcp.recvbuf_max=8388608
net.inet.tcp.delayed_ack=0

Any ideas what's causing the bottleneck? I think the link should handle 100 MB/s easily.

A: Okay, there actually were two problems:

*

*Jumbo frames weren't so irrelevant after all. That gave me a huge performance boost.

*My SSD disk can easily write 100 MB/s, but I recently turned on NTFS compression which created problems (second long stalls while writing). A TRIM optimization resolved that.

A: To test the cable and bandwidth of your drivers, you should take out hard disk (and anti-virus for the windows box) write limits.
So you can either:

*

*create a RAM disk on the windows box, download/push files onto it

*create and redirect a samba share to /dev/null and push files into it from the windows box

*run a cross-platform bandwidth utility (probably part of the Intel NIC utilities on the windows platform).
If anyone knows of a cross-platform windows-unix benchmark tool, please let me/us know :-)
And yes, you will need to make sure you have matching jumbo frames (2048 Bytes seems to be the 'norm') on your nics and switch. The standard TCP/IP packet size is a bit small for Gigabit streams.


text:
Q: Little to big endian buffer at once python I've created a buffer of words represented in little endian(Assuming each word is 2 bytes):
A000B000FF0A

I've separated the buffer to 3 words(2 bytes each)
A000
B000
FF0A

and after that converted to big endian representation:
00A0
00B0
0AFF

Is there a way instead of split into words to represent the buffer in big endian at once?
Code:
buffer='A000B000FF0A'
for i in range(0, len(buffer), 4):
    value = endian(int(buffer[i:i + 4], 16))

def endian(num):
    p = '{{:0{}X}}'.format(4)
    hex = p.format(num)
    bin = bytearray.fromhex(hex).reverse()
    l = ''.join(format(x, '02x') for x in bin)
    return int(l, 16)

A: Using the struct or array libraries are probably the easiest ways to do this.
Converting the hex string to bytes first is needed.
Here is an example of how it could be done:
from array import array
import struct

hex_str = 'A000B000FF0A'
raw_data = bytes.fromhex(hex_str)
print("orig string:      ", hex_str.casefold())
# With array lib
arr = array('h')
arr.frombytes(raw_data)
# arr = array('h', [160, 176, 2815])
arr.byteswap()
array_str = arr.tobytes().hex()
print(f"Swap using array: ", array_str)

# With struct lib
arr2 = [x[0] for x in struct.iter_unpack('<h', raw_data)]
# arr2 = [160, 176, 2815]
struct_str = struct.pack(f'>{len(arr2) * "h"}', *arr2).hex()
print("Swap using struct:", struct_str)

Gives transcript:
orig string:       a000b000ff0a
Swap using array:  00a000b00aff
Swap using struct: 00a000b00aff

A: You can use the struct to interpret your bytes as big or little endian. Then you can use the hex() method of the bytearray object to have a nice string representation.
Docs for struct.
import struct

# little endian
a = struct.pack("<HHH",0xA000,0xB000,0xFF0A)

# bih endian
b = struct.pack(">HHH",0xA000,0xB000,0xFF0A)

print(a)
print(b)

# convert back to string
print( a.hex()  )
print( b.hex() )

Which gives:
b'\x00\xa0\x00\xb0\n\xff'
b'\xa0\x00\xb0\x00\xff\n'
00a000b00aff
a000b000ff0a


text:
Q: TikZ scalebox without translation Below are two TikZ pictures. In the second one, I've added a \scalebox to scale the nodes ABC and the distance between them. I want the A to remain in the same position, but unfortunately the coordinates are scaled with respect to origin.
How can I rescale that part of the figure without translating it?

MWE for the picture with a scalebox:
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}

\node at (0,0) {0,0};
\node at (4,4) {4,4};
\node at (0,4) {0,4};
\node at (4,0) {4,0};

\scalebox{0.67}{
    \node at (2,2) (A) {A};
    \node [right=of A] {B};
    \node [below=of A] {C};
}
\end{tikzpicture}
\end{document}

To be clear: I do want the distances between A, B and C to scale, I just don't want the entire scalebox to move towards origin. In my actual document, the contents of the scalebox are more complicated.

A: Use a scope with options scale=0.67 and transform shape instead of the \scalebox. All numeric coordinates inside the scope will be scaled. But you can use an outside the scope defined named coordinate as "anchor" to position the node A.
\documentclass[tikz,margin=5mm]{standalone}
\usetikzlibrary{positioning}

\begin{document}
\begin{tikzpicture}
\draw[help lines](0,0)grid(4,4);
\node at (0,0) {0,0};
\node at (4,4) {4,4};
\node at (0,4) {0,4};
\node at (4,0) {4,0};
\coordinate (O) at (2,2);% coordinate for positioning node A
\begin{scope}[scale=0.67,transform shape]
    \node at (O) (A) {A};
    \node [right=of A] {B};
    \node [below=of A] {C};
\end{scope}
\end{tikzpicture}
\end{document}


text:
Q: how to convert pc serial number to string First of all I'd like to know if I can use these two instructions
gwmi win32_bios | select serialnumber

gwmi win32_Computersystemproduct | select identifyingnumber

indifferently.
The second question is why if I write
$sn = gwmi win32_bios | select serialnumber | out-string

$sn.gettype() returns me system.object
and
$sn.length returns me 561 even though my serial number is made of 22 chars. Thanks.

A: Looks like those two wmi properties give the same result on my machine.  I'm guessing that they pull from the same place.
In terms of the results of GetType, I get this:
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

Which means that $sn is a String, which is derived from System.Object.
Oh yeah...the last part.  $sn is not just the serial number.  It's The headers, the formatting, the spaces, and all of the properties of the result of the GetType() function.

A: By using Out-String, you are converting the output of gwmi win32_bios | select serialnumber to a string and storing it in $sn. So, $sn will now have the following content:
PS> $sn

serialnumber
------------
xxxxxxx

So, $sn.length is showing you the length of this entire string. If you want to change it only to the serial number:
PS> $sn = gwmi win32_bios | select -Expand serialnumber | out-string
PS> $sn
xxxxxxx
PS> $sn.Length
9

As you can see, my serial number (I removed the original) is only 7 characters wide. But, $sn.length shows 9. There are probably a couple hidden chars after the output. I can see a blank line after the output at the console.
Coming to the real point, this space is added by Out-String. So, you don't even need that. you can do:
PS> $sn = gwmi win32_bios | select -Expand serialnumber
PS> $sn
XXXXXX
PS> $sn.Length
7

$sn is still a string.
PS> $sn.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

A: if you do a get-member on the the output of gwmi win32_bios | select serialnumber you'll see that it in fact has the following properties, like any object in .NET.
typeName: Selected.System.Management.ManagementObject

Name         MemberType   Definition
----         ----------   ----------
Equals       Method       bool Equals(System.Object obj)
GetHashCode  Method       int GetHashCode()
GetType      Method       type GetType()
ToString     Method       string ToString()
serialnumber NoteProperty System.String serialnumber=N1B85 T10 55757

If you want the serial number, you need to do the following:
$sn = gwmi win32_bios | select serialnumber
$sn.serialnumber

That way you're selecting the contents of the serialnumber property of the serialnumber object.

A: Or you can just do this:
$sn = (gwmi win32_bios).serialnumber


text:
Q: How to compact variable in laravel without knowing if they are defined I am new to laravel and I have problem. I defined bunch of unique variables and I have no idea which of them are defined. How can i compact variables if I don`t know  if are they defined?

A: I would recommend store all the variables values in array.
For example lets say you have a $title, $content and $author you have to pass from the controller to the view, you can do something like
$data = [
'title' => 'Some title',
'content' => 'Hello blah blah...',
'author' => 'Someone'
];

And then in the view file, you can output using data_get('title',$data). data_get() is a laravel helper function that you can retrieve data from array and if the key doesn't exist, you will get null instead of throwing undefined index error message.


text:
Q: Read value from Combobox in winform application I am building a Windows forms application using VS2010. I want to read the value the user selected from the dropdown ComboBox and generate patientNo based on that. But when i run the application I get a NullReferenceException.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
    string patientNumber;

    string gender = comboBox2.SelectedValue.ToString();
    if (gender != null)
    {
        if (gender == "Female")
        {
            var generator = new PatientNumberGenerator();
            patientNumber = generator.GeneratePatientNumber(Gender.Female);
            const string message = "patientNumber";

            const string caption = "Testing PatientNumber class";
            var result = MessageBox.Show(message, caption,
                                         MessageBoxButtons.YesNo,
                                         MessageBoxIcon.Question);

        }
        else if (gender == "Male")
        {
            var generator = new PatientNumberGenerator();
            patientNumber = generator.GeneratePatientNumber(Gender.Male);
            const string message = "patientNumber";

            const string caption = "Testing PatientNumber class";
            var result = MessageBox.Show(message, caption,
                                         MessageBoxButtons.YesNo,
                                         MessageBoxIcon.Question);
        }
   }

}

A: You haven't said which line the exception is occuring on, so it's a bit of a shot in the dark. However:
string gender = comboBox2.SelectedValue.ToString();

comboBox2.SelectedValue might be null, in which case trying to call ToString() on it would cause a NullReferenceException. Try:
if (comboBox2.SelectedValue == null)
{
    return;
}
string gender = comboBox2.SelectedValue.ToString();
//[etc…]

If that's not your issue, the exception may be inside other calls in that method, such as GeneratePatientNumber.

A: If somewhere in your code you are setting comboBox2.DataSource property to some datasource, then .SelectedValue will retrieve a value.  If you are not setting the .DataSource property, then SelectedValue will return null.
I assume that since you keep getting null values you are not setting a datasource but instead setting your Items in the VS Designer. If that's the case, you should instead be using:
comboBox2.SelectedItem.ToString()

to retrieve the SelectedItem in your list.

A: Don't use combobox1.SelectedValue in case use:
string selected = combobox1.SelectedItem.ToString();

It worked for me.

A: The only place I can see you would get a NullReferenceException other than in GeneratePatientNumber is
comboBox2.SelectedValue.ToString();

If nothing is selected .SelectedValue will be null therefore cannot have ToString() called on it.

A: I know this is over a year old but I was working on a similar project with the exact same error. What fixed it for me was using
comboBox2.SelectedText.ToString();

or
comboBox2.SelectedItem.ToString();


text:
Q: Facebook Swift (facebook-sdk-swift) error after adding pod I did try the new released Facebook SDK for Swift Github, added but after

pod 'FacebookCore'

But after

pod install

I get a error, see attached image

Are there more steps needed?

A: Facebook SDK in Swift is still in Beta. You should wait until it is out of beta.
This is a post from facebook:
Since Swift is still under active development, the Facebook SDK for Swift Beta supports Swift 2.2.1 and 2.3, which gives you the ability to submit apps to the Apple App Store today. Later this year we will update the Facebook SDK for Swift when Swift 3 reaches GM.


text:
Q: Regex use in Laravel This is my Laravel code:
$validator = \Validator::make($val, [
                    'service_activity' => 'required|max:1000',
                    'inspired' => 'required',
                    'obstacles' => 'required|max:1000',
                    'working_on_acitivity' =>  array('required', 'regex:^(1[0-2]|0[1-9]|\d)\/(20\d{2}|19\d{2}|0(?!0)\d|[1-9]\d)$'),
                    'spend_time' => 'required',
                    'activity_impact' => 'required|max:1000',
                    'fund_raising' => 'required',
                    'raised_amount' => 'required|numeric',
                    'people_involved' => 'required|numeric',
                    'learned_from_experience' => 'required|max:1000',
                ],$messages);

I want to use the regex for the field in working_on_acitivity but always getting the same error. I have used the regex in an array as given in the Laravel documentation:

type":"ErrorException","message":"preg_match(): No ending delimiter '^' found

A: Change
'regex:^(1[0-2]|0[1-9]|\d)\/(20\d{2}|19\d{2}|0(?!0)\d|[1-9]\d)$'

to
'regex:#^(1[0-2]|0[1-9]|\d)\/(20\d{2}|19\d{2}|0(?!0)\d|[1-9]\d)$#'

using # as delimiter.
(This is based on your error message talking about missing delimiters.)


text:
Q: nutch parsing zip files I am using nutch 1.15 to crawl the link that contains the zip files which comprises of file1.txt, file2.txt and file3.txt.
I used the parse-zip, parse-tika plugin in nutch "plugin.includes" but it is not able to crawl the content of the text files and index it.
Parsed content returns like this,
"content" : "file1.txt\nfile2.txt\nfile3.txt\n"

Why it is not able to get the contents of file1.txt, etc?
removed zip from regex-urlfilter.txt,
#-(?i)\.(gif|jpg|png|ico|css|sit|eps|wmf|zip|ppt|mpg|xls|gz|rpm|tgz|mov|exe|jpeg|bmp|js)$
-(?i)\.(gif|jpg|png|ico|css|sit|eps|wmf|ppt|mpg|xls|gz|rpm|tgz|mov|exe|jpeg|bmp|js)$

plugin.includes in nutch-site.xml:
<property>
    <name>plugin.includes</name>
    <value>protocol-http|protocol-httpclient|urlfilter-regex|parse-(html|text|tika|zip|metatags)|index-(basic|anchor|metadata)|query-(basic|site|url)|response-(json|xml)|summary-basic|scoring-opic|urlnormalizer-(pass|regex|basic)|indexer-elastic</value>
</property>
<property>
    <name>http.content.limit</name>
    <value>-1</value>
</property>

Parse-plugins.xml file:
<parse-plugins>

  <!--  by default if the mimeType is set to *, or
        if it can't be determined, use parse-tika -->
    <mimeType name="*">
      <plugin id="parse-tika" />
    </mimeType>

    <mimeType name="application/rss+xml">
        <plugin id="parse-tika" />
        <plugin id="feed" />
    </mimeType>

    <mimeType name="application/x-bzip2">
        <!--  try and parse it with the zip parser -->
        <plugin id="parse-zip" />
    </mimeType>

    <mimeType name="application/x-gzip">
        <!--  try and parse it with the zip parser -->
        <plugin id="parse-zip" />
    </mimeType>

    <mimeType name="application/x-javascript">
        <plugin id="parse-js" />
    </mimeType>

    <mimeType name="application/x-shockwave-flash">
      <plugin id="parse-swf" />
    </mimeType>

    <mimeType name="application/zip">
        <plugin id="parse-zip" />
    </mimeType>

    <mimeType name="text/html">
        <plugin id="parse-html" />
    </mimeType>

        <mimeType name="application/xhtml+xml">
        <plugin id="parse-html" />
    </mimeType>

    <mimeType name="text/xml">
        <plugin id="parse-tika" />
        <plugin id="feed" />
    </mimeType>

       <!-- Types for parse-ext plugin: required for unit tests to pass. -->

    <mimeType name="application/vnd.nutch.example.cat">
        <plugin id="parse-ext" />
    </mimeType>

    <mimeType name="application/vnd.nutch.example.md5sum">
        <plugin id="parse-ext" />
    </mimeType>

    <!--  alias mappings for parse-xxx names to the actual extension implementation
    ids described in each plugin's plugin.xml file -->
    <aliases>
        <alias name="parse-tika"
            extension-id="org.apache.nutch.parse.tika.TikaParser" />
        <alias name="parse-ext" extension-id="ExtParser" />
        <alias name="parse-html"
            extension-id="org.apache.nutch.parse.html.HtmlParser" />
        <alias name="parse-js" extension-id="JSParser" />
        <alias name="feed"
            extension-id="org.apache.nutch.parse.feed.FeedParser" />
        <alias name="parse-swf"
            extension-id="org.apache.nutch.parse.swf.SWFParser" />
        <alias name="parse-zip"
            extension-id="org.apache.nutch.parse.zip.ZipParser" />
    </aliases>

</parse-plugins>

Am I missing any configuration in nutch side?


text:
Q: Link to JQuery Tab from within page content with ajax tabs I am trying to do this Link to JQuery Tab from within page content
But my pages are loaded from other pages like so

Profile

Honors

History

Following

How do I reference the ajax pages?

A: This is the code I used, added this to my onload function.
function jumpToTab() {
    hashNum = window.location.hash.replace('\#','');
    $("#profileTabs").tabs('select',hashNum);
}

jumpToTab();

$(window).bind('hashchange', function() {
   jumpToTab();
});

Links look like
Tab One
Tab Two
Tab Three

A: I have been working on this for the last two days, using various answers.  Many of the problems I've found are due to Answers referencing old versions of jqueryui.
The below works for jqueryui 1.12.1
I added the below code to the button click of a jqueryui modal
"Switch To Next Tab": function() {
            $( this ).dialog( "close" );//Close the modal
            $('#modal1body').empty;//empty the div container form current modal
            $('#tabs .ui-tabs-active')//remove the active classes for all tabs
                .removeClass("ui-tabs-active")
                .removeClass("ui-state-active");
            $('#tabs').tabs({ active: 1});//Set new tab = current tab + 1
}


text:
Q: About the implementation of color mixed Recently I found a method that mix two colors with passing weight and alpha of two colors to get the RGB value. But I don't understand how the calculation of 'w1'.
Could you tell me some implementation details?
function mix(
  color1: string,
  color2: string,
  weight: number,
  alpha1?: number,
  alpha2?: number
) {
  color1 = dropPrefix(color1); // remove '#'
  color2 = dropPrefix(color2);
  if (weight === undefined) weight = 0.5;
  if (alpha1 === undefined) alpha1 = 1;
  if (alpha2 === undefined) alpha2 = 1;

  var w = 2 * weight - 1;
  var alphaDelta = alpha1 - alpha2;

  // why?
  var w1 = ((w * alphaDelta === -1 ? w : (w + alphaDelta) / (1 + w * alphaDelta)) + 1) / 2;
  var w2 = 1 - w1;

  // convert to RGB array. 'ffffff' to [255, 255, 255]
  var rgb1 = toNum3(color1);
  var rgb2 = toNum3(color2);
  var r = Math.round(w1 * rgb1[0] + w2 * rgb2[0]);
  var g = Math.round(w1 * rgb1[1] + w2 * rgb2[1]);
  var b = Math.round(w1 * rgb1[2] + w2 * rgb2[2]);
  return '#' + pad2(r) + pad2(g) + pad2(b); // restore to hex string
}