How to redirect print result from python shell into qtextedit pyqt? - qtextedit

I want my output to appear in my pyqt textedit not python shell after clicking a pushbutton. I am not familiar with subprocess or stdout stuff and not even sure if this will involve them. Need some help here. Here is part of my code:
self.textEdit = QtGui.QTextEdit(Dialog)
self.textEdit.setGeometry(QtCore.QRect(20, 200, 431, 241))
self.textEdit.setObjectName(_fromUtf8("textEdit"))
def readI2C(self):
data = i2c.read_byte(0x50)
return data
self.textEdit.setText(data)
This code does not print anything. I tried it with print data but this prints result in python shell. Anyone can help?

Place this line self.textEdit.setText(data) before return data. Once you return value from method, lines after return will not execute.
Also, if you're going to use textEdit only for output (not for editing) set self.textEdit.setReadOnly(1)

Related

How i can Insert contents of text file with heredoc and variable with ruby

There was a problem when im creating the CLI. I'm want to give the user the opportunity to insert their data into a text file, for this I created a file and added a heredoc to it
I'm trying to get data from a text document that has a heredoc inside of it with a function that is supposed to interpolate
When I try to display the result of the file, I get the entire contents of the file, including the heredoc
an example will be below
I tried to solve my problem through File class
variable_name = File::open("path_directory/file_with_heredoc.txt", "r+")::read
Next, I decided to give the value of the variable to the terminal via
exec("echo #{variable_name}")
The terminal displays
file = <<-EOM
single text with def result: #{upcase_def("Hello")}
EOM
Tried to give through struct, but result is unchanged
exec("echo #{variable_name.strip}")
What do I need to do to get only data, no HEREDOC syntax?
I want to get this result
"single text with def result: HELLO"
I think this is what you are trying to do but I recommend you to first do some research why 'eval() is evil'. If the file is a user (or hacker) input you definitely want some sanitization there or a completely different approach.
def upcase_def(str)
str.upcase
end
data = File.read('file_with_heredoc.txt')
eval(data)
# => " single text with def result: HELLO\n"

Inputting string using (gets.chomp) and producing a histogram

I'm having struggles understanding ruby. I wish to have a program in which a user can input a set of text and it come back with asterisks. So far I was able to do it via a .txt file. Can anyone explain where I went wrong? I am struggling with ruby a lot.
Image of outcome when I run it
print "Please enter any length of text:"
user_input = String(gets.chomp)
h = Hash.new
f = user_input
f.each_line { |line|
letters = line.split(//)
letters.each { |w|
if h.has_key?(w)
h[w] = h[w] + 1
else
h[w] = 1
end
}
}
# sort the hash by
h.sort{|a,b| a[1]<=>b[1]}.each { |elem|
puts "\"#{elem[0]}\": " + '*' * elem[1]
}
Error message I encountered
Undefined method `chomp' for nil:NilClass (NoMethodError)
In the script runner of Atom where you are currently running your Ruby program, you can not read from standard input using gets. It appears that the script-runner package can extend this to provide a real terminal to the script where you can then also use STDIN.
Alternatively, you could also run your program from a real console. For that, you have run it from a command line window, e.g. with ruby name_of_program.rb instead of starting it from Atom.
The gets method must be called alone. Try it in your second line:
user_input = gets.chomp
without String.
I hope it useful for you. :)
Your code is working as intended. You went wrong by running the code in your text editor instead of through the console. The Kernal#gets method requires user input, which would need to be mocked in order to run within your text-editor. Because your editor is returning nil instead of user input in string format, the chomp method is raising your NoMethodError.
Essentially your code is fine, but your are trying to run it in a limited environment. As a beginner, if your code requires user input, it's easier to test the code by running your ruby file through the console/terminal with ruby <filename.rb>.

Updating the tab/file status after saving in a Sublime Text Plugin

This may be an old bug; I found this report. I'm using Sublime 3 but I think this code also works on 2.
When I call self.view.run_command('save') within a plugin, the save does happen -- I can type the file in a console window and see the results. The dirty flag seems to get cleared. But the tab for the file contains a dot rather than an x, indicating the file hasn't been saved. And sure enough, if you try to close it, it asks if you want to save the file.
Is there any way to refresh the file window so it recognizes that the file has been saved?
Here's my plugin code: (This is my first plugin so please excuse obvious style issues)
# Sublime Text plugin to insert output in the OUTPUT_SHOULD_BE comment
# Bind to key with:
# { "keys": ["f12"], "command": "insert_output" },
import sublime, sublime_plugin, pprint, os, re
class InsertOutputCommand(sublime_plugin.TextCommand):
def run(self, edit):
outfile = self.view.file_name().rsplit('.')[0] + ".out"
if not os.path.exists(outfile):
sublime.error_message("Not Found: " + outfile)
return
out_data = open(outfile).read().strip()
region = self.view.find(r"/\* OUTPUT_SHOULD_BE\n", 0)
if region:
self.view.insert(edit, region.end(), out_data)
self.view.run_command('save')
self.view.window().focus_view(self.view)
else:
sublime.error_message("Not Found: OUTPUT_SHOULD_BE")
I'm sure this is probably a terrible hack, but it works:
self.view.run_command("save")
# Refresh the buffer and clear the dirty flag:
sublime.set_timeout(lambda: self.view.run_command("revert"), 10)
The revert command, which must be delayed in order to work, simply brings back whatever is stored in the file. Since the file was successfully saved on disk, this is just the same file that we already see on the screen. In the process, the dirty flag is cleared and the dot on the file tab becomes an x.
Feels very hacky to me and I'd love a more proper solution. But at least it works, ugly or not.

ruby-progressbar and stdout

Suppose I have a method which computes hard problems (maybe a depth-first search in a huge graph), we can call this method dfs(graph).
This method also output to stdout each result reached, using puts result.
def dfs(graph)
while true
# lots of computation
result = something_reached
puts result
end
end
I want to display a progressbar in shell to show that computation is running, so I add an instance like this:
pbar = ProgressBar.create(title: "Computing", starting_at: 1, total: nil)
and progressbar status must be updated (pbar.increment) as computation is running.
In a shell, I execute my program like this:
ruby dfs.rb > dfs_results.txt
Issues:
With pbar is flushed to stdout so prograss-bar is redirected to dfs_results.txt and computation results are not store in this file.
Without pbar result data is stored in file as is expected, but obviously without progress-bar.
I know that results could be stored with File.open usage, but it is desirable done with shell redirections.
Question:
How should I be implemented to flush computation resulta to dfs_results.txt file and show a progress-bar to keep a executing progress for user?
Just open a file to log into:
log = File.open('dfs_results.txt', 'w')
# write into log file
log.write(result)
And your progressbar still writes to stdout. When you open a second screen you can follow the output with:
tails -f dfs_results.txt
Update: Or you can use stdout for the progressbar and stderr for the output of the script. Instead of puts result write:
$stderr.puts results
and start the script with:
ruby dfs.rb 2> dfs_results.txt
I still think the first version is better because results are not errors...

How do I get the output of an Xcode user script to auto indent?

The Problem
I want to press a key when I have a line highlighted and convert from a single line:
JGLogEntry *logEntry = [JGLogEntry applicationNoWindowsFrom:date1 to:date2 intoMOC:mockRawMOC];
to a multiline statement:
JGLogEntry *logEntry = [JGLogEntry applicationNoWindowsFrom:date1
to:date2
intoMOC:mockRawMOC];
What I've Tried
I've got a simple ruby script that almost gets me there.
#!/usr/bin/env ruby
s = STDIN.read
s.gsub!(/(:.+?\w) (\w.+?)/,'\1' + "\n\t" +'\2')
print s
When I set the output to "Replace Selection", I get this:
JGLogEntry *logEntry = [JGLogEntry applicationNoWindowsFrom:date1
to:date2
intoMOC:mockRawMOC];
When I set the output to "Place on Clipboard", then paste it in, I get the desired result:
JGLogEntry *logEntry = [JGLogEntry applicationNoWindowsFrom:date1
to:date2
intoMOC:mockRawMOC];
However, this is two keypresses which is clumsy.
Any ideas how I can get the replaced text to obey Xcode's auto indent rules?
Check the pre-installed script for "Convert tabs to spaces", and how it executes an in-line applescript. Use that to tell XCode to perform the menu item
Edit > Format > Re-Indent
I'm not sure how you do that with ruby, nor the details about the applescript content, but I would wager it's fairly straight-forward..

Resources