Processing.org user input code error? - joptionpane

Could you help me find the error in my code.
import javax.swing.JOptionPane;
String mortgagetype;
mortgagetype = JOptionPane.showInputDialog("What type of mortgage do you desire? (open or closed, only)");
if (mortgagetype == "open" || mortgagetype == "closed") {
print("hello");
}
I want the program to print hello if the user inputs open or closed. However it doesn't and I don't know what the problem is.

Instead of using mortgagetype == "something" in the if statement, use mortgagetype.equals("something").

Related

Error - Unexpected } at the end of While Loop

I'm using while true loop to constantly check run this script. After adding the if expression with whitelist ahk gives an error about unexpected } at the end of code. As far as I know there should be }.
Using Loop command gives the same error.
Removing the problematic } at the end causes the code running in background but not doing anything.
;Setup
Sleep, 1000
whiteList = "none"
;Main Loop
While True
{
siteName = YouTube
WinGetActiveTitle, tabName
Sleep, 10000
if tabName = %whiteList%{
Continue
}
;If current website is Youtube, ask if am I supposted to be here
if InStr(tabName, siteName){
Sleep, 10000
MsgBox, 292, Reality Check, Should you do this?
IfMsgBox, Yes
{
whiteList = tabName
}
;Close tab in mozilla
else
{
WinActivate, %tabName%
Sleep, 10
Send ^w
}
}
}
Code is unfinished, It should run in background and when the user is using YouTube fore some time it should ask him whether is he supposted to watch Youtube.
If he clicks yes, the program should ignore that specific page.
Else it should close it.
The % around the whiteList-var shouldn't be there. When I wrote it like below it seems to work:
if tabName = whiteList
Continue
Also the whiteList = tabName will just assign the string "tabName" to whiteList. Use whiteList := tabName for assigning, and if var1 = var2 for comparison.

Why is a DOORS Module sometimes null when trying to edit the Module via DXL?

I'm new to DXL programming language in IBM DOORS. However, I think I have managed to do many interesting things: create Modules, create Objects, create Links, delete Objects etc.
However, I have a very specific problem regarding "null" Modules. I've just written null between "" because the modules exist and they are referenced with a correct name.
When doing this:
Module m1 = edit("1. MY_MODULE", false)
save(m1)
close(m1)
An error like this appears:
enter image description here
You could not understand what does that mean as it is spanish. Basically states this: "Module null parameter in the first position of the argument." That means that the "m1" is null, as the parameter for save() method is null.
The point is that it is an error which appears only sometimes. It seems that the Module is null as it has been previously opened and DOORS does not close properly.
Is there any way, any method...whatever to avoid this error?
I assume that the script cannot find the module when another folder is active.
Try
Module m1 = edit ("/myproject/myfolder/mysubfolder/1. MY_MODULE", false)
There might be many reasons that the module can't be opened in edit mode. For example: User do not have write access OR Module is being used by other user, etc.
However, you can get around the error with the below code snippet:
Module m = edit('My_module', false)
if(!null m) {
//execute program
...
}
else {
//do something
}
I hope this helps.
How does your script work? do you open the same module again and again and sometimes get the error or do you open lots of modules and for some of them it works and for others it doesn't? In the latter case, perhaps you misspelled the path. You could add some sanity checks like
string fullPathToMod = "/myproject/myfolder.."
Item i = item fullPathToMod;
if null i then error "there is no item called " fullPathToMod
if "Module" != type i then error "there is an item, but it's not a module, it's a " type i
This is how the Code is structured:
void checkModule(string folderPath, string mName, Skip list, int listSize, int listLastIndex, string headers[], string heading[], string headerKey, bool uniqueKey, string combinedKey[]){
if (module mName){
Folder f = folder(folderPath)
current = f
Module m = edit(folderPath""mName, false)
current = m
Object o = first(m) // error sometimes: Se ha pasado un parametro Module null en una posiciĆ³n de argumento 1
if (o == null){
loadModule(m, list, listSize, listLastIndex, headers, heading)
} else {
updateModule(m, mName, list, listSize, listLastIndex, heading, headerKey, headers, uniqueKey, combinedKey)
save(m)
close(m)
}
if (lastError() != ""){
print "Error: " lastError() "\n"
}
} else {
print "No module " mName ".\n"
}
}
Exactly it breaks in line:
current = m
But as said, only sometimes, not always.
BTW, I'm executing this script via Batch, via Java code. One curious thing is that if I close DOORS, and execute the script it does execute correctly. It is as if it needs to be closed in order to edit modules correctly.
I pressume current can be used more than once with different types of Items. I guess it should not be wrong, but it breaks saying (more or less):
Null value passed to DXL commmand (current Module).
Obviously, it means that m is null, but I cannot see any reason for that.

Adobe 9 Check box required field

I've created reports in Adboe that have checkobxes and set then to required fields.
But when i click the submit button all fields but the check boxes are validated.
I.e
If i dont complete the required textbox field the report will not submit, but when i do and the required checkbox fields are not checked it still submits.
This only appears to be happening on Adobe 9
Any ideas?
Thanks
Sp
Here is a link to a test page
http://www.mediafire.com/?mnkmmlime2f
If you fill the text box with anything it will submit regardless of the check box status (which is also a required field)
I have figured it out.
Adobe Reader checkbox allows has a value (default "false") so when the form validates it sees the checkbox as having a value.
I've had to write some java to stop the form submitting if the checkbox has a null/False/false value
This works like a dream
Thanks for trying to help wit hthis post all
var f;
var Valid = "1";
for (var i = 0; i < this.numFields; i++)
{
f = this.getField(this.getNthFieldName(i));
if (f.type == 'checkbox')
{
if(f.required == true)
{
if(f.value == "false" || f.value == "False" || f.value == "null")
{
Valid = "0";
}
}
}
};
if(Valid == "1")
{
this.submitForm('');
}
else
{
app.alert("Please complete all required fields");
}

How can I implement incremental (find-as-you-type) search on command line?

I'd like to write small scripts which feature incremental search (find-as-you-type) on the command line.
Use case: I have my mobile phone connected via USB, Using gammu --sendsms TEXT I can write text messages. I have the phonebook as CSV, and want to search-as-i-type on that.
What's the easiest/best way to do it? It might be in bash/zsh/Perl/Python or any other scripting language.
Edit:
Solution: Modifying Term::Complete did what I want. See below for the answer.
I get the impression GNU Readline supports this kind of thing. Though, I have not used it myself. Here is a C++ example of custom auto complete, which could easily be done in C too. There is also a Python API for readline.
This StackOverflow question gives examples in Python, one of which is ...
import readline
def completer(text, state):
options = [x in addrs where x.startswith(text)]
if state < options.length:
return options[state]
else
return None
readline.set_completer(completer)
this article on Bash autocompletion may help. This article also gives examples of programming bash's auto complete feature.
Following Aiden Bell's hint, I tried Readline in Perl.
Solution 1 using Term::Complete (also used by CPAN, I think):
use Term::Complete;
my $F;
open($F,"<","bin/phonebook.csv");
my #terms = <$F>; chomp(#terms);
close($F);
my $input;
while (!defined $input) {
$input = Complete("Enter a name or number: ",#terms);
my ($name,$number) = split(/\t/,$input);
print("Sending SMS to $name ($number).\n");
system("sudo gammu --sendsms TEXT $number");
}
Press \ to complete, press Ctrl-D to see all possibilities.
Solution 2: Ctrl-D is one keystroke to much, so using standard Term::Readline allows completion and the display off possible completions using only \.
use Term::ReadLine;
my $F;
open($F,"<","bin/phonebook.csv");
my #terms = <$F>; chomp(#terms);
close($F);
my $term = new Term::ReadLine;
$term->Attribs->{completion_function} = sub { return #terms; };
my $prompt = "Enter name or number >> ";
my $OUT = $term->OUT || \*STDOUT;
while ( defined (my $input = $term->readline($prompt)) ) {
my ($name,$number) = split(/\t/,$input);
print("Sending SMS to $name ($number).\n");
system("sudo gammu --sendsms TEXT $number");
}
This solution still needs a for completion.
Edit: Final Solution
Modifying Term::Complete (http://search.cpan.org/~jesse/perl-5.12.0/lib/Term/Complete.pm) does give me on the fly completion.
Source code: http://search.cpan.org/CPAN/authors/id/J/JE/JESSE/perl-5.12.0.tar.gz
Solution number 1 works with this modification. I will put the whole sample online somewhere else if this can be used by somebody
Modifications of Completion.pm (just reusing it's code for Control-D and \ for each character):
170c172,189
my $redo=0;
#match = grep(/^\Q$return/, #cmp_lst);
unless ($#match < 0) {
$l = length($test = shift(#match));
foreach $cmp (#match) {
until (substr($cmp, 0, $l) eq substr($test, 0, $l)) {
$l--;
}
}
print("\a");
print($test = substr($test, $r, $l - $r));
$redo = $l - $r == 0;
if ($redo) { print(join("\r\n", '', grep(/^\Q$return/, #cmp_lst)), "\r\n"); }
$r = length($return .= $test);
}
if ($redo) { redo LOOP; } else { last CASE; }

Opening an MS-Cash Drawer, Wrong Code? Bad Code?

Humbling expierence here and I think this one will make a fool of me, but...I'm trying to convert an ancient cash register program to .net. Conquered everything else, but I can't pop open the cash register. Its connected to COM1, you are supposed to send a "trigger" text down COM1 that will cause the register to open.
Here is the .net code.
MsgBox("Opening Drawer")
Dim port As System.IO.Ports.SerialPort
port = New System.IO.Ports.SerialPort("Com1")
port.PortName = "COM1"
port.BaudRate = 9600
port.Parity = IO.Ports.Parity.None
port.DataBits = 8
port.StopBits = IO.Ports.StopBits.One
'port.Handshake = IO.Ports.Handshake.RequestToSend
port.RtsEnable = True
'port.DtrEnable = True
port.Open()
If port.IsOpen Then
'MsgBox("Attempt 1")
port.Write("####################")
MsgBox("Signal Sent: " & Chr(65))
Else
MsgBox("Port is not open")
End If
port.Close()
MsgBox("Pop, durn it!")
I get msgboxes "Signal Sent", "Done Pop Drawer"
Dang thing, just won't pop. It's an MS-Cash Drawer (EP125KC). Definitely connected to COM1, definitely has power. Chr(65) is the old code used to pop drawer and it works:
Open drawerComPort For Output Access Write As #1
Print #1, Chr$(65); "A";
Close #1
NOTE: The above code worked successfully. The root problem was caused by a reveresed power cord (negative was on the wrong side).
Thanks for all the help guys!
You've set your handshake to None but the cash drawer probably has its own idea. Also set DtrEnable to True. Chr(65) is the ASCII code for an "A", your VB code suggests the real command is "AA".
The manual documents that the cash drawer auto-tunes its baudrate. It recommends sending at least 20 # characters. And that the real command is Ctrl+G (Chr(7)). The "AA" command might have worked previously due to a baudrate mismatch. Perhaps.
If I remember my very rusty BASIC.
Print #1, Chr$(65); "A";
means print to port1 the character 65 followed by the string "A", Now the character 65 is 'A', so this looks to me like you should be sending "AA" to port1
port.Write("AA");
or alternately,
port.Write(new byte[]{65,'A'}, 0, 2);
It might be sending Unicode 65, which would be 0065, which would not end well.
Just a thought, can you try sending a raw int?
I dont use .net, but is the port buffered? do you need to send a flush/fflush()?
Are you sure you're supposed to send out this code? I would have always thought that the code is prefixed by ESC i.e. 0x1b hexadecimal...for cash drawers...
"\x1bA"
Interesting that double 'A' is used...oh well... :)
Edit: After thinking about this I realized there is another way of doing it, read on...
I have modified your original BASIC code with a bit of bullet-proofing...save it to opendrawer.bas
Sub OpenDrawer()
drawerComPort = "COM1"
Open drawerComPort For Output Access Write As #1
REM ADDED ERROR HANDLING
ON ERROR GOTO ErrHandler
Print #1, Chr$(65); "A";
Close #1
print "Drawer Ok"
OpenDrawer_Exit:
On Error Goto 0
Exit Sub
ErrHandler:
print "Oops, Write Failed"
Goto OpenDrawer_Exit
End Sub
REM The Main....
OpenDrawer
Download the old QB4.5 MS-Quick Basic compiler, and compile that to an executable, into opendrawer.exe, the QB4.5 can be found here. Now, the onus is on you to make this bulletproof, i.e. what happens if writing to COM1 fails, issue a message like in the example BASIC code I modified
Then you can use the System.Diagnostics.Process to shell out using a hidden window
public class TestDrawer
{
private StringBuilder sbRedirectedOutput = new StringBuilder();
public string OutputData
{
get { return this.sbRedirectedOutput.ToString(); }
}
public void Run()
{
System.Diagnostics.ProcessStartInfo ps = new System.Diagnostics.ProcessStartInfo();
ps.FileName = "opendrawer";
ps.ErrorDialog = false;
ps.CreateNoWindow = true;
ps.UseShellExecute = false;
ps.RedirectStandardOutput = true;
ps.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
using (System.Diagnostics.Process proc = new System.Diagnostics.Process())
{
proc.StartInfo = ps;
proc.Exited += new EventHandler(proc_Exited);
proc.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(proc_OutputDataReceived);
proc.Start();
proc.WaitForExit();
proc.BeginOutputReadLine();
while (!proc.HasExited) ;
}
}
void proc_Exited(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("proc_Exited: Process Ended");
if (this.sbRedirectedOutput.ToString().IndexOf("Oops, write failed") > -1){
MessageBox.Show(this, "Error in opening Cash Drawer");
}
if (this.sbRedirectedOutput.ToString().IndexOf("Drawer Ok") > -1){
MessageBox.Show(this, "Drawer Ok");
}
}
void proc_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
{
if (e.Data != null) this.sbRedirectedOutput.Append(e.Data + Environment.NewLine);
//System.Diagnostics.Debug.WriteLine("proc_OutputDataReceived: Data: " + e.Data);
}
The process shells out to a hidden window and all output is redirected and handled in the event handler...that should do the trick. Notice, how the redirected output goes into the sbRedirectedOutput (a StringBuilder instance). In the proc_ProcExited event handler, it checks the sbRedirectedOutput for the message 'Oops Write failed' which would be issued from the QB4.5 program.
Be aware, that you may need to include the QB4.5's run-time library in the same directory...not 100% sure...it's being years...
What do you think?
Hope this helps,
Best regards,
Tom.