Error: Can't Assign Function Call / Don't want to - arrays

It's friday and I'm tired and my brain obvs doesn't want to find this answer. Please help.
I want to assign the value to an array. It works in subsequent lines but not in one particular line, even though syntax seems the same to me? It seems to think I'm calling a function??
for entry in PROJECT:
i = i + 1
#A
if entry.startswith("A") :
ProjectA(i) = entry
#B
elif entry.startswith("B"):
ProjectB(i)= entry
#C
elif entry.startswith("C") :
ProjectC(i) = entry
# and Programme
elif entry.startswith("D") :
ProjectD(i) = entry
I'm told the problem is the last line: "ProjectD(i) = entry". Which to me seems like a replica of "ProjectC(i) = entry"

ProjectA(i) looks like you are calling a function; ProjectA[i] looks like an array element.

Related

lapply calling .csv for changes in a parameter

Good afternoon
I am currently trying to pull some data from pushshift but I am maxing out at 100 posts. Below is the code for pulling one day that works great.
testdata1<-getPushshiftData(postType = "submission", size = 1000, before = "1546300800", after= "1546200800", subreddit = "mysubreddit", nest_level = 1)
I have a list of Universal Time Codes for the beginning and ending of each day for a month. What I would like to do is get the syntax to replace the "after" and "before" values for each day and for each day to be added to the end of the pulled data. Even if it placed the data to a bunch of separate smaller datasets I could work with it.
Here is my (feeble) attempt. "links" is the data frame with the UTCs
mydata<- lapply(1:30, function(x) getPushshiftData(postType = "submission", size = 1000, after= links$utcstart[,x],before = links$utcendstart[,x], subreddit = "mysubreddit", nest_level = 1))
Here is the error message I get: Error in links$utcstart[, x] : incorrect number of dimensions
I've also tried without the "function (x)" argument and get the following message:
Error in ifelse(is.null(after), "", sprintf("&after=%s", after)) :
object 'x' not found
Can anyone help with this?

How could I do the sum of all values of a nested hash?

I have a nested hash like this
Aranea={
"Aranéomorphes"=>{
"Agelenidae"=>[80,1327],
"Amaurobiidae"=>[49,270],
"Ammoxenidae"=>[4,18],
"Anapidae"=>[58,233],
"Anyphaenidae"=>[56,572],
"Araneidae"=>[175,3074],
"Archaeidae"=>[5,90],
"Arkydiae"=>[2,38],
"Austrochilidae"=>[3,10],
"Caponiidae"=>[18,119],
"Cheiracanthiidae"=>[12,353],
"Cithaeronidae"=>[2,8],
"Clubionidae"=>[16,639],
"Corinnidae"=>[68,489],
"Ctenidae"=>[48,519],......
For each key (spiders families), the array represents [number of genders, number of species].
Iwould like to get the sum of all first elements....i.e all the genders in total....
I tried different things without success like :
genre = []
#total = genre.transpose.map {|x| x.reduce(:+)}
Or....
def sum_deeply(h)
h.values.inject(0) { |m, v|
m + (Hash === v[0] ? sum_deeply(v[0]) : v[0].to_i)
}
end
puts sum_deeply(Aranea)
But none does work for with transpose I get a no implicit conversion error...
Could anyone enligthen me on this ? Thanks
!!! Update.... 08.07.2020... solution found with
families = Aranea
num_genders = families.flat_map do |_family_name, species_hash|
num_genders, _num_species = species_hash.values.transpose
num_genders
Thanks to Kache for his help on this.
This should do what you want:
families = Aranea
num_genders = families.flat_map do |_family_name, species_hash|
num_genders, _num_species = species_hash.values.transpose
num_genders
end
num_genders.inject(:+)
Just a tip: splitting out the "data extraction" and "data processing" (i.e. accessing the num_genders value vs summing them) will make your code easier to follow.
I don't think there'll be any part of the above that you won't understand, but if there is, just let me know what parts you'd like to have explained.

How to create a for loop when the variable is in a sentence?

I want to create a for loop when the variable is in a string format.
my code is:
for i in range(1,32):
DEP_RATE = pd.read_sql_query('select DAYNUM,YYYYMM,sum(DEP_RATE) from ASPM.aspm_qtr where LOCID="ABQ" and DAYNUM = i:"{i}" group by YYYYMM',{i:str(i)},rconn)
the error is:
'dict' object has no attribute 'cursor'
I used this code:
for i in range(1,32):
DEP_RATE = pd.read_sql_query('select DAYNUM,YYYYMM,sum(DEP_RATE) from ASPM.aspm_qtr where LOCID="ABQ" and DAYNUM = "i" group by YYYYMM',rconn, params={i:str(i)})
It hasn't error but doesn't work. the problem is:
("Truncated incorrect DOUBLE value: 'i'")
This appears to be a PANDAS question, yes? I believe it's an argument mismatch with the read_sql_query API. The function signature is:
pandas.read_sql_query(sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, chunksize=None)
Which roughly says that the first two positional arguments are required, and everything else is defaulted or optional.
To make it more obvious, consider putting your core SQL string on a separate line:
sql = 'SELECT daynum, ... AND daynum = :i'
for i in range(1, 32):
DEP_RATE = pd.read_sql_query(sql, {i: str(i)}, rconn)
With this formulation, it's more obvious that your arguments do not match the API: your second argument is off. Perhaps you want (note the additional keyword argument params):
DEP_RATE = pd.read_sql_query(sql, rconn, params={i: str(i)})
I corrected the code. The correct answer is:
DEP_RATE = list(np.zeros((1,1)))*31
for i in range(1,32):
DEP_RATE[i-1] =np.array(pd.read_sql_query('select DAYNUM,YYYYMM,sum(DEP_RATE) from ASPM.aspm_qtr where LOCID="ABQ" and DAYNUM = '+str(i)+' group by YYYYMM;',rconn, params={i:str(i)}))

Trying to define a function with a loop in ruby, and I'm getting an error where there isn't a function

I wrote a program to extract all (over 1000) the comments from a reddit post, and I'm having trouble defining a function.
The program:
require "rubygems"
require "json"
require "net/http"
require "uri"
require 'open-uri'
require 'neatjson'
#The URL, which changes.
url = ("https://www.reddit.com/r/AskReddit/comments/46n0zc.json")
#Sets up the JSON reader.
result = JSON.parse(open(url).read)
post = result[0]["data"]["children"]
children = result[1]["data"]["children"]
#Sets up the base location.
base = ("https://www.reddit.com" + post[0]["data"]["permalink"].to_s)
#Sets up the arrays.
mainIDs = Array.new
reIDs = Array.new
#Collects the main jsons.
children.each do |child|
if child["data"].has_key? "body"
mainIDs.push(child["data"]["id"].to_s)
end
end
mainINT = mainIDs.count
#Collects the remaining.
children.each do |child|
if child["data"].has_key? "children"
reIDs = child["data"]["children"]
end
end
remainINT = reIDs.count
puts "Main Comments: " + mainINT.to_s
puts "Total Comments: " + (mainINT + remainINT).to_s
#Divides the page.
puts ("__" * 50)
puts ("\n")
#Creates a function for collection.
def printAllComments(array, comINT)
for i in array do i
url = base + i
puts "Post URL: " + url
result = JSON.parse(open(url).read)
children = result[1]["data"]["children"]
int = comINT
for i in children do child
if child["data"].has_key? "body"
puts "Comment Number: " + int.to_s
puts "Author: " + child["data"]["author"]
puts "Body: " + neatBD(child["data"]["body"].to_s)
puts "ID: " + child["data"]["id"]
puts "Ups: " + child["data"]["ups"].to_s
puts "\n\n"
int += 1
end
end
end
end
printAllComments(mainINT, 1)
The "Creates a function for collection" is where the error is. When I run this, I get:
Main Comments: 64
Total Comments: 1676
____________________________________________________________________________________________________
007----extractallredditpostcomments.rb:51:in `printAllComments': undefined method `each' for 64:Fixnum (NoMethodError)
from 007----extractallredditpostcomments.rb:72:in `<main>'
When I should be getting the first 64 comments from the main array, instead it just breaks after it prints the line. What's weird is that the error is on line 51, and line 51 is the:
url = base + i
there's no 'each' function there.
What am I missing?
for i in array do is equivalent to array.each do |i|. If array is not, actually, an array, you will get the error you are getting. Proof:
for i in 64 do puts i end
# NoMethodError: undefined method `each' for 64:Fixnum
Stylistically... no Rubyist uses for; everyone uses each directly.
so there are a couple items that I would point out.
First the loop syntax feels a bit funny. If you want to access each element of the array I would use array.each do |item|, same of the inner loop children.each do |child|.
Next you are actually passing the mainINT instead of mainIDs which is an int, not an array. This is what was throwing the error you asked about.
Lastly you are trying to reference base from within your method but it doesn't exist within the method's scope, try passing it into the method or making the variable global with #base.
Changing these few items I was able to get one URL to print out and then ran into an issue with parsing the JSON but I will leave that to you. This should hopefully get you moving forward.
Patrick

Multiple outputs with a for loop in praat

I have a script where I have multiple folders each with three audio files in them ID#_1, ID#_2, and ID#_3. The user can input a string of different ID#s, one after the other, and then the script recognizes the different IDs and runs the code for each of them.
I have a for loop set up for this -
form Settings
comment Enter the IDs of the different subjects
sentence subjectIDs
endform
numOfSubjects = length(subjectIDs$)/4
for i from 0 to (numOfSubjects - 1)
subjectID$ = mid$(subjectIDs$, 1 + 4*i, 4 + 4*i)
outFile$ = subjectID$ + "/SubjectResponseOnsets" + subjectID$ + ".txt"
path$ = subjectID$ + "/" + subjectID$
#firstOutput
#secondOutput
#thirdOutput'
Each of these procedures is defined previously in the code, and they basically output certain ranges from the audio files out to a text file.
The code seems to work fine and generate the output file correctly when one ID is given, but when I try to run it with more than one ID at a time, only the text file for the first ID is outputted.
The for loop does not seem to be working well, but the code does work fine in the first run.
I would greatly appreciate any help!
I don't know if I understood well what your script was trying to do, since the snippet you pasted was incomplete. It's best if you provide code that is executable as is. In this case, you were missing the closing endfor, and you were calling some procedures that were not defined in your snippet (not even as placeholders). I had to write some dummy procedures just to make it run.
Since you also didn't say how your script was failing, it was unclear what needed to be fixed. So I took a stab at making it work.
It sounded as if your ID splitting code was giving you some problems. I took the split procedure from the utils plugin available through CPrAN, which makes inputting the IDs easier (full disclosure: I wrote that plugin).
form Settings
comment Enter the IDs of the different subjects
sentence subjectIDs 01 02 03
endform
#split: " ", subjectIDs$
numOfSubjects = split.length
for i to numOfSubjects
subjectID$ = split.return$[i]
path$ = subjectID$
outFile$ = path$ + "/SubjectResponseOnsets" + subjectID$ + ".txt"
# Make sure output directory exists
createDirectory: path$
#firstOutput
#secondOutput
#thirdOutput
endfor
procedure firstOutput ()
appendFileLine: outFile$, "First"
endproc
procedure secondOutput ()
appendFileLine: outFile$, "Second"
endproc
procedure thirdOutput ()
appendFileLine: outFile$, "Third"
endproc
# split procedure from the utils CPrAN plugin
# http://cpran.net/plugins/utils
procedure split (.sep$, .str$)
.seplen = length(.sep$)
.length = 0
repeat
.strlen = length(.str$)
.sep = index(.str$, .sep$)
if .sep > 0
.part$ = left$(.str$, .sep-1)
.str$ = mid$(.str$, .sep+.seplen, .strlen)
else
.part$ = .str$
endif
.length = .length+1
.return$[.length] = .part$
until .sep = 0
endproc
If this is not what you are having trouble with, you'll have to be more specific.

Resources