Automated indentation cleaner for MATLAB or Octave? [closed] - matlab

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
Does anyone know of an existing method of automatically cleaning the indentation of a MATLAB/Octave script? I've got someone else's code (no, really!), and it's horrible - none of the loops or functions are indented, and half of the other lines are indented to apparently random depths.
The problem with MATLAB is that it doesn't use braces, so C++ style indenters aren't going to work. Python ones might, with a bit of modification, which I will try if I can't find a pre-existing solution.
Basically it'd just need to indent lines after lines starting with function, for, if, while... and un-indent lines starting with end*, I think...
Clarification: As pointed out by Jonas, MATLAB users can just select all, and ctrl+I to nicify the indentation. Unfortunately, I don't have access to the MATLAB editor, and it would also be nice to be able to auto-indent a batch of files all at once.

CTRL+A (to select all), followed by CTRL+I (to automatically indent) will do the trick in the Matlab editor.

Ah, I should have known emacs and vi would have answers. I really should learn one of them. Anyway, I got frustrated with the work I was doing, and wrote this as a displacement activity. Remove the + '.test.m' to replace files:
#!/usr/bin/env python
import re, sys
def startswith(line=""):
# these need some word-boundary condition, but \b isn't working
ctrlstart = '\s*(function|if|while|for|switch)'
ctrlcont = '\s*(elseif|else|case|catch|otherwise)'
ctrlend = '\s*(end|endfunction|endif|endwhile|endfor|endswitch)'
match = re.match(ctrlstart, line)
if ( match != None ) :
return ['start', match.group(0)]
match=re.match(ctrlcont, line)
if ( match!=None ) :
return ['cont', match.group(0)]
match=re.match(ctrlend, line)
if ( match!=None ) :
return ['end', match.group(0)]
else :
return [False, None]
def main( filelist = list() ) :
for filename in filelist:
nextindent = 0
indentmult = 2
file = open(filename, 'r')
filelines = file.readlines()
for ind in range(0, len(filelines)) :
indentlevel = nextindent
match = startswith(filelines[ind])
if match[0] == 'start' :
nextindent += 1
elif match[0] == 'cont' :
indentlevel -= 1
elif match[0] == 'end' :
indentlevel -= 1
nextindent -= 1
elif match[0] == False :
nextindent = indentlevel
filelines[ind] = ' '*indentlevel*indentmult + filelines[ind].lstrip().rstrip() +'\n'
outfile = open(filename + '.test.m', 'w')
outfile.writelines(filelines)
file.close()
outfile.close()
args = []
for arg in sys.argv[1:] :
args += [str(arg)]
main(args)

I tried the emacs way but it doesn't work, i am new to ubuntu and octave. So i took the easiest way :D, online site that indent the code for me and i can copy/paste the new clean code.
http://base-n.de/matlab/code_beautifier.html

Here is a vim plugin to automatically indent and syntax highlight for octave code
https://github.com/tranvansang/octave.vim

Related

if statement never returns true in scala when comparing strings

I'm reading text from a text file in Scala. I'm having difficulties with if statements.
for (line <- Source.fromFile(filename).getLines) {
if (line.length>7) {
println("b1 >" + line(7)+ "< " + line(0).getType)
if(line(7)=="#") {
println("hashtag")
}
}
}
below is 2 lines from my text file. the first line has 4 spaces followed by many hashtags. the second line is 4 spaces followed by 1 hashtag (the 4 spaces keep getting deleted by stack overflow)
##################################################################################################################################################
#
below is the output i recieve
//| b1 >#< 12
//| b1 > < 12
Question 1) why is getType returning 12? This is the strangest data type I've ever heard of.
Question 2) (possibly answered by Q1) why does the if(line(7)=="#") statement never returns true?
To answer your questions in reverse order:
Question 2. Because line is a String, line(7) is a Char which is never equal to a String. You want to compare it with '#' instead.
Question 1. Because of the above, this calls Char.getType method which
Returns a value indicating a character's general category.
(not that you can find it from Scala's own documentation). You probably wanted getClass instead.

How to remove part of file between two line delimiter values in Scala Spark? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have text as below,
TIME STAMP1
A1200 EVENT START
EVENT NAME = DOS
EVENT_INS = 1
EVENT_ID = 100
BUFFER = 233355
FORMAT = ATC
LOC = C:/User/data
;
TIME STAMP2
A1201 EVENT START
EVENT NAME = DOS
EVENT_INS = 0
EVENT_ID = 87
BUFFER = 773355
FORMAT = ETC
LOC = C:/User/data
;
how can I remove TIME STAMP2 based on A1201,need to remove from A1201 to ; using scala.A1201 sensor part will repeat at different location in the file. Wherever it comes, I need to remove from A1201 to ;..
How can I do with Scala Spark ?.
You can use the following simple solution
val rdd = sparkContext.wholeTextFiles("path to the text file")
rdd.map(x => x._2.replace("\n", "|*|").split(";").filter(!_.contains("A1201")).mkString(";").replace("|*|", "\n")+";")
where, wholeTextFiles would read the file in Tuple2 format with filename as first argument and text data as the second argument
x._2.replace("\n", "|*|") replaces the line feeds with special character which is to be used later
.split(";") splits the text at ; and forms array
.filter(!_.contains("A1201")) filters out all text from A1201 to ;
.mkString(";").replace("|*|", "\n")+";" converts the array of string to original format.
I hope the answer is helpful

Use commands onto the Manage Snippets plugin from Gedit

I have gedit and the Manage Snippets plugin and I would like to create a snippets to comment a line (it's easy, just add : "# $GEDIT_CURRENT_LINE", for python code for example) but, if the line is ever commented, I would like to uncomment it.
Is there a special syntax to use, I don't know, python or c++ statements like an if with a condition on $GEDIT_CURRENT_LINE ? Because any of code write on the snippets will be only print.
Ok, actually, I just find how a way to do it.
To use bash commands onto the manage snippets plugin, just use `.
For example, in my case, to know what is the first caracter on the line : `${GEDIT_CURRENT_LINE:0:1}` and, with the if statement :
``if [ ${GEDIT_CURRENT_LINE:0:1} == "#" ]; then echo ${GEDIT_CURRENT_LINE:2}; else GEDIT_CURRENT_LINE_STR=$GEDIT_CURRENT_LINE; echo "# $GEDIT_CURRENT_LINE_STR"; fi``
this snippets will comment the line or uncomment it if it is ever commented. (Just as Notepad++ do it).
Edit : you have to create a new variable with the line to rewrite it : GEDIT_CURRENT_LINE_STR=$GEDIT_CURRENT_LINE;. Without that new variable, the current line text can be interpreted as a command and then, just erase the line because of an error. (I updated the code above)
Edit2 : here a snippets to comment/uncomment all the selected lines with python (and not just on as before) :
$<
AllLines = $GEDIT_SELECTED_TEXT.split('\n')
if AllLines == ['']:
AllLines = $GEDIT_CURRENT_LINE.split('\n')
NewLines = []
for line in AllLines:
if line[0:2] == '# ':
NewLines += [line.replace('# ', '')]
elif line[0] == '#':
NewLines += [line.replace('#', '')]
elif line[0] != '#':
NewLines += ['# ' + line]
return '\n'.join(NewLines)
>

Can anyone tell me the name of this cipher please? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
Can anyone tell me the name of this cipher please?
I know it's a simple substitution cipher, I just don't know the name of it.
Cipher Key:
help
Cipher alphabet:
a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z
h|e|l|p|a|b|c|d|f|g|i|j|k|m|n|o|q|r|s|t|u|v|w|x|y|z
Text:
this is a test
Cipher text:
tdfs fs h tast
Isn't that just a simple substitution cipher? You've just moved the 4 letters of "help" to the front and shifted all the remaining letters to the right.
EDIT
Here's an implementation in python as an exercise in lambda, itertools, and star (*) arguments, and wasting time (and perhaps to rescue what could be an interesting discussion on coding ciphers in python):
import string
from itertools import izip, count, starmap
def cipher(s,key):
# characters you want to translate, e.g.
# 'abcd ... xyz '
raw = string.ascii_lowercase + ' '
# cipher with your key, e.g.
# 'helpabcdfgi...z '
sub = key + string.translate(raw, None, key)
# create a dictionary from a character to an index
# in the original raw value string
m = dict( izip( raw, count() ) )
# looks up the index in the map using: starmap(m.get, s)
# then gets the substitution character: map( lambda i:sub[i], ...)
# and joins them together
return ''.join( map( lambda i:sub[i], starmap( m.get, s ) ))
And some test code to verify it works:
ins = 'this is a test'
outs = cipher(ins, "help")
print ins,' -> ',outs
exp = "tdfs fs h tast"
if exp == outs:
print "pass :)"
else:
print "~~ FAIL ~~", " expected ", exp
Output:
D:\temp>cipher.py
this is a test -> tdfs fs h tast
pass :)
I think I have found the answer. A Caesar variant, a "Mixed Alphabet" substitution cipher.
Simple yes, but to add mor complexity you could put it in a block like this (becoming a mixture of Mixed Alphabet and Polyalphabetic):
|a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z
------------------------------------------------------
1|h|e|l|p|a|b|c|d|f|g|I|j|k|m|n|o|q|r|s|t|u|v|w|x|y|z
2|e|l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|v|w|x|y|z|h|e|l|p|a|b|c|d|f|g|I|j|k|m|n|o|q|r|s|t
22|v|w|x|y|z|h|e|l|p|a|b|c|d|f|g|I|j|k|m|n|o|q|r|s|t|u
23|w|x|y|z|h|e|l|p|a|b|c|d|f|g|I|j|k|m|n|o|q|r|s|t|u|v
24|x|y|z|h|e|l|p|a|b|c|d|f|g|I|j|k|m|n|o|q|r|s|t|u|v|w
25|y|z|h|e|l|p|a|b|c|d|f|g|I|j|k|m|n|o|q|r|s|t|u|v|w|x
26|z|h|e|l|p|a|b|c|d|f|g|I|j|k|m|n|o|q|r|s|t|u|v|w|x|y
This would then be more of a Vigenere Cipher variant rather than a Caesar Cipher variant.
Still with the key:
help
The same message:
this is a test
Would become:
tfiv kx c hkep
Another level of complexity would be to group the letters either all together or into blocks:
tfivkxchkep
or blocked (3 characters):
tfi
vkx
chk
epz
With an extra z added to make up the missing character.

Parenthesis Balancing Algorithm recursion [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Can somebody explain to me the algorithm for the Parenthesis Balancing problem?
"Is the string (code) syntax correct on account of matching parentheses couples?"
I can't figure it out apart from the fact that for each " ( " there should be another " ) " for the algorithm to return true.
Thanks!
I found this solution but I do not understand it and I don't want to copy and paste it:
def balance(chars: List[Char]): Boolean = {
def balanced(chars: List[Char], open: Int): Boolean = {
if (chars.isEmpty) open == 0
else
if (chars.head == '(') balanced(chars.tail,open+1)
else
if (chars.head == ')') open>0 && balanced(chars.tail,open-1)
else balanced(chars.tail,open)
}
balanced(chars,0)
}
This code recursively checks if string contains matching amount of opening and closing parentheses by calling balanced() on the string without first element.
Expectancy of parentheses in the string is kept in a kind of balance indicator open - positives indicate amount of needed ')' and negatives amount of needed '('. Initial balance is 0.
When recursion reaches end of string it checks if balance is ok (open == 0), e.g. there was matching amount of parentheses seen.
There is also a check (open > 0) to ensure that ')' wasn't encountered before there was '(' it could close.