im trying to run this code, but it returns the following error: 'Series' objects are mutable, thus they cannot be hashed. can anyone help me please?
(X is a dataset with multiple feature, y has only one feature)
j=1
for i in X.columns:
plt.subplot(5,4,j)
sns.scatterplot((X[i],y))
j+=1
Related
I need to compare the 2 arrays declared here to return records that exist only in the filtered_apps array. I am using the contents of previous_apps array to see if an ID in the record exists in filtered_apps array. I will be outputting the results to a CSV and displaying records that exist in both arrays to the console.
My question is this: How do I get the records that only exist in filtered_apps? Easiest for me would be to put those unique records into a new array to work with on the csv.
start_date = Date.parse("2022-02-05")
end_date = Date.parse("2022-05-17")
valid_year = start_date.year
dupe_apps = []
uniq_apps = []
# Finding applications that meet my criteria:
filtered_apps = FinancialAssistance::Application.where(
:is_requesting_info_in_mail => true,
:aasm_state => "determined",
:submitted_at => {
"$exists" => true,
"$gte" => start_date,
"$lte" => end_date })
# Finding applications that I want to compare against filtered_apps
previous_apps = FinancialAssistance::Application.where(
is_requesting_info_in_mail: true,
:submitted_at => {
"$exists" => true,
"$gte" => valid_year })
# I'm using this to pull the ID that I'm using for comparison just to make the comparison lighter by only storing the family_id
previous_apps.each do |y|
previous_apps_array << y.family_id
end
# This is where I'm doing my comparison and it is not working.
filtered_apps.each do |app|
if app.family_id.in?(previous_apps_array) == false
then #non_dupe_apps << app
else "No duplicate found for application #{app.hbx_id}"
end
end
end
So what am I doing wrong in the last code section?
Let's check your original method first (I fixed the indentation to make it clearer). There's quite a few issues with it:
filtered_apps.each do |app|
if app.family_id.in?(previous_apps_array) == false
# Where is "#non_dupe_apps" declared? It isn't anywhere in your example...
# Also, "then" is not necessary unless you want a one-line if-statement
then #non_dupe_apps << app
# This doesn't do anything, it's just a string
# You need to use "p" or "puts" to output something to the console
# Note that the "else" is also only triggered when duplicates WERE found...
else "No duplicate found for application #{app.hbx_id}"
end # Extra "end" here, this will mess things up
end
end
Also, you haven't declared previous_apps_array anywhere in your example, you just start adding to it out of nowhere.
Getting the difference between 2 arrays is dead easy in Ruby: just use -!
uniq_apps = filtered_apps - previous_apps
You can also do this with ActiveRecord results, since they are just arrays of ActiveRecord objects. However, this doesn't help if you specifically need to compare results using the family_id column.
TIP: Getting the values of only a specific column/columns from your database is probably best done with the pluck or select method if you don't need to store any other data about those objects. With pluck, you only get an array of values in the result, not the full objects. select works a bit differently and returns ActiveRecord objects, but filters out everything but the selected columns. select is usually better in nested queries, since it doesn't trigger a separate query when used as a part of another query, while pluck always triggers one.
# Querying straight from the database
# This is what I would recommend, but it doesn't print the values of duplicates
uniq_apps = filtered_apps.where.not(family_id: previous_apps.select(:family_id))
I highly recommend getting really familiar with at least filter/select, and map out of the basic array methods. They make things like this way easier. The Ruby docs are a great place to learn about them and others. A very simple example of doing a similar thing to what you explained in your question with filter/select on 2 arrays would be something like this:
arr = [1, 2, 3]
full_arr = [1, 2, 3, 4, 5]
unique_numbers = full_arr.filter do |num|
if arr.include?(num)
puts "Duplicates were found for #{num}"
false
else
true
end
end
# Duplicates were found for 1
# Duplicates were found for 2
# Duplicates were found for 3
=> [4, 5]
NOTE: The OP is working with ruby 2.5.9, where filter is not yet available as an array method (it was introduced in 2.6.3). However, filter is just an alias for select, which can be found on earlier versions of Ruby, so they can be used interchangeably. Personally, I prefer using filter because, as seen above, select is already used in other methods, and filter is also the more common term in other programming languages I usually work with. Of course when both are available, it doesn't really matter which one you use, as long as you keep it consistent.
EDIT: My last answer did, in fact, not work.
Here is the code all nice and working.
It turns out the issue was that when comparing family_id from the set of records I forgot that the looped record was a part of the set, so it would return it, too. I added a check for the ID of the array to match the looped record and bob's your uncle.
I added the pass and reject arrays so I could check my work instead of downloading a csv every time. Leaving them in mostly because I'm scared to change anything else.
start_date = Date.parse(date_from)
end_date = Date.parse(date_to)
valid_year = start_date.year
date_range = (start_date)..(end_date)
comparison_apps = FinancialAssistance::Application.by_year(start_date.year).where(
aasm_state:'determined',
is_requesting_voter_registration_application_in_mail:true)
apps = FinancialAssistance::Application.where(
:is_requesting_voter_registration_application_in_mail => true,
:submitted_at => date_range).uniq{ |n| n.family_id}
#pass_array = []
#reject_array = []
apps.each do |app|
family = app.family
app_id = app.id
previous_apps = comparison_apps.where(family_id:family.id,:id.ne => app.id)
if previous_apps.count > 0
#reject_array << app
puts "\e[32mApplicant hbx id \e[31m#{app.primary_applicant.person_hbx_id}\e[32m in family ID \e[31m#{family.id}\e[32m has registered to vote in a previous application.\e[0m"
else
<csv fields here>
csv << [csv fields here]
end
end
Basically, I pulled the applications into the app variable array, then filtered them by the family_id field in each record.
I had to do this because the issue at the bottom of everything was that there were records present in app that were themselves duplicates, only submitted a few days apart. Since I went on the assumption that the initial app array would be all unique, I thought the duplicates that were included were due to the rest of the code not filtering correctly.
I then use the uniq_apps array to filter through and look for matches in uniq_apps.each do, and when it finds a duplicate, it adds it to the previous_applications array inside the loop. Since this array resets each go-round, if it ever has more than 0 records in it, the app gets called out as being submitted already. Otherwise, it goes to my csv report.
Thanks for the help on this, it really got my brain thinking in another direction that I needed to. It also helped improve the code even though the issue was at the very beginning.
The "PercentDone" NSArray of Doubles that looks like this when all index's are filled:
(0,0,0)
Here is the predicate:
predicate = NSPredicate(format: "PercentDone CONTAINS %# && recordID == %#",Double(0), self.recordName!)
Here is the error I keep getting when viewing the subscription:
server message = "Missing filter value";
Even when I search on Apple documentation I don't find much help using predicates with numbers or arrays. I've tried turning it into a string and filtering but still no answer I even trying making regular array filled with numbers but I still can't seem to use the predicate correctly. Even when try to use some of the predicate key words in the Apple archive documentation it doesn't work. Does anyone know how to create a predicate with a NSArray of numbers?
I am having difficulty troubleshooting some code.
I have a for loop and in it I clone a part (called EnemySiteHub).
I expect that I can store each cloned part to a table (called EnemySiteTable).
Unfortunately, even though the loop runs successfully and I actually see the cloned EnemySiteHubs during a run of the game.. The table is size remains 0.
Trying to access the table in code gives a nil error.
Code snip:
local ENEMYSITE_COUNT = 5
local EnemySiteTable = {} -- [[ Store the table of enemy site objects ]]
-- Loops until there are the amount of enemy site hubs set in ENEMYSITE_COUNT
for i = 1, ENEMYSITE_COUNT do
--Makes a copy of EnemySiteHub
local enemySite = ServerStorage.EnemySites.EnemySiteHub:Clone()
enemySite.Parent = workspace.EnemySites
EnemySiteTable[i] = enemySite
This line of code causes causes the error below.
local enemySiteTableSize = #enemySiteTable
18:12:37.984 - ServerScriptService.MoveEnemyToSite:15: attempt to get length of a nil value
Any help will be appreciated.
#array is used to retrieve the length of arrays. You will have to use some sort of table.function() or use a for i,v in pairs(EnemySiteTable) loop.
Here's some more information: https://developer.roblox.com/en-us/articles/Table
Thanks #pyknight202
The problem originated somewhere else in my code.
The EnemySiteTable is in a module script.
This code below is the correct code to give access to the EnemySiteTable
--Have the table of enemies accessible
EnemySiteManager.EnemySiteTable = EnemySiteTable
I had an error (typo) in that line of code.
The effect of that error kept returning a nil table, giving a table size of 0.
I'm trying to call a set of elements in the example below.
session_times: {
thursday: ["10:20am", "12:30pm", "6:40pm"],
friday: ["10:20am", "12:30pm", "6:40pm"],
saturday: ["10:20am", "12:30pm", "6:00pm"],
sunday: ["10:20am", "12:30pm", "6:30pm"]
}
I tried doing the following functions
days_all = movie[:session_times]
string = ':' + 'thursday'
var1 = days_all[:thursday]
var2 = days_all["#{string}"]
var3 = days_all[string]
The variable var1 comes out perfectly fine but i dont understand why var2 or var 3 will not get my result, it should come out the same with same variable called right?
Help would be much appreciated :)
No, there is a difference between symbol and string and they are not always interchangable. A symbol is not the same as a string starting with a colon (that's still a string). When you use the key: val hash syntax the keys are symbols; "key" => val would be a string key.
any of these would work:
string = "thursday" # don't put the colon in here
days_all[:"#{string}"]
days_all[string.to_sym]
days_all["#{string}".to_sym]
If you install the gem activesupport and then require active_support/all (this is automatically done in rails), it's less strict about what key you need to use:
days_all = days_all.with_indifferent_access
days_all["thursday"]
days_all[:thursday]
days_all.thursday
With Ruby :x refers to a Symbol and "x" refers to a string. A Symbol is an "internalized string", it acts more like an arbitrary constant, and every instance of :x is identical with every other, they're literally the same object.
The same is not true for strings, each one may be different, and normally occupies a different chunk of memory. This is why you see Symbols used for keys in hashes, their repetition would be wasteful otherwise.
You can reference your structure any of the following ways:
days_all[:thursday] # With a plain symbol
days_all["thursday".to_sym] # With a converted string
days_all[:"thursday"] # With a long-form symbol
Another thing to note is you probably don't want to stick with this data structure if you can avoid it. This isn't very "machine readable", names like :thursday are completely arbitrary. It's much better to use a consistent index like 0 meaning Sunday, 1 meaning Monday and so on. That way functions like cwday can be used to look things up in a regular Array.
The same goes for human-annotated times like "10:30pm" where a value like 1350 meaning 22 hours plus 30 minutes, or even 2230 if you don't mind gaps between your intervals. Those are easy to compare: 1130<230 is never suddenly true due to ASCII sorting issues.
I just started developing a GAE app with the Go runtime, so far it's been a pleasure. However, I have encountered the following setback:
I am taking advantage of the flexibility that the datastore provides by having several different structs with different properties being saved with the same entity name ("Item"). The Go language datastore reference states that "the actual types passed do not have to match between Get and Put calls or even across different App Engine requests", since entities are actually just a series of properties, and can therefore be stored in an appropriate container type that can support them.
I need to query all of the entities stored under the entity name "Item" and encode them as JSON all at once. Using that entity property flexibility to my advantage, it is possible to store queried entities into an arbitrary datastore.PropertyList, however, the Get and GetAll functions return ErrFieldMismatch as an error when a property of the queried entities cannot be properly represented (that is to say, incompatible types, or simply a missing value). All of these structs I'm saving are user generated and most values are optional, therefore saving empty values into the datastore. There are no problems while saving these structs with empty values (datastore flexibility again), but there are when retrieving them.
It is also stated in the datastore Go documentation, that it is up to the caller of the Get methods to decide if the errors returned due to empty values are ignorable, recoverable, or fatal. I would like to know how to properly do this, since just ignoring the errors won't suffice, as the destination structs (datastore.PropertyList) of my queries are not filled at all when a query results in this error.
Thank you in advance, and sorry for the lengthy question.
Update: Here is some code
query := datastore.NewQuery("Item") // here I use some Filter calls, as well as a Limit call and an Order call
items := make([]datastore.PropertyList, 0)
_, err := query.GetAll(context, &items) // context has been obviously defined before
if err != nil {
// something to handle the error, which in my case, it's printing it and setting the server status as 500
}
Update 2: Here is some output
If I use make([]datastore.PropertyList, 0), I get this:
datastore: invalid entity type
And if I use make(datastore.PropertyList, 0), I get this:
datastore: cannot load field "Foo" into a "datastore.Property": no such struct field
And in both cases (the first one I assume can be discarded) in items I get this:
[]
According to the following post the go datastore module doesn't support PropertyList yet.
Use a pointer to a slice of datastore.Map instead.