I want to visualize some of my statistical caluclations in Ruby.
My problem is, that I can't find the right gem for that.
rsruby doesn't seem to be up-to-date and I can't install it in Ruby 1.9.2.
Do you know a way how to run the R commands in Ruby?
I just saw this post and thought I should comment since I use R pretty extensively. If you are coming from an R background the best gem I have found is Rinruby. The reason it is fantastic is because you don't interpret the commands in ruby, you use actual R code. For example:
require "rinruby"
#Set all your variables in Ruby
n = 10
beta_0 = 1
beta_1 = 0.25
alpha = 0.05
seed = 23423
R.x = (1..n).entries
#Use actual R code to perform the analysis
R.eval <<EOF
set.seed(#{seed})
y <- #{beta_0} + #{beta_1}*x + rnorm(#{n})
fit <- lm( y ~ x )
est <- round(coef(fit),3)
pvalue <- summary(fit)$coefficients[2,4]
EOF
On the Rinruby website I listed above there are some fantastic examples to get you started. Hope this helped.
-Sean
As #Hansi mentioned, RServe is the best way I've found to run R remotely. If you're using Ruby from a web-context especially, RServe can offer some nice benefits.
Best of all (in my mind), you don't get locked into any one programming framework, as there are RServe clients for a variety of languages including Java and C++. When using web-accessible platforms, you can even keep Rserve running on a separate host and route traffic over TCP/IP for added security.
Related
One of my AppleScripts hasn't been working for a few weeks, so I decided to investigate why. Upon opening it in the Script Editor of OS X, I was kind of surprised to see the code formatted like this. Snippet:
FasdUAS 1.101.10ˇˇˇˇ
k
lˇ˛ˇ˛Get battery level± "Get battery level
ˇ˝
l|ˇ¸ˇ˚
Q|
ˇ˙
ks
r
Iˇ˘ˇ¯
ˇ˘.sysoexecTEXTˇˇÄTEXT
m±Pioreg -w0 -l | grep "\"MaxCapacity\" = "ˇ¯
oˇ˜ˇ˜0maxcapacitymaxCapacity
r
lˇˆˇı
n
4ˇÙ
ˇÙ
cwor
m
ˇÛˇÛˇˇ
oˇÚˇÚ0maxcapacitymaxCapacityˇˆˇı
oˇÒˇÒ0maxlevelmaxLevel
r !
Iˇ"ˇÔ
ˇ.sysoexecTEXTˇˇÄTEXT
As you can see, a lot of weird characters that pretty much make this script impossible to use, and impossible to "fix", syntax-wise.
What can cause something like this to happen and how can I rectify it? It will take me hours to rebuild it manually.
I am trying to learn Julia by repeating some of the easy ProjectEuler problems in Julia. Everything has been really smooth so far, up until I encountered this frustrating problem. I spent some time debugging my code, and here's what I found:
(Hopefully I'm not missing something really stupid here)
function is_abundant(n::Int) #just a function
return prod(map(x->int((x[1]^(x[2]+1)-1)/(x[1]-1)),factor(n))) > 2 * n
end
abundants=[12] #there should be a better way to initialize an Array
for i=13:28120
if is_abundant(i)
push!(abundants,i)
end
end
le=abundants; #The following lines are the problems
ri=abundants;
d=length(abundants)
println(d)
pop!(le)
shift!(ri)
println(le==ri, " ", endof(ri), " ", endof(abundants))
The output I get is:
6964
true 6962 6962
which means that Julia has changed all three sets of le , ri and abundants with each of pop! and shift! commands. I was able to work around this bug/problem by using a dumb extra identity mapping:
le=map(x->x,abundants)
ri=map(x->x,abundants)
Now the output would change to what I initially expected:
6964
false 6963 6964
My question is, if this is not a bug, why is Julia keeping an equivalence relation between le , ri and abundants sets in the first place? Also, can anyone reproduce this behaviour? I am using Julia "Version 0.3.0-rc3+14 (2014-08-13 16:01 UTC)" on Ubuntu 14.04.
le and ri both point to the same list that abundants points to, so this is expected behavior - they are all operating on the same memory. This part of the manual might help you understand. Or possibly the MATLAB differences section, as it is different in MATLAB (but most other languages are like Julia).
For
abundants=[12] #there should be a better way to initialize an Array
how about
abundants = {} # Vector of anything
or
abundants = Int[] # Vector of ints
and instead of your map(x->x,...), you can just use copy.
I know that there are various ways to get random numbers, eg, from the shell. However, I'm running vim on an android phone with very little compiled in. Also, it does not have to be rigorously random. The point is, what's an interesting, or concise, or fast (that is, with vim native functions), or short way to get a sequence of reasonably good random numbers in Vim?
Try something like
function Rand()
return str2nr(matchstr(reltimestr(reltime()), '\v\.#<=\d+')[1:])
endfunction
. I know no better option then using some of the time functions (there are two of them: reltime() and localtime(), but the latter is updated only each second). I would prefer to either avoid random numbers or use pyeval('random.randint(1, 10)') (preceded by python import random), because shell is slow and I don’t trust time-based solutions.
Note: documentation says that format of the item returned by reltime() depends on the system, thus I am using reltimestr(), not doing something with reltime()[1] which looks like if it contains nanoseconds.
I've recently played around with random numbers in Vim script myself. Here are some resources that I found in the process.
No Vim script
By all means, use an external random number generator if you can. As a rule, they are better and faster than anything that could be done in Vim script.
For example, try
:python import random; print random.randrange(1, 7)
:echo system('echo $RANDOM')
another scripting language, for example Ruby
Libraries
Vim script libraries. These hopefully strive to provide decent quality RNG implementations.
vital.vim is an excellent and comprehensive library created by the vim-jp user group. Their random number generator sports an impressive array of functionality and is the best pure Vim script RNG I know of. vital.vim uses an Xorshift algorithm. Check it out!
Rolling a die with vital.vim:
let Random = vital#of('vital').import('Random')
echo Random.range(1, 7)
vim-rng is a small random number generator plugin. It exports a couple of global functions that rely on a multiply-with-carry algorithm. This project seems to be a work in progress.
Rolling a die with rng:
echo RandomNumber(1, 6)
magnum.vim is my own little big integer library. I've recently added a random number generator that generates integers of any size. It uses the XORSHIFT-ADD algorithm.
Rolling a die with magnum.vim:
let six = magnum#Int(6)
echo magnum#random#NextInt(six).Add(magnum#ONE).Number()
Rndm has been around for much longer than the other libraries. Its functionality is exposed as a couple of global functions. Rolling a die with Rndm:
echo Urndm(1, 6)
Discussion and snippets
Finally, a few links to insightful discussion and Vim script snippets.
ZyX's reltime snippet on this page.
loreb's vimprng project on GitHub has an impressive number of RNG implementations in Vim script. Very useful.
This old mailing list discussion has a couple of Vim script snippets. The first one given by Bee-9 is limited to 16 bit but I found it quite effective. Here it is:
let g:rnd = localtime() % 0x10000
function! Random(n) abort
let g:rnd = (g:rnd * 31421 + 6927) % 0x10000
return g:rnd * a:n / 0x10000
endfunction
Another script, found in a person named Bart's personal config files.
Episode 57 on Vimcasts.org discusses Vim's 'expression register' and refers to random number examples throughout. Refers to this Stackoverflow question and ZyX's snippet. Recommended.
The Vim wiki on wikia has an article 'Jump to a random line' that has a few resources not mentioned yet.
Based on others' answers and other resources from the internet, I have written
two functions to generate a random integer in the given range [Low, High].
Both the two functions receive two arguments: Low and High and return a
random number in this range.
Combine Python and Vim script
The first function combines Python and Vim script.
" generate a random integer from range [Low, High] using Python
function! RandInt(Low, High) abort
" if you use Python 3, the python block should start with `python3` instead of
" `python`, see https://github.com/neovim/neovim/issues/9927
python3 << EOF
import vim
import random
# using vim.eval to import variable outside Python script to python
idx = random.randint(int(vim.eval('a:Low')), int(vim.eval('a:High')))
# using vim.command to export variable inside Python script to vim script so
# we can return its value in vim script
vim.command("let index = {}".format(idx))
EOF
return index
endfunction
Pure Vim script
The second function I propose uses pure vim script:
function! RandInt(Low, High) abort
let l:milisec = str2nr(matchstr(reltimestr(reltime()), '\v\.\zs\d+'))
return l:milisec % (a:High - a:Low + 1) + a:Low
endfunction
Use luaeval() (Neovim only)
The third way to generate random number is to use lua via luaeval().
" math.randomseed() is need to make the random() function generate different numbers
" on each use. Otherwise, the first number it generate seems same all the time.
luaeval('math.randomseed(os.time())')
let num = luaeval('math.random(1, 10)')
If you want to generate random number in non-serious occasions, you may use the
these methods as a starter.
I’m updating an old Perl script to Ruby and having a problem with finding a replacement for one Perl library.
In the Perl script we use Net::CIDR::Lite, which takes a start and end ip address range and outputs a CIDR string.
This is a Perl example that shows the functionality:
#!/usr/bin/perl
use Net::CIDR::Lite;
$cidrblocks = Net::CIDR::Lite->new;
$cidrblocks->add_range("109.152.0.0-109.152.7.255");
$coveragezone = "";
#cidrlist = $cidrblocks->list();
$cidrcount=0;
while ( defined $cidrlist[$cidrcount] ) {
$coveragezone .= "$cidrlist[$cidrcount]";
}
continue {
$cidrcount++;
}
print "$coveragezone";
This script returns a string:
=> 109.152.0.0/21
Does anyone know of a Ruby lib or gem I could use to duplicate the functionality of the add_range call?
$cidrblocks = Net::CIDR::Lite->new;
$cidrblocks->add_range("109.152.0.0-109.152.7.255");
You can either use the built-in IPAddr class which also handles CIDR networks, or you use the ipaddress gem which provides some additional helpers.
A simple example would be:
cidrblocks = []
cidrblocks << IPAddr.new("109.152.0.0/21")
included = cidrblocks.find{|net| net.include?("109.152.6.123") }
I prefer the NetAddr gem, in particular its NetAddr::CIDR class.
It's a very rich IPv4/IPv6 gem.
Looking through the three modules I know of, Ruby's built-in IPAddr, NetAddr and IPAddress, mentioned by #holgerjust, none of them give us the ability to supply a start IP and end IP and return the resulting network. They all assume a CIDR form of the network, and then work toward testing the individual IPs to see if they fit into the subnet, or using that subnet definition to generate the IPs themselves.
I found a ruby module which does this translation see
http://wejn.org/stuff/cidr.rb.html
have included it in my rails app and it's perfect
Can't find a suitable gem?
Do what comes naturally - reimpliment the Perl module in Ruby.
While this may not be entirely relevant to your question, I ported part of CIDR::Lite to Ruby:
https://github.com/noahhaon/cidr-lite-ruby
I found its performance to be far better than the available ruby alternatives at the time for merging very large sets of overlapping CIDRs.
HTH
I'm trying to make a rouguelike game that runs inside a terminal using Ruby but I'm not exactly sure how to go about doing that. I want to be able to address and update each cell in the standard 80*24 terminal window individually. Can I do this with the standard library or alternately are there any good gems I could do this with?
Curses is probably the easiest to implement and it is widely available across platforms. Ruby bindings used to come as part of the standard library, but it's now a gem: gem install curses. Here's an example from the docs:
require "curses"
def show_message(message)
height = 5
width = message.length + 6
top = (Curses.lines - height) / 2
left = (Curses.cols - width) / 2
win = Curses::Window.new(height, width, top, left)
win.box("|", "-")
win.setpos(2, 3)
win.addstr(message)
win.refresh
win.getch
win.close
end
Curses.init_screen
begin
Curses.crmode
Curses.setpos((Curses.lines - 1) / 2, (Curses.cols - 11) / 2)
Curses.addstr("Hit any key")
Curses.refresh
Curses.getch
show_message("Hello, World!")
ensure
Curses.close_screen
end
You can use Gosu.
You can find more alternatives in ruby toolbox - game libraries.
I'm assuming you're using a linux. For manipulating the terminal you will need the ncurses library bindings for Ruby. See ncurses-ruby.
The documentation is sparse, but there are plenty of examples at this github repository.