I have a rather unusual problem, and it is hurting my brain.
Problem: Given a textbox of known length, and the text that will go inside it, make the text "fit" by truncating it with room for "..." to fit inside the box. (Context : This is for ASP.NET C#, but I think the algorithm is language agnostic.)
Example : [_________]
Text : The big brown dog jumped over the red fence.
Solution :[The bi...]
Example : [_________]
Text : Ferret
Solution :[Ferret___]
Given:
// Returns the number of px (as an int) that the arg text is in length
public int textLength(String theText, float emSize)
Question: What is the simplest and fastest way to do this?
I am afraid to do it by hacking off one character at a time, adding "..." and then checking the length because some of the strings to fit are veeeeery long.
You could do a binary search on the correct length instead, which means you only have to try log(n) sizes.
Oh, also if the text is monospaced (every character is given the width of an em) then it's pretty easy to figure this out programatically:
if str.length * emWidth < textBoxWidth
tb.text = str
else
tb.text = substring(str, 0, round_down(textBoxWidth / emWidth) - 3) + "..."
Why start from end? Start from the beginning and add letters (and ...) until it no longer fits. :)
Related
For the past while I've been working on a calculator, but have run into problems when needing to divide by a half. I'll add the offending bit of code along with a loop to keep it open below.
on = true
while on == true do
half = 1.0 / 2.0
puts ("FUNCTION IN TESTING MODE, DO NOT EXPECT IT TO FUNCTION PROPERLY")
puts ("Area of a triangle")
print("What is the legnth of the base? ").to_i
base = gets.chomp("base")
print("\nWhat is the height? ")
height = gets.chomp("height").to_i
PreAreaT = base * height
AreaT = PreAreaT * half
puts("The area of the triangle is #{AreaT}")
end
So essentially, how on Earth do I get the program to display an answer, rather than outputting nothing for the answer?
EDIT:As it would turn out the code above is improperly done. I've spent nearly two weeks asking myself why it wouldn't work only to find I had .to_i after a print statement rather than the input.
Your to_i call is switched around here.
print("What is the legnth of the base? ").to_i
base = gets.chomp("base")
Should be the other way 'round.
print("What is the length of the base? ")
base = gets.chomp("base").to_i
Further, chomp will attempt to remove any occurrences of base or height from the string. Be sure that you're intention is to remove those occurrences; if you want to remove whitespace, you'll have to take a different approach.
I wish to capitalize the first letter of a sentence, on-the-fly, as the user types the text in a CKEditor content instance.
The strategy consists in catching each keystroke and try to replace it when necessary, that is for instance, when the inserted character follows a dot and a space. I'm fine with catching the event, but can't find a way to parse characters surrounding the caret position:
var instance = CKEDITOR.instances.htmlarea
instance.document.getBody().on('keyup', function(event) {
console.log(event);
// Would like to parse here from the event object...
event.data.preventDefault();
});
Any help would be much appreciated including a strategy alternative.
You should use keydown event (close to what you proposed):
var editor = CKEDITOR.instances.editor1;
editor.document.getBody().on('keydown', function(event) {
if (event.data.getKeystroke() === 65 /*a*/ && isFirstLetter()) {
// insert 'A' instead of 'a'
editor.insertText('A');
event.data.preventDefault();
}
});
Now - how should isFirstLetter() look like?
You have to start from editor.getSelection().getRanges() to get caret position.
You're interested only in the first range from the collection.
To extract text content from before the caret use small trick:
move start of the range to the beginning of document: range.setStartAt( editor.document.getBody(), CKEDITOR.POSITION_AFTER_START ),
use CKEDITOR.dom.walker to traverse through DOM tree in source order,
collect text nodes and find out what's before caret (is it /\. $/) - remember that you have to skip inline tags and stop on block tags - hint: return false from guard function to stop traversing.
Example of how you can use walker on range:
var range, walker, node;
range = editor.getSelection().getRanges()[0];
range.setStartAt(editor.document.getBody(), CKEDITOR.POSITION_AFTER_START);
walker = new CKEDITOR.dom.walker(range);
walker.guard = function(node) {
console.log(node);
};
while (node = walker.previous()) {}
And now few sad things.
We assumed that selection is empty when you type - that doesn't have to be true. When selection is not collapsed (empty) then you'll have to manually remove its content before calling insertText. You can use range#deleteContents to do this.
But this is not all - after deleting range's content you have to place caret in correct position - this isn't trivial. Basically you can use range#select (on the range after deleteContents), but in some cases it can place caret in incorrect place - like between paragraphs. Fixing this is... is not doable without deeeeeeeep knowledge about HTML+editables+insertions+other things :).
This solution is not complete - you have to handle paste event, deleting content (one can delete words from the start of sentence), etc, etc.
I guess there are couple of other problems I didn't even thought about :P.
So this approach isn't realistic. If you still want to implement this feature I think that you should set timer and by traversing DOM (you can use walker on range containing entire document, or recently typed text (hard to find out where it is)) find all sentences starting from lower letter and fix them.
This is what worked for me in Ckeditor 4.
var editor = CKEDITOR.instances.editor1;
editor.document.getBody().on('keydown', function(event) {
if (event.data.getKeystroke() >= 65 && event.data.getKeystroke()<=91 && encodeURI(this.getText())=="%0A" && this.getText().length==1 ) {
//uppercase the char
editor.insertText(String.fromCharCode(event.data.getKeystroke()));
event.data.preventDefault();
}
});
I'm using the following command to print a justified text:
^FB1800,3,0,J^FT100,200^A0B,26,26^FH\^FDLONG TEXT TO BE PRINTED, WHICH DOESNT FIT IN ONLY 3 LINES...^FS
The command ^FB1800,3,0,J prints a field block in a width of 1800 dots, maximum 3 lines, justified.
The problem is that if the text exceeds the maximum number of lines, it overwrites the last line! :( That of course makes the text of the last line unreadable.
How can I avoid that? Does anybody know if is there a way to cut the exceeding text?
The documentation says exactly that this happens:
Text exceeding the maximum number of lines overwrites the last line. Changing the font size automatically increases or decreases the size of the block.
For reference: I'm using printer Zebra 220Xi4.
Any help would be appreciated. Thank you!
Take a look at the ^TB command. It is preferred over the ^FB command and truncates if the text exceeds the size defined in the TB params
I had just about the same problem, what fixed it in my case - although not the most elegant way - is to specify a higher number of maximum lines, and then formatting it in a way that only the first 3 are in the visible area.
In your case it would be for example ^FB1800,7,0,J instead of ^FB1800,3,0,J
This at least fixed it for me right away, because I print this text at the bottom of the label. If you need to have it somewhere in the middle or top, there might be some tricks with putting a (white) box on top of the overflow-area, since the Zebra printers seem to render before printing. Hope it helps.
Depending on the higher-level programming language you're using (assuming that you are), you could accomplish the same thing (truncate the text to be printed to a specified number of characters) with code like this (C# shown here):
public void PrintLabel(string price, string description, string barcode)
{
const int MAX_CAPS_DESC_LEN = 21;
const int MAX_LOWERCASE_DESC_LEN = 32;
try
{
bool descAllUpper = HHSUtils.IsAllUpper(description);
if (descAllUpper)
{
if (description.Length > MAX_CAPS_DESC_LEN)
{
description = description.Substring(0, MAX_CAPS_DESC_LEN);
}
}
else // not all upper
{
if (description.Length > MAX_LOWERCASE_DESC_LEN)
{
description = description.Substring(0, MAX_LOWERCASE_DESC_LEN);
}
}
. . .
This is what I'm using; is there any reason to prefer the "raw" ^TB command over this?
I have a webpage which displays multiple textual entries which have no restriction on their length. They get automatically cut if they are too long to avoid going to a new line. This is the PHP function to cut them:
function cutSentence($sentence, $maxlen = 16) {
$result = trim(substr($sentence, 0, $maxlen));
$resultarr = array(
'result' => $result,
'islong' => (strlen($sentence) > $maxlen) ? true : false
);
return $resultarr;
}
As you can see in the image below, the result is fine, but there are a few exceptions. A string containing multiple Ms (I have to account for those) will go to a newline.
Right now all strings get cut after just 16 characters, which is already very low and makes them hard to read.
I'd like to know if a way exists to make sure sentences which deserve more spaces get it and those which contain wide characters end up being cut at a lower number of characters (please do not suggest using the CSS property text-overflow: ellipsis because it's not widely supported and it won't allow me to make the "..." click-able to link to the complete entry, and I need this at all costs).
Thanks in advance.
You could use a fixed width font so all characters are equal in width. Or optionally get how many pixels wide every character is and add them together and remove the additional character wont the pixel length is over a certain amount.
If the style of your application isn't too important, you could simply use a font in the monospace family such as Courier.
Do it in Javascript rather than in PHP. Use the DOM property offsetWidth to get the width of the containing element. If it exceeds some maximum width, then truncate accordingly.
Code copied from How can I mimic text-overflow: ellipsis in Firefox? :
function addOverflowEllipsis( containerElement, maxWidth )
{
var contents = containerElement.innerHTML;
var pixelWidth = containerElement.offsetWidth;
if(pixelWidth > maxWidth)
{
contents = contents + "…"; // ellipsis character, not "..." but "…"
}
while(pixelWidth > maxWidth)
{
contents = contents.substring(0,(contents.length - 2)) + "…";
containerElement.innerHTML = contents;
pixelWidth = containerElement.offsetWidth;
}
}
Since you are asking for a web page then you can use CSS text-overflow to do that.
It seems to be supported enough, and for firefox there seems to be css workarounds or jquery workarounds...
Something like this:
span.ellipsis {
white-space:nowrap;
text-overflow:ellipsis;
overflow:hidden;
width:100%;
display:block;
}
If you fill more text than it fits it will add the three dots at the end.
Just cut the text if it is really too long so you don't waste html space.
More info here:
https://developer.mozilla.org/En/CSS/Text-overflow
Adding a 'see more' link at the end is easy enough, as appending another span with fixed width, containing the link to see more. text will be truncated with ellipsis before that.
This question is similar in spirit to :
https://stackoverflow.com/questions/492178/links-between-personality-types-and-language-technology-preferences
But it is based specifically on indentation (spaces vs tabs and the number of spaces).
The reason I am asking here instead of searching is because I remember seeing a specific document writing about this. If I remember correctly, it also talked about why Linus prefers eight spaces.
The document you are referring to is, I believe, the Linux Kernel Coding Standard:
https://computing.llnl.gov/linux/slurm/coding_style.pdf
Personally, I prefer four spaces, straight up. I try to keep it to 79 characters per line, unless I don't feel like it or there's a long string. When parenthetical statements or comments spill, I align the beginning to the next tab stop on the first line (or one past the next indentation level if I have to,) then align thereafter. Here is a sample of some of my code (taken from some random codebase I'm working on.) Notice what I do with that multi-line conditional.
void R_RecursiveWorldNode (mnode_t *node, int clipflags){
msurface_t *surf;
static vec3_t oldviewangle, oldorigin;
vec3_t deltaorigin, net_movement_angle;
float len_deltaorigin;
float movement_view_diff; //difference between the net movement
//angle and the view angle (0 when
//movement during frame was straight
//ahead.)
VectorSubtract (r_origin, oldorigin, deltaorigin);
len_deltaorigin = abs(len_deltaorigin);
VectorCopy (deltaorigin, net_movement_angle);
VectorNormalize(net_movement_angle);
VectorSubtract (net_movement_angle, vpn, net_movement_angle);
movement_view_diff = abs (movement_view_diff);
// if we have either a new PVS or a significant amount of
// movement/rotation, we should actually recurse the BSP again.
if ( (r_oldviewcluster != r_viewcluster && r_viewcluster != -1) ||
len_deltaorigin > 12.0 || vpn[YAW] != oldviewangle[YAW] ||
movement_view_diff > 1.0 ) {
VectorCopy (vpn, oldviewangle);
VectorCopy (r_origin, oldorigin);
r_ordinary_surfaces = NULL;
r_alpha_surfaces = NULL;
r_special_surfaces = NULL;
__R_RecursiveWorldNode (node, clipflags);
}
surf = r_ordinary_surfaces;
while (surf){
GL_RenderLightmappedPoly( surf );
surf = surf->ordinarychain;
}
}
This comes, I think, from being a Python programmer. It's C equivalent of the default indentation scheme in the IDLE editor which I used to use a lot.