Sinatra executing ls on sever side - html

I am trying to show in Chrome using Sinatra, the result of ls. But the explorer gets in an "Connecting..." loop.
My code is:
require 'rubygems' if RUBY_VERSION < "1.9"
require 'sinatra/base'
#This is the webservice to launch the gamma project
#Using Request at the principal webpage
class MyApp < Sinatra::Base
get '/' do
result = exec "ls"
puts result
end
end
I am not sure of that puts, I think that maybe is not the apropiate method. What could be happening and how can I solve it?
PS: In the explorer I used localhost.com:4567/

Use the backticks ( ` ) instead of the Kernel#exec command. The former returns a string that you can then use in your ruby process. The latter throws your execution context into a new process and has no return value.
get '/' do
result = %x`ls`
puts result
end
Note that the call to puts will not look very nice and that you'll probably want to format it or parse/manipulate it further. But at least you'll get something you can use.

As #pgblu pointed out you should use backticks.
https://stackoverflow.com/a/18623297/1279355
And the second thing, puts print the result only to your shell/log,
but to see the result in your chrome you need either:
get '/' do
result = %x`ls`
return result
end
or
get '/' do
result = %x`ls`
result
end
As you can see the return is optional, if there is no return Sinatra just displays the last variable/operation.

Related

When defining a variable in a julia function, I get an error about an undefined variable on that line

Problem
I'm writing a Julia script, and in the function there is a while loop. Inside the while loop there is a variable. That line is throwing errors about the variable being undefined when in fact that is the very line defining the variable.
The code
The error is on line 65
function cleanTexLoop(fileName::String)
f = open(fileName, "r")
while ! eof(f)
line = readline(f), <-- line 65
#line = sentenceFilter(line)
println(line)
end
close(f)
end
The function opens a file which IS getting passed into a loop. The loop runs until the end of file. While looping the file is read line by line. Each time it is read the line is stored in variable line and the file advances. In the proper version, that one line (66) isn't commented out, however for debugging it is. line is then taken as input into a filter which modifies the line before storing it again as line. The final version of this script will have four filters, but for now, I'd be happy to get this to run with just zero filters.
(Note that a user has kindly pointed out the comma that after hours of looking at the code continued to allude me. I'm waiting for that user to write up an answer)
The error message
cleanTexLoop("test.tex")
ERROR: UndefVarError: line not defined
Stacktrace:
[1] cleanTexLoop(::String) at /home/nero/myScripts/latexCleaner.jl:65
[2] macro expansion at ./REPL.jl:97 [inlined]
[3] (::Base.REPL.##1#2{Base.REPL.REPLBackend})() at > ./event.jl:73
Previous working version
I had previous written another version of this which works in entirety, however I needed to make some substantial changes to its structure in order to better suit future plans. Note that some of the names aren't up to the normal naming convention. Namely, I use "!" when no variables are actually being changed.
function CleanTexLoop(fileName::String,regX::String,sub::String)
f = open(fileName, "r")
while ! eof(f)
println(applySub!(f,regX,sub))
end
close(f)
end
function applySub!(file::IOStream,regX::String,sub::String)
return replace(
readline(file),
Base.Regex(regX),
Base.SubstitutionString(sub)
)
end
A simple loop which demonstrates why this should work
x = 0
while x < 4
y = x
println(y)
x = x+1
end
As expected, this prints zero to one, and is, as far as I can tell, representative of what I am doing. In both cases I am passing some variable into the loop which, through some action, defines another variable inside the loop which is then printed. Why this works, and the other doesn't is beyond me.
What I've seen on Google.
From looking this problem up, it appears as if this problem arrises when defining variables outside of a loop, or similar environment, as a result of them failing to be passed into the environment. However, this isn't what's happening in my case. In my case the variable is being defined for the first time.
As mentioned in the comments, the problem was an errant comma.

printing the output of shell command from python subprocess

I am running a shell script which emits lots of line while executing...they are just status output rather than the actual output....
I want them to be displayed on a JTextArea. I am working on jython. The piece of my code looks like:
self.console=JTextArea(20,80)
cmd = "/Users/name/galaxy-dist/run.sh"
p = subprocess.Popen(cmd, stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=True)
self.console.append(p.stdout.read())
This will wait until the command finishes and prints the output. But I want to show the realtime out put to mimic the console. Anybody have the idea ?
You're making things more complicated than they need to be. The Popen docs state the following about the stream arguments:
With the default settings of None, no redirection will occur; the child’s file handles will be inherited from the parent. [my emphasis]
Therefore, if you want the subprocess' output to go to your stdout, simply leave those arguments blank:
subprocess.Popen(cmd, shell=True)
In fact, you aren't using any of the more advanced features of the Popen constructor, and this particular example doesn't need any parsing by the shell, so you can simplify it further with the subprocess.call() function:
subprocess.call(cmd)
If you still want the return code, simply set a variable equal to this call:
return_code = subprocess.call(cmd)

Hanging MySQL2 connections spun up in EventMachine

I'm running this code from the mysql2 gem docs:
require 'mysql2/em'
EM.run do
client1 = Mysql2::EM::Client.new
defer1 = client1.query "SELECT sleep(3) as first_query"
defer1.callback do |result|
puts "Result: #{result.to_a.inspect}"
end
client2 = Mysql2::EM::Client.new
defer2 = client2.query "SELECT sleep(1) second_query"
defer2.callback do |result|
puts "Result: #{result.to_a.inspect}"
end
end
It runs fine, printing the results
Result: [{"second_query"=>0}]
Result: [{"first_query"=>0}]
but then the script just hangs and never returns to the command line. Any idea what is going on?
EM.run will start an EventMachine reactor. That reactor just loops and loops and loops until you somehow tell it to stop. You can manually stop it using EM.stop.
In your case, you might want to check for the callback results and stop the reactor when both callbacks fired. Ilya's em-http-request library provides a nice interface for exactly that use case. Might be worth a look.

Directing output to stdout in a function without the calling code seeing it

I wrote several Powershell scripts which deploy software for a client. I used Write-Host to output a lot of information so that the progress of the deploy can be watched and they call this from one of their deploy application using Start-Transcript to capture this output.
However, they also need to be able to call some of these scripts from another application which can only capture output from stdout. This means that Write-Host won't work there since it outputs only to the console or host and doesn't get directed to stdout (correct?)
My thought was that I could change the code to use Write-Out instead, except that this causes another problem. Since I use functions and since functions in Powershell "return" everything that goes to stdout to the caller that would likely screw up any of my code that retrieves output from a function.
Is there a way to direct output to stdout from a function without it going to the calling code as the output of the function itself? Here is an example of the problem:
function Test-Output ([int]$number) {
Write-Output "This is a string"
return $number
}
[int]$someNumber = Test-Output 10
$someNumber
If you run the code above you'll see an error because Powershell is trying to assign "This is a string" to the integer $someNumber. If you change the variable to a string then it will capture the full output of the function (This is a string 10) and assign it to the variable.
Thanks for any suggestions that you can give!
Function output and stdout are the same thing so the calling code is going to see anything output to the stdout stream. In this case I would suggest using the Write-Progress cmdlet to report progress to the end user and leave actual function output alone.
Try this.
function Add-Numbers {
param (
[double] $FirstNumber,
[double] $SecondNumber
)
Write-Host "Hello World"
return ($FirstNumber + $SecondNumber)
}
$result = Add-Numbers 1 2
#Write-Host "Result is $result"

How can I print the SQL query executed after Perl's DBI fills in the placeholders?

I'm using Perl's DBI module. I prepare a statement using placeholders, then execute the query.
Is it possible to print out the final query that was executed without manually escaping the parameters and dropping them into the placeholders?
Thanks
See Tracing in DBI. The following works using DBD::SQLite but produces a lot of output:
$dbh->trace($dbh->parse_trace_flags('SQL|1|test'));
Output:
<- prepare('SELECT ... FROM ... WHERE ... = ?')= DBI::st=HASH(0x21ee924) at booklet-excel.pl line 213
<- execute('Inhaler')= '0E0' at booklet-excel.pl line 215
etc etc.
You could plug your own filter in to the trace stream to only keep prepares.
You can do a debug print of a prepared statement using the Statement attribute. This can be accessed either with a "statement handle" or a "database handle".
print $sth->{Statement} # with a statement handle
print $dbh->{Statement} # with a database handle
Not in general, because DBI doesn't necessarily produce such a query. If your database supports prepared statements and placeholders in its API, DBI will pass them through and let the database do the work, which is one of the reasons to use prepared statements.
This works for DBD::mysql with server-side prepare disabled (the default):
$ DBI_TRACE=2 perl your-script-here
It will print each statement twice, once before binding parameters and once after. The latter will be well-formed SQL that you can run yourself.
There is also a module, DBI::Log, which only prints SQL statements (no other debug noise), and optional timing information and caller stacktraces. It's really useful.
If you don't want to create your own tracer module (as suggested by Sinan), you are better off just trying to print the argument hash before it is passed to $sth->execute(). This is especially true, since the "Trace" functionality is DBMS dependent and $sth->{Statement} only returns the SQL placeholder statement. Here's what I did.
...
while (my $row = $csv->getline_hr($fh)) {
my $cval = "";
my $tquery = $query;
foreach my $j (#cols) {
$cval = $row->{$j};
$tquery =~ s/\?/\'$cval\'/;
}
print "$tquery\n\n";
$rc = $sth->execute(#{$row}{#cols});
}
Where I have used Text::CSV...
NOTE: This is not exact, due to DBMS implementation dependent handling of {'}s.
As masto says in general the placeholders in the SQL are not directly replaced with your parameters. The whole point of parameterized SQL is the SQL with placeholders is passed to the database engine to parse once and then it just receives the parameters.
As idssl notes you can obtain the SQL back from the statement or connection handle and you can also retrieve the parameters from ParamValues. If you don't want to do this yourself you can use something like DBIx::Log4perl to log just the SQL and parameters. See DBIX_L4P_LOG_DELAYBINDPARAM which outputs something like this:
DEBUG - prepare(0.1): 'insert into mje values(?,?)'
DEBUG - $execute(0.1) = [{':p1' => 1,':p2' => 'fred'},undef];
Of course as it uses Log::Log4perl you can omit the "DEBUG - " if you want. There is a small tutorial for using DBIx::Log4perl here.
You should be able to use DBIx::Log4perl with any DBD and if you cannot for some reason RT it and I will look at it.
If you don't want to go with DBIx::Log4perl and the DBI trace options don't suit your needs you can write callbacks for DBI's prepare/select*/execute methods and gather whatever you like in them.
For the majority of queries, the simplest debugging is to use the following...
If you prepare and execute a single statement using do method, use:
use feature 'say';
say $dbh->{Statement};
If you use prepare and execute methods separately, use:
use feature 'say';
use Data::Dumper;
$Data::Dumper::Sortkeys = 1;
say $sth->{Statement};
say Dumper($sth->{ParamValues});
For perl neophytes, my solution, copied from not2qubit and simplified/hopefully made a bit more generic/reuseable:
sub dump_query {
my $tquery = shift;
my #args = shift;
my $j;
foreach my $j (#args) { $tquery =~ s/\?/\'$j\'/; }
print STDERR "$tquery\n\n";
}