What is the preferred way to indent cases in a switch? [closed] - language-agnostic

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
As I was writing another switch in Eclipse, I once again came across a rather weird (to me, at least) default indentation, which is applied to 'switch' statements:
switch (i) {
case 1:
...
case n:
...
}
I tend to prefer another way:
switch (i) {
case 1:
...
case n:
...
}
Which way is more readable and eye-pleasing for you? I'm still not hundred percent determined what's best for me, so I'd like to stick to what's best for other people who would read my code.
BTW, you're free to close this question if this is too subjective. :)

According to the "official" Java Code Conventions, it's the first variant (no additional indentation for case).

I prefer the second way as well. But it is more important to stay consistent within a particular application and/or within a particular team than it is to indent one way or the other.

I tend to indent all control structure bodies a single (4space) tab like so:
switch (i)
{
case 1:
...
case n:
...
}
I consider the switch to be the outer control structure and the case directives part of the body(even though they are part of the control structure).
I would then further tab indent each case like so:
switch (i)
{
case 1:
do_something();
case n:
do_something_else();
}
I find this to be the most readable format for the switch case construct.
As jkohlhepp has mentioned conformity to the code style conventions of the project you are working on is the most important thing, if you are working on a project that has none, it is worth developing some.

I use second way:
switch (i) {
case 1:
...
case n:
...
}

The first is the standard switch case indentation.
switch (i) {
case 1:
.... // Here you can write more code in a row than using the second way
break;
case n:
....
break;
default:
....
break;
}
Notice the new inserted line between switch (i) and case 1:

The first method makes logical sense (to me), however I also prefer the second method. I think most of us are conditioned to expect that code inside braces will be indented.

Related

Get a word broken into syllables and separated by hyphens, without displaying it as

I would like to get a string, of a word broken into one or more syllables, and if more than one, with hyphens, in-between, too.
For example: I would like to get Floccinaucinihilipil-ification out of Floccinaucinihilipilification.
Current browsers are able to break them by hyphens already, grammatical correct.
The reason: I would like to show a term like it would have been shown in a dictionary. Therefor the easiest thing would be to get access to how the browser would break it, but show it in one single line.
In other words: Is there any way to get access to a word as it would be shown to an user agent if there is enough space to show at least the narrowest syllables?
It's possible, if a bit tedious, to determine where the word wraps are located in the document. But you're also depending on the browser having a hyphenation dictionary, which can depend on the platform and possibly the user's language.
Here's one approach, which works in Firefox. I couldn't get Chrome or WebKit to reliably hyphenate the word at every possible spot, and it simply gave up hyphenating below a certain width.
testbed.innerHTML = testbed.innerHTML.replace(/./g, '<span>$&</span>');
outer = testbed.getBoundingClientRect();
match = [...testbed.querySelectorAll('span:not(:first-child)')].filter(e => e.getBoundingClientRect().x == outer.x);
match.forEach(e => e.classList.toggle('match', true));
output = [...testbed.children].map(e => (e.classList.contains('match') ? '-' : '') + e.textContent).join('');
console.log(output);
div#testbed {
width: 0;
hyphens: auto;
}
span.match {
background: magenta;
}
<div id=testbed lang=en>Floccinaucinihilipilification</div>
If you want automatic hyphenation you will have to use a third party js library like Hyphenator.
If you want to place marks, such as ­, manually, you can do so within the html by hand.

Line break inside quotes in an HTML attribute? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have this HTML:
<form action="mypage.php" method="post"
onsubmit="return confirm('Are you sure you want to submit this form? Submitting this form has serious consequences and you should definitely think long and hard before doing it.');">
I want to keep my code at or below 80 characters wide. How can I split this up into multiple lines while retaining the exact same functionality?
I'ld create a Javascript section that defines a function that you call from the form:
<script type="text/javascript">
function formSubmit() {
return confirm('Are you sure you want to submit this form? Submitting' +
' this form has serious consequences and you should ' +
'definitely think long and hard before doing it.');
}
</script>
the form:
<form action="mypage.php" method="post" onsubmit="formSubmit()">
This gets your Javascript out of you HTML form and can be clearly broken where you like.
Do as you want. It is not important to the HTML as long as you avoid doing this for blocks like <PRE>. There's lot of tools like HTML Tidy, HTML beautify, HTML format you could google for and try. Or hit ENTER by hand from time to time
EDIT
I seem to not really get the question at first. If you need to split the JS arguments, slice the strings into smaller blocks and then concatenate it back using +, so instead of
alert('long line here');
you cold write:
alert('long ' +
'line ' +
'here');
but it would be better to separate JS from HTML so your onSubmit should calling the function, instead of holding the end JS code.
I would definitely recommend removing the inline Javascript and keeping things separated. You could even go so far as to remove the onsubmit function and just capture the event in your Javascript itself.
You could break up the string and concatonate it again as has been proposed to get a quick solution, but if you would like to style the confirmation box even more, I would suggest looking into something like http://onehackoranother.com/projects/jquery/boxy/ or http://jqueryui.com/dialog/#modal-confirmation for additional solution options.

Regular expression to remove HTML tags from a string [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Regular expression to remove HTML tags
Is there an expression which will get the value between two HTML tags?
Given this:
<td class="played">0</td>
I am looking for an expression which will return 0, stripping the <td> tags.
You should not attempt to parse HTML with regex. HTML is not a regular language, so any regex you come up with will likely fail on some esoteric edge case. Please refer to the seminal answer to this question for specifics. While mostly formatted as a joke, it makes a very good point.
The following examples are Java, but the regex will be similar -- if not identical -- for other languages.
String target = someString.replaceAll("<[^>]*>", "");
Assuming your non-html does not contain any < or > and that your input string is correctly structured.
If you know they're a specific tag -- for example you know the text contains only <td> tags, you could do something like this:
String target = someString.replaceAll("(?i)<td[^>]*>", "");
Edit:
Ωmega brought up a good point in a comment on another post that this would result in multiple results all being squished together if there were multiple tags.
For example, if the input string were <td>Something</td><td>Another Thing</td>, then the above would result in SomethingAnother Thing.
In a situation where multiple tags are expected, we could do something like:
String target = someString.replaceAll("(?i)<td[^>]*>", " ").replaceAll("\\s+", " ").trim();
This replaces the HTML with a single space, then collapses whitespace, and then trims any on the ends.
A trivial approach would be to replace
<[^>]*>
with nothing. But depending on how ill-structured your input is that may well fail.
You could do it with jsoup http://jsoup.org/
Whitelist whitelist = Whitelist.none();
String cleanStr = Jsoup.clean(yourText, whitelist);

Language support for recursive comments

Most languages I've worked with don't have support for recursive comments.
Is there any reason why language designers would choose not to implement this?
Is it deceptively complex?
Would it have undesired results?
Example of a recursive comment:
/*
for (int j = 0; j <= SourceTexture.Height; j += SampleSize)
{
...
}
// Comment within comment below:
/*for (int i = 0; i < TextureColour.Length; i++)
{
...
}*/
sourceTexture.SetData<Color>(TextureColour);
*/
EDIT: I understand the argument of the answers so far (problems occur when you have comment tokens in strings). However, the reason for my confusion is that you have that problem now.
For example, i know the code below wouldn't give the expected result.
/*
char *str = "/* string";
// Are we now 1 level inside a comment or 2 levels?
*/
printf("Hello world");
/*
char *str2 = "string */";
*/
But in my mind that's no different to an unexpected result in the case below:
/*
CODE "*/";
*/
Which would also yield an unexpected/undesired result.
So, while it could be a problem for recursive comments, my argument as to why that's not a reason not to do it, is that it is already a problem for non-recursive comments. As a programmer i know the compiler behaves like this and i work around it. I don't think it's much more effort to work around the same problem with recursive comments.
Is there any reason why language designers would choose not to
implement this?
It makes the lexical analysis more difficult to implement.
Is it deceptively complex?
IMHO, no, but this is subjective.
Would it have undesired results?
Hard to tell. You have already discovered that even normal block comments can make problems:
/* print ("*/"); */
I know 2 languages that have nesting block comments: Haskell and Frege.
I will make an example and perhaps it will be clearer:
/*
char *str = "/* string";
// Are we now 1 level inside a comment or 2 levels?
*/
printf("Hello world. Will this be printed? Or is it a comment?");
/*
char *str2 = "string */";
*/
You couldn't parse comments inside a comment without interpreting what is inside the comment. But you can't interpret what is inside a comment because it's a comment, so by definition "human text" and not "language".
Although C's multi-line comments can't be nested, the effect of recursive comments can more-or-less be achieved in C using #if 0 ... #endif (and I strongly recommend you use that when you want to disable a block of code, for exactly that reason).
Even the C preprocessor, designed to be as dumb as a post, would be perfectly capable of handling nested comments, just as it has to be capable of handling nested #if directives with false conditions. So it's not really to do with anything being difficult to define or parse, since although it makes comments more complex, they'd still be no more complex than other things done in preprocessing.
But, using #if 0 ... #endif requires of course that there not be any unmatched #endif in the code you're trying to exclude.
Fundamentally comments cannot be both (a) completely unstructured and (b) recursive. Either by happenstance or deliberate choice, C has gone with (a) -- commented text doesn't have to obey any syntax constraints other than not containing the comment-terminator sequence (or trigraph equivalent such as *??/<newline>/).
I believe it is just never considered to begin with and it becomes a "non-important" feature addition as things develop. Also, it requires a lot more validation.
Example scenario...
MyLang version 1: Objective
Provide Multi-line commenting
Developer: hmmm.. I know, every time I find a /* I will comment everything until the next */ - easy!
MyLang version 1 release
1 day later...
User: erm... I cant do recursive comments, help me.
Support: Please hold.
30 mins later...
Support Manager -> Developer: User cannot do recursive comments.
Developer: (What's a recursive...) hang on...
30 mins later
Developer: yeah, we dont support recursive commenting.

How do I put two spaces after every period in our HTML?

I need there to be two spaces after every period in every sentence in our entire site (don't ask).
One way to do it is to embark on manually adding a &nbsp after every single period. This will take several hours.
We can't just find and replace every period, because we have concatenations in PHP and other cases where there is a period and then a space, but it's not in a sentence.
Is there a way to do this...and everything still work in Internet Explorer 6?
[edit] - The tricky part is that in the code, there are lines of PHP that include dots with spaces around them like this:
<?php echo site_url('/css/' . $some_name .'.css');?>
I definitely don't want extra spaces to break lines like that, so I would be happy adding two visible spaces after each period in all P tags.
As we all know, HTML collapses white space, but it only does this for display. The extra spaces are still there. So if the source material was created with two spaces after each period, then some of these substitution methods that are being suggested can be made to work reliably - search for "period-space-space" and replace it with something more suituble, like period-space-&emsp14;. Please note that you shouldn't use because it can prevent proper wrapping at margins. (If you're using ragged right, the margin change won't be noticeable as long as you use the the nbsp BEFORE the space.)
You can also wrap each sentence in a span and use the :after selector to add a space and format it to be wide with "word-spacing". Or you can wrap the space between sentences itself in a span and style that directly.
I've written a javascript solution for blogger that does this on the fly, looks for period-space-space, and replaces it with a spanned, styled space that appears wider.
If however your original material doesn't include this sort of thing then you'll have to study up on sentence boundary detection algorithms (which are not so simple), and then modify one to also not trip over PHP code.
You might be able to use the JavaScript split method or regex depending on the scope of the text.
Here's the split method:
var el = document.getElementById("mydiv");
if (el){
el.innerText = el.innerText.split(".").join(".\xA0 ");
}
Test case:
Hello world.Insert spaces after the period.Using the split method.
Result:
Hello world. Insert spaces after the period. Using the split method.
Have you thought using output buffer? ob_start($callback)
Not tested, but if you'll stick this before any output (or betetr yet, offload the function):
<?php
function processDots($buffer)
{
return (str_replace(".", ". ", $buffer));
}
ob_start("processDots");
?>
and add this to end of input:
<?php ob_end_flush(); ?>
Might just work :)
If you're not opposed to a "post processing"/"javascript" solution:
var nodes = $('*').contents().map(function(a, b) {
return (b.nodeType === Node.TEXT_NODE ? b : null);
});
$.each(nodes, function(i,node){
node.data = node.data.replace(/(\.\s)/g, '.\u00A0\u00A0');
});
Using jQuery for the sake of brevity, but not required.
p.s. I saw your comment about not all periods and a space are to be treated equal, but this is about as good as it gets. otherwise, you're going to need a lot better/more bullet-proof approach.
Incorporate something like this into your PHP file:
<?php if (preg_match('/^. [A-Z]$/' || '/^. [A-Z]$/')) { preg_replace('. ', '. '); } ?>
This allows you to search for the beginning of each new sentence as in .spacespaceA-Z, or .spaceA-Z and then replaces that with . space. [note: Capital letter is not replaced]