Error accessing data from an array in ruby ​on rails - html

The error tells me that the method '[]' is not defined in the line 127
this is my code and Idon't see the error
def verificar_area archivo
bandera= false
Spreadsheet.client_encoding = 'UTF-8'
book = Spreadsheet.open archivo
#wk = book.worksheet 0
areas = ["Secundaria",
"Preparatoria",
"Universitario",
"Edad 11 a 15 años",
"Edad de 16 a 19 años",
"Solo estudian",
"Adolescentes que trabajan y estudian"]
(1 .. #wk.row_count).each do |index_renglon|
#renglon_excel = #wk.rows[index_renglon]
area=#renglon_excel[8] #This is the line 127
if areas.include?(area)
bandera=true
else
bandera=false
break
end #fin if
end #fin for
return bandera
end
the error in the browser is this

You are getting the error because #renglon_excel is nil for that specific iteration
#renglon_excel[8]
And you are trying to access with index of [8] on nil
To avoid this you can add a check
#renglon_excel = #wk.rows[index_renglon]
next unless #renglon_excel
area = #renglon_excel[8]

Related

Run Octave function form shell

It is possible to write a function directly in the octave shell?
A=147;
B=26.3;
C=5.4;
d=0.35*A;
function S=function_test(A,B,C,d)
S=2*A*B*C*d;
end
I tried this but if I wanted to know the value of "S", this error appears:
error: 'S' undefined near line 1, column 1
Yes it is possible. You does it correctly. But you missed indicating how you call the function. For me, no error occurs:
≫ function_test(1,2,3,4)
ans = 48
≫ res = function_test(1,2,3,4)
res = 48
≫ S = function_test(-1,3,5,7)
S = -210
≫

809: unexpected token at '' (JSON parser error ruby3.0.4 mac os catalina

I have just started learning ruby and trying to learn extracting web data. I am using samplewebapp code given in a sites API documentation
On executing the test.rb file as given below it generates a token.
The token.json file contains the following
{"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIzY2U1NjFhMC01ZmE5LTQ5NjUtYTQ2Mi01NmI2MzEzNjRlZGMiLCJqdGkiOiJmMjc0ZTgwM2FmZjVlMTFiMTAzNzIwMzAwNzRlNDRhZDE3ODg3ZjAzOGQ2ODk0OWIwNzVkMmQ5N2E2MjAwYzc5ZWRhNzU4MmQ3MTg1MTc1YiIsImlhdCI6MTY1NDU2OTc0MS41MjgxNTUsIm5iZiI6MTY1NDU2OTc0MS41MjgxNTcsImV4cCI6MTY1NDU3MzM0MS41MjgwMzksInN1YiI6IjE5NGFlNTU5LTU5OWMtNDQ2ZC1hOTRhLWM2MTIyYjZkMTA2ZiIsInNjb3BlcyI6W10sImNyZWRpdHNfcmVtYWluaW5nIjo0NzAwLCJyYXRlX2xpbWl0cyI6W3sicmF0ZSI6NSwiaW50ZXJ2YWwiOjYwfV19.XoN5A-H8Z7d8p_0e2rCcyV4yWO9MAF3TZlHk5VP5NjUEqtTXTVYKfKuzidYDs7K8ZzAtWzyt3aR5VSUG0_nw-uPd7Z3_Y75alQMqa2b5rHGn5JFWH7nuAriskr26WSCqAdj4cNjccPORryRr5sYKwpE4Y4kTG0IX_8frvwYxwp-8wFpLLj98K3axwN7CCpWdnPDSzuMqmH6tSpF0XhdYxB5LTVH0AyH7lN0S0_Lftq0b3sOLIvEaTfNkuRGNqwLkBYFkHFuPqwrKd8RJhC2W1QZhrmUw3eYnh-0iQABGk2V0skIqDlb6BbQ5GFX6MXgiXAc-h5Ndda7pZ5N5UCQU3g","expires_at":1654573341}
However it also generates a JSON parser error as under
/Users/mm/.rbenv/versions/3.0.4/lib/ruby/3.0.0/json/common.rb:216:in `parse': 809: unexpected token at '' (JSON::ParserError)
from /Users/mm/.rbenv/versions/3.0.4/lib/ruby/3.0.0/json/common.rb:216:in `parse'
from /Users/mm/Desktop/prokerala/client.rb:21:in `parseResponse'
from /Users/mm/Desktop/prokerala/client.rb:99:in `get'
I googled around for a while and some of the responses talk about the issues between double and single quotes.. I tried changing those also but it doesn't work.
I have also tried running it with system ruby - which gives a different error
Would appreciate very much if someone could explain what the error is / logic behind this.. Also I am not clear about the error message itself. The message talks about parse error 809:"unexpected token" on column no 809 of the token there is nothing.. Am i reading it wrong?
code used in test.rb file
client = ApiClient.new('YOUR CLIENT_ID', 'YOUR CLIENT_SECRET');
result = client.get('v2/astrology/thirumana-porutham/advanced', {
:girl_nakshatra => 4,
:girl_nakshatra_pada => 2,
:boy_nakshatra => 26,
:boy_nakshatra_pada => 3
})
puts JSON.pretty_generate(result)
code used in client.rb file
require 'net/http'
require 'json'
class ApiError < StandardError
end
class ApiClient
BASE_URL = "https://api.prokerala.com/"
# Make sure that the following file path is set to a location that is not publicly accessible
TOKEN_FILE = "./token.json"
def initialize(clientId, clientSecret)
# Instance variables
#clientId = clientId
#clientSecret = clientSecret
end
def parseResponse(response)
content = response.body
res = JSON.parse(content)
if res.key?('access_token')
return res
end
if res['status'] == "error"
raise ApiError, res['errors'].map {|e| e['detail']}.join("\n")
end
if res['status'] != "ok"
raise "HTTP request failed"
end
return res
end
def saveToken(token)
# Cache the token until it expires.
File.open(ApiClient::TOKEN_FILE,"w") do |f|
token = {
:access_token => token['access_token'],
:expires_at => Time.now.to_i + token['expires_in']
}
f.write(token.to_json)
end
end
def getTokenFromCache
if not File.file?(ApiClient::TOKEN_FILE)
return nil
end
begin
# Fetch the cached token, and return if not expired
text = File.read(ApiClient::TOKEN_FILE)
token = JSON.parse(text)
if token['expires_at'] < Time.now.to_i
return nil
end
return token['access_token']
rescue JSON::ParserError
return nil
end
end
def fetchNewToken
params = {
:grant_type => 'client_credentials',
:client_id => #clientId,
:client_secret => #clientSecret
}
res = Net::HTTP.post_form(URI(ApiClient::BASE_URL + 'token'), params)
token = parseResponse(res)
saveToken(token)
return token['access_token']
end
def get(endpoint, params)
# Try to fetch the access token from cache
token = getTokenFromCache
# If failed, request new token
token ||= fetchNewToken
uri = URI(ApiClient::BASE_URL + endpoint)
uri.query = URI.encode_www_form(params)
req = Net::HTTP::Get.new(uri.to_s, {'Authorization' => 'Bearer ' + token})
res = Net::HTTP.start(uri.hostname) do |http|
http.request(req)
end
return parseResponse(res)
end
end
running the test file using ruby 3.0.4 gives the a JSON parse error. Full error reproduced as below
/Users/mm/.rbenv/versions/3.0.4/lib/ruby/3.0.0/json/common.rb:216:in `parse': 809: unexpected token at '' (JSON::ParserError)
from /Users/mm/.rbenv/versions/3.0.4/lib/ruby/3.0.0/json/common.rb:216:in `parse'
from /Users/mm/Desktop/prokerala/client.rb:21:in `parseResponse'
from /Users/mm/Desktop/prokerala/client.rb:99:in `get'
from test.rb:11:in `<main>'
I executed the above code and from this, we are getting
#<Net::HTTPMovedPermanently 301 Moved Permanently readbody=true> as response
and response body as empty string '', which results in error in parsing the body.
Since, API endpoint is secure with https, we need set use_ssl: true before starting the session. Try below code and it will fix the issue.
res = Net::HTTP.start(uri.hostname, use_ssl: true) do |http|
http.request(req)
end

How to throw a specific Exception in Julia

I am doing test driven development in Julia.
The test expects a certain exception to be thrown.
How do I throw the expected exception?
I'm looping through a string and counting the occurrence of specific letters.
Any letter than 'A','C','G',or'T' should result in an exception
Running Julia version 1.2.0.
I have tried these alternatives:
throw(DomainError())
throw(DomainError)
throw("DomainError")
I expected those to work based on this resource:
https://scls.gitbooks.io/ljthw/content/_chapters/11-ex8.html
Here is a link to the problem I am trying to solve:
https://exercism.io/my/solutions/781af1c1f9e2448cac57c0707aced90f
(Heads up: That link may be unique to my login)
My code:
function count_nucleotides(strand::AbstractString)
Counts = Dict()
Counts['A'] = 0
Counts['C'] = 0
Counts['G'] = 0
Counts['T'] = 0
for ch in strand
# println(ch)
if ch=='A'
Counts['A'] += 1
# Counts['A'] = Counts['A'] + 1
elseif ch=='C'
Counts['C'] += 1
elseif ch=='G'
Counts['G'] += 1
elseif ch=='T'
Counts['T'] += 1
else
throw(DomainError())
end
end
return Counts
end
The test:
#testset "strand with invalid nucleotides" begin
#test_throws DomainError count_nucleotides("AGXXACT")
end
My error report, see the lines with: Expected and Thrown.
strand with invalid nucleotides: Test Failed at /Users/username/Exercism/julia/nucleotide-count/runtests.jl:18
Expression: count_nucleotides("AGXXACT")
Expected: DomainError
Thrown: MethodError
Stacktrace:
[1] top-level scope at /Users/shane/Exercism/julia/nucleotide-count/runtests.jl:18
[2] top-level scope at /Users/juliainstall/buildbot/worker/package_macos64/build/usr/share/julia/stdlib/v1.2/Test/src/Test.jl:1113
[3] top-level scope at /Users/username/Exercism/julia/nucleotide-count/runtests.jl:18
Test Summary: | Fail Total
strand with invalid nucleotides | 1 1
ERROR: LoadError: Some tests did not pass: 0 passed, 1 failed, 0 errored, 0 broken.
The MethodError comes from the call to DomainError -- there are no zero-argument constructor for this exception type. From the docs:
help?> DomainError
DomainError(val)
DomainError(val, msg)
The argument val to a function or constructor is outside the valid domain.
So there are one constructor which takes the value that was out of the domain, and one that, in addition, takes an extra message string. You could e.g. do
throw(DomainError(ch))
or
throw(DomainError(ch, "this character is bad"))

Octave Get line number of error

The error I'm getting is not very descriptive, it will tell me
error: gradientDescent: product: nonconformant arguments (op1 is 1x97, op2 is 97x2)
I know the file is gradientDescent.m, but is there a way to get the line number of the error?
lasterror() contains a stack trace.
In my application, I'm getting the message "error: plot: properties must appear followed by a value", with no line number.
After I get the prompt back, I can example the stack trace like this:
octave:23> lasterror().stack
ans =
6x1 struct array containing the fields:
file
name
line
column
scope
context
octave:24> lasterror().stack.file
ans = /usr/share/octave/4.2.2/m/plot/draw/private/__plt__.m
ans = /usr/share/octave/4.2.2/m/plot/draw/plot.m
ans = /home/baccala/WAM/waveletauditory/SOM-Toolbox/som/vis_trajgui.m
ans = /home/baccala/WAM/waveletauditory/SOM-Toolbox/som/vis_trajgui.m
ans = /home/baccala/WAM/waveletauditory/SOM-Toolbox/som/vis_trajgui.m
ans = /home/baccala/WAM/waveletauditory/SOM-Toolbox/som/vis_trajgui.m
octave:25> lasterror().stack.line
ans = 96
ans = 223
ans = 616
ans = 567
ans = 548
ans = 253
octave:26>
Which tells me that the troublesome call to plot in on line 616 of vis_trajgui.m.

HTTParty and JSON memory leak?

I've been having a hard time debugging the memory leak.
I have paging using HTTParty inside Sidekiq, and the memory is keep growing and growing. I profiled the sidekiq and this is what I found:
540 /home/user/.rvm/gems/ruby-2.2.3/gems/aws-sdk-core-2.4.2/lib/seahorse/client/configuration.rb:157:DATA
540 /home/user/.rvm/gems/ruby-2.2.3/gems/aws-sdk-core-2.4.2/lib/seahorse/client/configuration.rb:157:NODE
609 /home/user/.rvm/gems/ruby-2.2.3/gems/activesupport-4.1.14/lib/active_support/core_ext/class/attribute.rb:86:DATA
1376 /home/user/.rvm/gems/ruby-2.2.3/gems/activerecord-4.1.14/lib/active_record/connection_adapters/postgresql/database_statements.rb:148:STRING
1712 /home/user/.rvm/gems/ruby-2.2.3/gems/activesupport-4.1.14/lib/active_support/dependencies.rb:247:ARRAY
1713 /home/user/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/set.rb:290:STRING
1964 /home/user/.rvm/gems/ruby-2.2.3/gems/mime-types-3.1/lib/mime/types/_columnar.rb:29:OBJECT
1964 /home/user/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/set.rb:72:OBJECT
2572 /home/user/.rvm/gems/ruby-2.2.3/gems/mime-types-3.1/lib/mime/types/_columnar.rb:24:STRING
2987 /home/user/.rvm/gems/ruby-2.2.3/gems/activesupport-4.1.14/lib/active_support/dependencies.rb:247:NODE
3126 /home/user/.rvm/gems/ruby-2.2.3/gems/mime-types-3.1/lib/mime/types/container.rb:10:OBJECT
3506 /home/user/.rvm/gems/ruby-2.2.3/gems/activesupport-4.1.14/lib/active_support/dependencies.rb:247:DATA
3928 /home/user/.rvm/gems/ruby-2.2.3/gems/mime-types-3.1/lib/mime/type.rb:532:STRING
3928 /home/user/.rvm/gems/ruby-2.2.3/gems/mime-types-3.1/lib/mime/type.rb:543:STRING
5175 /home/user/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/set.rb:81:HASH
5234 /home/user/.rvm/gems/ruby-2.2.3/gems/activesupport-4.1.14/lib/active_support/dependencies.rb:247:STRING
5892 /home/user/.rvm/gems/ruby-2.2.3/gems/mime-types-3.1/lib/mime/type.rb:546:STRING
8120 /home/user/.rvm/gems/ruby-2.2.3/gems/json-1.8.3/lib/json/common.rb:155:ARRAY
87403 /home/user/.rvm/gems/ruby-2.2.3/gems/json-1.8.3/lib/json/common.rb:155:HASH
541817 /home/user/.rvm/gems/ruby-2.2.3/gems/json-1.8.3/lib/json/common.rb:155:STRING
Notice the json STRING and HASH. These bottom 2 just keeps growing as the sidekiq keeps on running more and more jobs.
The code is this:
...
begin
reactions = HTTParty.get("https://graph.facebook.com/v2.7/#{vid.external_id}/reactions?summary=true&limit=#{PAGE_SIZE}&access_token=#{ENV['at']}")
rescue Exception => ex
return
end
r_last_id = "vl/programs/#{vid.program_id}/vids/#{vid.id}/reactions/last_id"
r_last_entry_idx = "vl/programs/#{vid.program_id}/vids/#{vid.id}/reactions/last_entry_idx"
reactions_purged = []
abort = false
total_records = reactions['summary']['total_count'] || 0
last_total_count = $redis.get(r_last_entry_idx).to_i
need_to_run = total_records - last_total_count
need_to_run = 0 if need_to_run < 0
last_id = nil
loop do
break if reactions['data'].nil? || reactions['data'].empty?
reactions['data'].each do |r|
last_id = $redis.get(r_last_id)
abort = true and break if !last_id.nil? && need_to_run <= 0
need_to_run -= 1
reactions_purged << r
end
GC.start # <----- Even this didnt solve it
break if abort
break if reactions['paging']['next'].nil?
reactions = HTTParty.get(reactions['paging']['next'])
end
...
Even the GC.start I added as you see, didn't solve it.
What causes this JSON leakage? this is coming from HTTParty...
Thanks