Ruby on rails calculating total sum - ruby-on-rails

id
tithe
offertory
pledge
Total
1
120
230
280
???
I have a table like this and I want the total = tithe + offertory + pledge.
how do I write a query for this?

With the use of sum:
Record.where(id: 1).sum('tithe + offertory + pledge')

Related

Ruby aggregate function with model

I have a product model in my ruby on rails application which has name,endorsement and expense attributes.
I need to write a query that list all records, but for every record I need to calculate endorsement-expense as income value. That seems to be ok. However, I need to sum all of the incomes consequtively as well.
For example my records are like these:
Name Endorsement Expense
X 100 25
Y 20 17
X 60 55
T 178 78
I need to list those values as:
Name Endorsement Expense Income Total Income
X 100 25 75 75
Y 20 17 3 78
X 60 55 5 83
T 178 78 100 183
How can I do that ?
Thanks.
rows = Product.select('name,endorsement,expense, (endorsement-expense) as income')
total_income = 0
rows.each do |row|
total_income += row.income
puts "#{row.name}, #{row.endorsement}, #{row.expense}, #{row.income}, #{total_income}"
end
You can also do it with a total income for each product:
products = Product.select("(endorsement - expense) AS 'income', name, endorsement, created_at, null as total")
products.each do |p|
p.total = Product.select("sum(endorsement) - sum(expense) AS 'total'").where(name: p.name).where("created_at <= ?", p.created_at).group('name').last.total
end
You can apply inject function to accumulate total income.
It will look something like this:
products.inject{|sum, product| sum += (product.endorsement - product.expense }

formatting strings in lua in a pattern

I want to make a script that takes any number, counts up to them and returns them in a format.
so like this
for i = 1,9 do
print(i)
end
will return
1
2
3
4
5
6
7
8
9
however I want it to print like this
1 2 3
4 5 6
7 8 9
and I want it to work even with things more than 9 so things like 20 would be like this
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20
I'm sure it can be done using the string library in lua but I am not sure how to use that library.
Any help?
function f(n,per_line)
per_line = per_line or 3
for i = 1,n do
io.write(i,'\t')
if i % per_line == 0 then io.write('\n') end
end
end
f(9)
f(20)
The for loop takes an optional third step:
for i = 1, 9, 3 do
print(string.format("%d %d %d", i, i + 1, i + 2))
end
I can think of 2 ways to do this:
local NUMBER = 20
local str = {}
for i=1,NUMBER-3,3 do
table.insert(str,i.." "..i+1 .." "..i+2)
end
local left = {}
for i=NUMBER-NUMBER%3+1,NUMBER do
table.insert(left,i)
end
str = table.concat(str,"\n").."\n"..table.concat(left," ")
And another one using gsub:
local NUMBER = 20
local str = {}
for i=1,NUMBER do
str[i] = i
end
-- Makes "1 2 3 4 ..."
str = table.concat(str," ")
-- Divides it per 3 numbers
-- "%d+ %d+ %d+" matches 3 numbers divided by spaces
-- (You can replace the spaces (including in concat) with "\t")
-- The (...) capture allows us to get those numbers as %1
-- The "%s?" at the end is to remove any trailing whitespace
-- (Else each line would be "N N N " instead of "N N N")
-- (Using the '?' as the last triplet might not have a space)
-- ^ e.g. NUMBER = 6 would make it end with "4 5 6"
-- The "%1\n" just gets us our numbers back and adds a newline
str = str:gsub("(%d+ %d+ %d+)%s?","%1\n")
print(str)
I've benchmarked both code snippets. The upper one is a tiny bit faster, although the difference is almost nothing:
Benchmarked using 10000 interations
NUMBER 20 20 20 100 100
Upper 256 ms 276 ms 260 ms 1129 ms 1114 ms
Lower 284 ms 280 ms 282 ms 1266 ms 1228 ms
Use a temporary table to contain the values until you print them:
local temp = {}
local cols = 3
for i = 1,9 do
if #temp == cols then
print(table.unpack(temp))
temp = {}
end
temp[#temp + 1] = i
end
--Last minute check for leftovers
if #temp > 0 then
print(table.unpack(temp))
end
temp = nil

Wilson Score in Rails + Add Random Number to Upvote in Postgres Select Statement

I am trying to add a randomized number to my Wilson Score select statement.
My Post model has columns 'upvotes_count' and 'downvotes_count' that get incremented and decremented according to how many upvotes and downvotes they have (duh..).
Post.select("((upvotes_count + 1 + 1.9208) / (upvotes_count + downvotes_count + 2) - " +
"1.96 * SQRT(((upvotes_count + 1) * (downvotes_count + 1)) / (upvotes_count + downvotes_count + 2) + 0.9604) / " +
"(upvotes_count + downvotes_count + 2)) / (1 + 3.8416 / (upvotes_count + downvotes_count + 2)) " +
"AS ci_lower_bound, posts.*")
.order("ci_lower_bound DESC")
Note: In theory, Wilson Score doesn't allow for cases where both upvotes_count and downvotes_count equal 0, so I cheat and add upvote and downvote to each post record. I know this is mathematical "blasphemy" so please don't hurt me math gods. Otherwise, I wouldn't get post records with zero upvotes and zero downvotes...and that sucks.
What would be ideal is to have a select statement that would add a different random number (Poisson preferably) to upvotes_count of each post to give an artificial bump to it's Wilson score so it would occasionally appear higher on the list.
Question: How do I add a different random number to upvotes_count for each post selected in my select statement?
Something like this...but obviously it doesn't work...
Post.select("((upvotes_count + 1 + random + 1.9208) / (upvotes_count + downvotes_count + 2) - " +
"1.96 * SQRT(((upvotes_count + 1 + random) * (downvotes_count + 1)) / (upvotes_count + downvotes_count + 2) + 0.9604) / " +
"(upvotes_count + random + downvotes_count + 2)) / (1 + 3.8416 / (upvotes_count + random + downvotes_count + 2)) " +
"AS ci_lower_bound, posts.*")
This answer may be blasphemy too and I'm not sure I would ever do this, but here's how you could probably do what you're asking
# app/models/post.rb
class Post < ActiveRecord::Base
def self.custom_select_query
select("((upvotes_count + 1 + #{random(100)} + 1.9208) / (upvotes_count + downvotes_count + 2) - " +
"1.96 * SQRT(((upvotes_count + 1 + #{random(99)}) * (downvotes_count + 1)) / (upvotes_count + downvotes_count + 2) + 0.9604) / " +
"(upvotes_count + #{random(98)} + downvotes_count + 2)) / (1 + 3.8416 / (upvotes_count + #{random(97)} + downvotes_count + 2)) " +
"AS ci_lower_bound, posts.*")
end
private
def self.random(max)
SecureRandom.random_number(max)
end
end
Then call it Post.custom_select_query

finding the rth term of a sequence

the question is to give a possible formula for the rth term.
i'm able to solve two questions but rest i can't seems to be of a different way or like weird.as i'm studying alevels i think there's a common rule or maybe an easy way to solve sequence related problems.i never understood sequence well enough-it's just that hard for me.
6 18 54 162
i'm able to solve it by 2*3^r
4 7 12 19
by r^2+3
but
4 12 24 40 60
i'm trying so many ways but i can't find the answer.i think there's a common rule for solving all these not much marks are there so it should be solved in an easy way but i'm not getting how to.please help
Here's a formula in R for the sequence:
g <- function(n) 6*n + 2*n^2 + 4
g(0:4)
[1] 4 12 24 40 60
Here is one way to solve this relation. First, recognize that it is quadratic as the difference is an arithmetic sequence (linear).
Then note that g(x + 1) = g(x) + 8 + 4x. Represent g(x) = a*x^2 + b*x + c.
Then:
g(x+1) = a(x+1)^2 + b(x+1) + c = g(x) + 8 + 4x = a*x^2 + b*x + c + 8 * 4x
ax^2 + 2ax + a + b*x + b + c = a*x^2 + b*x + c + 8 + 4x
Thus
2ax + a +b = 8 + 4x
As this holds for all x, it must be that 2ax = 4x or a = 2. Thus
4x + 2 + b = 8 + 4x
So b = 6. With these known, c is determined by g(0) = c = 4.

If function not working in case of numeric characters

So i have used the following code
If (txtbedroom + txtkitchen + txtbathroom + txtlivingroom + 0) > 9 Or (txtbedroom + txtkitchen + txtbathroom + txtlivingroom + 0) < 7 Then
If MsgBox("Please ensure the number of rooms you entered is entered correctly.", vbYesNo) = vbNo Then
Exit Sub
End If
End If
even if the result of the following is less than 9 and greater than 7 the if function still gets satisfied... what can be done??
Anyway I solved the problem. I used a variable and the code CInt() like x = CInt(txtbedroom) to convert the text to number and then it worked...

Resources