plugin for formatting comments - sublimetext2

Can anyone point me in the direction of a plugin or otherwise for formatting comments?
I'm using coffeescript, commenting is the same as python (#line, ### block ###), although javascript commenting also passes straight through the compiler.

OK, turns out that Edit -> Wrap keeps comments intact - complete newby.
There is also https://github.com/spadgos/sublime-jsdocs

I don't have a plug-in but I can offer a python script that I wrote. Enter your comment as a string at the 'user entered comment' (uec) variable, save and run. It will format a block quote surrounded by pound signs 80 characters across. If you need your block quote shorter or longer then just change the 80, the 78, and the 76.
def first2lines(): return str(('#' * 80) + '\n' + '#' + (' ' * 78) + '#') # first two lines
def leftSide(): return '# ' # left side of border
def rightSide(): return ' #' # right side of border
def last2lines(): return str('#' + (' ' * 78) + '#' + '\n' + ('#' * 80)) # last two lines
# user entered comment
uec = "This program will neatly format a programming comment block so that it's surrounded by pound signs (#). It does this by splitting the comment into a list and then concatenating strings each no longer than 76 characters long including the correct amount of right side space padding. "
if len(uec) > 0:
eosm = '<<<EOSM>>>' # end of string marker
comment = uec + ' ' + eosm
wordList = comment.split() # load the comment into a list
tmpString = '' # temporarily holds loaded elements
loadComment = '' # holds the elements that will be printed
counter = 0 # keeps track of the number of elements/words processed
space = 0 # holds right side space padding
last = wordList.index(wordList[-1]) # numerical position of last element
print first2lines()
for word in wordList:
tmpString += word + ' ' # load the string until length is greater than 76
# processes and prints all comment lines except the last one
if len(tmpString.rstrip()) > 76:
tmpList = tmpString.split()
tmpString = tmpList[-1] + ' ' # before popping last element load it for the beginning of the next cycle
tmpList.pop()
for tmp in tmpList:
loadComment += tmp + ' '
loadComment = loadComment.rstrip()
space = 76 - len(loadComment)
print leftSide() + loadComment + (space * ' ') + rightSide()
loadComment = ''
# processes and prints the last comment line
elif len(tmpString.rstrip()) <= 76 and counter == last:
tmpList = tmpString.split()
tmpList.pop()
for tmp in tmpList:
loadComment += tmp + ' '
loadComment = loadComment.rstrip()
space = 76 - len(loadComment)
print leftSide() + loadComment + (space * ' ') + rightSide()
counter += 1
print last2lines()
else:
print first2lines()
print leftSide() + "The length of your comment is zero, it must be at least one character long. " + rightSide()
print last2lines()

You can use netbeans, it has autoFormatting Alt+Mayus+F

Related

Why is isspace() returning false for strings from the docx python library that are empty?

My objective is to extract strings from numbered/bulleted lists in multiple Microsoft Word documents, then to organize those strings into a single, one-line string where each string is ordered in the following manner: 1.string1 2.string2 3.string3 etc. I refer to these one-line strings as procedures, consisting of 'steps' 1., 2., 3., etc.
The reason it has to be in this format is because the procedure strings are being put into a database, the database is used to create Excel spreadsheet outputs, a formatting macro is used on the spreadsheets, and the procedure strings in question have to be in this format in order for that macro to work properly.
The numbered/bulleted lists in MSword are all similar in format, but some use numbers, some use bullets, and some have extra line spaces before the first point, or extra line spaces after the last point.
The following text shows three different examples of how the Word documents are formatted:
Paragraph Keyword 1: arbitrary text
1. Step 1
2. Step 2
3. Step 3
Paragraph Keyword 2: arbitrary text
Paragraph Keyword 3: arbitrary text
• Step 1
• Step 2
• Step 3
Paragraph Keyword 4: arbitrary text
Paragraph Keyword 5: arbitrary text
Step 1
Step 2
Step 3
Paragraph Keyword 6: arbitrary text
(For some reason the first two lists didn't get indented in the formatting of the post, but in my word document all the indentation is the same)
When the numbered/bulleted list is formatted without line extra spaces, my code works fine, e.g. between "paragraph keyword 1:" and "paragraph keyword 2:".
I was trying to use isspace() to isolate the instances where there are extra line spaces that aren't part of the list that I want to include in my procedure strings.
Here is my code:
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
def extractStrings(file):
doc = file
for i in range(len(doc.paragraphs)):
str1 = doc.paragraphs[i].text
if "Paragraph Keyword 1:" in str1:
start1=i
if "Paragraph Keyword 2:" in str1:
finish1=i
if "Paragraph Keyword 3:" in str1:
start2=i
if "Paragraph Keyword 4:" in str1:
finish2=i
if "Paragraph Keyword 5:" in str1:
start3=i
if "Paragraph Keyword 6:" in str1:
finish3=i
print("----------------------------")
procedure1 = ""
y=1
for x in range(start1 + 1, finish1):
temp = str((doc.paragraphs[x].text))
print(temp)
if not temp.isspace():
if y > 1:
procedure1 = (procedure1 + " " + str(y) + "." + temp)
else:
procedure1 = (procedure1 + str(y) + "." + temp)
y=y+1
print(procedure1)
print("----------------------------")
procedure2 = ""
y=1
for x in range(start2 + 1, finish2):
temp = str((doc.paragraphs[x].text))
print(temp)
if not temp.isspace():
if y > 1:
procedure2 = (procedure2 + " " + str(y) + "." + temp)
else:
procedure2 = (procedure2 + str(y) + "." + temp)
y=y+1
print(procedure2)
print("----------------------------")
procedure3 = ""
y=1
for x in range(start3 + 1, finish3):
temp = str((doc.paragraphs[x].text))
print(temp)
if not temp.isspace():
if y > 1:
procedure3 = (procedure3 + " " + str(y) + "." + temp)
else:
procedure3 = (procedure3 + str(y) + "." + temp)
y=y+1
print(procedure3)
print("----------------------------")
del doc
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
import docx
doc1 = docx.Document("docx_isspace_experiment_042420.docx")
extractStrings(doc1)
del doc1
Unfortunately I have no way of putting the output into this post, but the problem is that whenever there is a blank line in the word doc, isspace() returns false, and a number "x." is assigned to empty space, so I end up with something like: 1. 2.Step 1 3.Step 2 4.Step 3 5. 6. (that's the last iteration of print(procedure3) from the code)
The problem is that isspace() is returning false even when my python console output shows that the string is just a blank line.
Am I using isspace() incorrectly? Is there something in the string I am not detecting that is causing isspace() to return false? Is there a better way to accomplish this?
Use the test:
# --- for s a str value, like paragraph.text ---
if s.strip() == "":
print("s is a blank line")
str.isspace() returns True if the string contains only whitespace. An empty str contains nothing, and so therefore does not contain whitespace.

Cannot prettify html code with sublime text nor beautiful soup

I am trying to webscrape some website for information. i have saved the page I want to scrape as .html file and have opened it with sublime text but there are some parts that cannot be displayed in a prettified way ; I have the same problem when trying to use beautifulsoup ; see picture below (I cannot really share full code since it's disclosing private info).
Just feed the HTML as a multiline string to BeautifulSoup object and use soup.prettify(). That should work. However beautifulsoup has default indentation to 2 spaces. So if you want custom indent you can writeup a little wrapper like this:
def indentPrettify(soup, indent=4):
# where desired_indent is number of spaces as an int()
pretty_soup = str()
previous_indent = 0
# iterate over each line of a prettified soup
for line in soup.prettify().split("\n"):
# returns the index for the opening html tag '<'
current_indent = str(line).find("<")
# which is also represents the number of spaces in the lines indentation
if current_indent == -1 or current_indent > previous_indent + 2:
current_indent = previous_indent + 1
# str.find() will equal -1 when no '<' is found. This means the line is some kind
# of text or script instead of an HTML element and should be treated as a child
# of the previous line. also, current_indent should never be more than previous + 1.
previous_indent = current_indent
pretty_soup += writeOut(line, current_indent, indent)
return pretty_soup
def writeOut(line, current_indent, desired_indent):
new_line = ""
spaces_to_add = (current_indent * desired_indent) - current_indent
if spaces_to_add > 0:
for i in range(spaces_to_add):
new_line += " "
new_line += str(line) + "\n"
return new_line

displaydata function in ex3 coursera machine learning

I am facing a issue, here is my script. some end or bracket issue but I have checked noting is missing.
function [h, display_array] = displayData(X, example_width)
%DISPLAYDATA Display 2D data in a nice grid
% [h, display_array] = DISPLAYDATA(X, example_width) displays 2D data
% stored in X in a nice grid. It returns the figure handle h and the
% displayed array if requested.
% Set example_width automatically if not passed in
if ~exist('example_width', 'var') || isempty(example_width)
example_width = round(sqrt(size(X, 2)));
end
% Gray Image
colormap(gray);
% Compute rows, cols
[m n] = size(X);
example_height = (n / example_width);
% Compute number of items to display
display_rows = floor(sqrt(m));
display_cols = ceil(m / display_rows);
% Between images padding
pad = 1;
% Setup blank display
display_array = - ones(pad + display_rows * (example_height + pad), ...
pad + display_cols * (example_width + pad));
% Copy each example into a patch on the display array
curr_ex = 1;
for j = 1:display_rows
for i = 1:display_cols
if curr_ex > m,
break;
end
% Copy the patch
% Get the max value of the patch
max_val = max(abs(X(curr_ex, :)));
display_array(pad + (j - 1) * (example_height + pad) +
(1:example_height), ...
pad + (i - 1) * (example_width + pad) +
(1:example_width)) = ...
reshape(X(curr_ex, :),
example_height, example_width) / max_val;
curr_ex = curr_ex + 1;
end
if curr_ex > m,
break;
end
end
% Display Image
h = imagesc(display_array, [-1 1]);
% Do not show axis
axis image off
drawnow;
end
ERROR:
displayData
parse error near line 86 of file C:\Users\ALI\displayData.m
syntax error
Pls guide which is the error in the script, this script is already written in
the coursera so its must be error free.
You seem to have modified the code, and moved the "ellipsis" operator (i.e. ...) or the line that is supposed to follow it, in several places compared to the original code in coursera.
Since the point of the ellipsis operator is to appear at the end of a line, denoting that the line that follows is meant to be a continuation of the line before, then moving either the ellipsis or the line below it will break the code.
E.g.
a = 1 + ... % correct use of ellipsis, code continues below
2 % treated as one line, i.e. a = 1 + 2
vs
a = 1 + % without ellipsis, the line is complete, and has an error
... 2 % bad use of ellipsis; also anything to the right of '...' is ignored
vs
a = 1 + ... % ellipsis used properly so far
% but the empty line here makes the whole 'line' `a = 1 +` which is wrong
2 % This is a new instruction

How to save the values of the factors of a CFA analysis in my dataset

I performed a CFA using the lavaan package
require('lavaan');
HS.model <- 'external_regulation_soc =~ JOBMOTIVATIE_extsoc1 +
JOBMOTIVATIE_extsoc2 + JOBMOTIVATIE_extsoc3
external_regulation_mat =~ JOBMOTIVATIE_extmat1 +
JOBMOTIVATIE_extmat2 + JOBMOTIVATIE_extmat3
introjected_regulation =~ JOBMOTIVATIE_introj1 +
JOBMOTIVATIE_introj2 + JOBMOTIVATIE_introj3 +
JOBMOTIVATIE_introj4
identified_regulation =~ JOBMOTIVATIE_ident1 +
JOBMOTIVATIE_ident2 + JOBMOTIVATIE_ident3
intrinsic_motivation =~ JOBMOTIVATIE_intrin1 +
JOBMOTIVATIE_intrin2 + JOBMOTIVATIE_intrin3'
fit <- cfa(HS.model, data = dataset, scores="regression")
summary(fit, fit.measures=TRUE, standardized=TRUE)
I managed to get the values for the five factors in a seperate dataset using
data_factor <- predict(fit)
But I need these 5 factors (as columns, as variables), added to my original dataset. How can I achieve this?
I tried cbind, but got an error:
factorERS <- select(dataset, JOBMOTIVATIE_extsoc1 +
JOBMOTIVATIE_extsoc2 + JOBMOTIVATIE_extsoc3)
data_CFA <- cbind(dataset, fit$scores)
Error in fit$scores : $ operator not defined for this S4 class
Thanks for helping me out!

Word Count printed in Vim document

I'd like to add to my .vimrc file a function which updates the text in an open document, specifically where it finds the text "Word Count: " it would use vim to insert an accurate word count in the current document.
This is mostly as a programming exercise and to better learn vim, I know there are external programs like wc available to do this work.
Here's an example of a similar function I'm using to count lines of code:
function! CountNonEmpty()
let l = 1
let char_count = 0
while l <= line("$")
if len(substitute(getline(l), '\s', '', 'g')) > 3
let char_count += 1
endif
let l += 1
endwhile
return char_count
endfunction
function! LastModified()
if &modified
let save_cursor = getpos(".")
let n = min([15, line("$")])
keepjumps exe '1,' . n . 's#^\(.\{,10}LOC:\).*#\1' .
\ ' ' . CountNonEmpty() . '#e'
call histdel('search', -1)
call setpos('.', save_cursor)
endif
endfun
autocmd BufWritePre * call LastModified()
Can someone help me figure out how to add to the LastModified function so that it inserts a word count where it finds the text Word Count in the header?
After some more digging I found the answer. This is code from Michael Dunn, another StackOverflow user, posted at Fast word count function in Vim
I'll post how I incorporated it here in case anyone else finds this portion of my .vimrc to be useful:
function! CountNonEmpty()
let l = 1
let char_count = 0
while l <= line("$")
if len(substitute(getline(l), '\s', '', 'g')) > 3
let char_count += 1
endif
let l += 1
endwhile
return char_count
endfunction
function WordCount()
let s:old_status = v:statusmsg
exe "silent normal g\<c-g>"
let s:word_count = str2nr(split(v:statusmsg)[11])
let v:statusmsg = s:old_status
return s:word_count
endfunction
" If buffer modified, update any 'Last modified: ' in the first 20 lines.
" 'Last modified: ' can have up to 10 characters before (they are retained).
" Restores cursor and window position using save_cursor variable.
function! LastModified()
if &modified
let save_cursor = getpos(".")
let n = min([15, line("$")])
keepjumps exe '1,' . n . 's#^\(.\{,10}LOC:\).*#\1' .
\ ' ' . CountNonEmpty() . '#e'
keepjumps exe '1,' . n . 's#^\(.\{,10}Word Count:\).*#\1' .
\ ' ' . WordCount() . '#e'
call histdel('search', -1)
call setpos('.', save_cursor)
endif
endfun
autocmd BufWritePre * call LastModified()