Preferred way to add Maps to a List? - list

I've been trying to learn Elixir for a few days and I'm wondering if there is a better/preferred way of adding maps to a collection. For example, I'm working with a photos list that contains many photo maps. I am adding new maps using Enum.concat(photos, photo).
However, I am trying to look at the documentation and I am probably missing something obvious. Is there a better way to add a photo to photos instead of:
photos = Enum.concat(photos, photo)
Thank you.

Enum.concat/2 is just one of many ways you can insert an item into a list. You can also use the shorthand ++ operator:
photos = photos ++ [photo]
If the order does not matter to you, you can also prepend your photo at the start of the list; it's much faster performance wise (O(1) compared to O(n)).
photos = [ photo | photos ]

Related

Django Designing Models for Dating App Matches

I’m working on a dating app for a hackathon project. We have a series of questions that users fill out, and then every few days we are going to send suggested matches. If anyone has a good tutorial for these kinds of matching algorithms, it would be very appreciated. One idea is to assign a point value for each question and then to do a
def comparison(person_a, person_b) function where you iterate through these questions, and where there’s a common answer, you add in a point. So the higher the score, the better the match. I understand this so far, but I’m struggling to see how to save this data in the database.
In python, I could take each user and then iterate through all the other users with this comparison function and make a dictionary for each person that lists all the other users and a score for them. And then to suggest matches, I iterate through the dictionary list and if that person hasn’t been matched up already with that person, then make a match.
person1_dictionary_of_matches = {‘person2’: 3, ‘person3’: 5, ‘person4’: 10, ‘person5’: 12, ‘person6’: 2,……,‘person200’:10}
person_1_list_of_prior_matches = [‘person3’, 'person4']
I'm struggling on how to represent this in django. I could have a bunch of users and make a Match model like:
class Match(Model):
person1 = models.ForeignKey(User)
person2 = models.ForeignKey(User)
score = models.PositiveIntegerField()
Where I do the iteration and save all the pairwise scores.
and then do
person_matches = Match.objectsfilter(person1=sarah, person2!=sarah).order_by('score').exclude(person2 in list_of_past_matches)
But I’m worried with 1000 users, I will have 1000000 rows in my table if do this. Will this be brutal to have to save all these pairwise scores for each user in the database? Or does this not matter if I run it at like Sunday night at 1am or just cache these responses once and use the comparisons for a period of months? Is there a better way to do this than matching everyone up pairwise? Should I use some other data structure to capture the people and their compatibility score? Thanks so much for any guidance!
Interesting question. In machine learning's current paradigm you work with sparse matrices that means that you would not have to perform every single match evaluation. The sparsity may come from two alternatives:
Create a batch offline analysis of your data to perform some clustering (fancy solution).
Filter the individuals by some key attributes: a) gender/sexual preference, b) geographical location, c) dating status etc. (simple solution)
After the filtering you could perform a function for estimating appropriate matches for the new user. Based on the selected choices of the user adscribe selected matches into the database for future queries. However, if you get serious about this problem I suggest you give Spark a try. This is not a problem for an SQL database but for a Big Data Engine.

Musicbrainz querying artist and release

I am trying to get an artist and their albums. So reading this page https://musicbrainz.org/doc/Development/XML_Web_Service/Version_2 i created the following query to get Michael Jackson's albums
http://musicbrainz.org/ws/2/artist/?query=artist:michael%20jackson?inc=releases+recordings
My understanding is to add ?inc=releases+recordings at the end of the URL which should return Michael Jackson's albums however this doesnt seem to return the correct results or i cant seem to narrow down the results? I then thought to use the {MBID} but again thats not returned in the artists query (which is why im trying to use inc in my query)
http://musicbrainz.org/ws/2/artist/?query=artist:michael%20jackson
Can anyone suggest where im going wrong with this?
You're not searching for the correct Entity. What you want is to get the discography, not artist's infos. Additionally, query fields syntax is not correct (you must use Lucene Search Syntax).
Here is what you're looking for:
http://musicbrainz.org/ws/2/release-group/?query=artist:"michael jackson" AND primarytype:"album"
We're targeting the release-group entity to get the albums, searching for a specific artist and filtering the results to limit them to albums. (accepted values are: album, single, ep, other)
There are more options to fit your needs, for example you can filter the type of albums using the secondarytype parameter. Here is the query to retrieve only live albums:
http://musicbrainz.org/ws/2/release-group/?query=artist:"michael jackson" AND primarytype:"album" AND secondarytype="live"
Here is the doc:
https://musicbrainz.org/doc/Development/XML_Web_Service/Version_2/Search
Note that to be able to use MB's API you need to understand how it is structured, especially, the relations between release_group, release and medium.

What is the best way to use query with a list and keep the list order? [duplicate]

This question already has answers here:
Django: __in query lookup doesn't maintain the order in queryset
(6 answers)
Closed 8 years ago.
I've searched online and could only find one blog that seemed like a hackish attempt to keep the order of a query list. I was hoping to query using the ORM with a list of strings, but doing it that way does not keep the order of the list.
From what I understand bulk_query only works if you have the id's of the items you want to query.
Can anybody recommend an ideal way of querying by a list of strings and making sure the objects are kept in their proper order?
So in a perfect world I would be able to query a set of objects by doing something like this...
Entry.objects.filter(id__in=['list', 'of', 'strings'])
However, they do not keep order, so string could be before list etc...
The only work around I see, and I may just be tired or this may be perfectly acceptable I'm not sure is doing this...
for i in listOfStrings:
object = Object.objects.get(title=str(i))
myIterableCorrectOrderedList.append(object)
Thank you,
The problem with your solution is that it does a separate database query for each item.
This answer gives the right solution if you're using ids: use in_bulk to create a map between ids and items, and then reorder them as you wish.
If you're not using ids, you can just create the mapping yourself:
values = ['list', 'of', 'strings']
# one database query
entries = Entry.objects.filter(field__in=values)
# one trip through the list to create the mapping
entry_map = {entry.field: entry for entry in entries}
# one more trip through the list to build the ordered entries
ordered_entries = [entry_map[value] for value in values]
(You could save yourself a line by using index, as in this example, but since index is O(n) the performance will not be good for long lists.)
Remember that ultimately this is all done to a database; these operations get translated down to SQL somewhere.
Your Django query loosely translated into SQL would be something like:
SELECT * FROM entry_table e WHERE e.title IN ("list", "of", "strings");
So, in a way, your question is equivalent to asking how to ORDER BY the order something was specified in a WHERE clause. (Needless to say, I hope, this is a confusing request to write in SQL -- NOT the way it was designed to be used.)
You can do this in a couple of ways, as documented in some other answers on StackOverflow [1] [2]. However, as you can see, both rely on adding (temporary) information to the database in order to sort the selection.
Really, this should suggest the correct answer: the information you are sorting on should be in your database. Or, back in high-level Django-land, it should be in your models. Consider revising your models to save a timestamp or an ordering when the user adds favorites, if that's what you want to preserve.
Otherwise, you're stuck with one of the solutions that either grabs the unordered data from the db then "fixes" it in Python, or constructing your own SQL query and implementing your own ugly hack from one of the solutions I linked (don't do this).
tl;dr The "right" answer is to keep the sort order in the database; the "quick fix" is to massage the unsorted data from the database to your liking in Python.
EDIT: Apparently MySQL has some weird feature that will let you do this, if that happens to be your backend.

How to select content items from Sitecore using contains parameter. Sitecore Query is very slow

I have a Sitecore data template called "Meeting". It has a field called "Additional Activities". This field is a multi-list that allows the content editor to associate many different Activities with a meeting. My Meeting content items do not all live in the same folder in the content tree. They are spread out throughout the site. Given a particular Activity, I need to be able to find and display a list of all of the associated Meetings for that Activity. Right now I am using Sitecore Query as follows:
/Sitecore/Content/Home//*[(##templatename='Meeting') and (contains (###Additional Activities#, '{C73FAE38-DBF5-42C9-B872-8E412B99E9DE}'))]
That works, but it is terribly slow. I thought about creating some sort of in-memory cache that I could query, but then I have problems with when to rebuild the cache. I also thought of using Lucene, but I have found Lucene queries to be super complicated to implement. Does anyone have any suggestions as to a better way to do this? Should I just use Sitecore Query to get the list of ALL Meetings in the content tree and then iterate through them?
There is an alternative to Lucene, to what you are trying to do. Let me be clear though; I agree with Klaus, looking into Lucene is the recommended route. That being said; here's an alternative version. For what you are trying to do, you can use the Sitecore LinkDatabase. It will do the trick for you, as long as you are only looking to find meetings that reference a particular activity.
The code would look something like this:
Item activityTemplate = Sitecore.Context.Database.GetItem( "/sitecore/templates/path/to/your/activity/template" );
var links = new List<ItemLink>( Globals.LinkDatabase.GetItemReferrers( activityTemplate, false ) );
List<ItemLink> filteredLinks = links.FindAll( il => il.SourceDatabaseName == Sitecore.Context.Database.Name );
// filtered links is now a list of all references to your activity
foreach ( ItemLink fl in filteredLinks )
{
Item si = fl.GetSourceItem();
// Check if the reference is a meeting item
if ( si.TemplateID == Sitecore.Data.ID.Parse( "{0E06BFCA-3595-4F31-BDBF-746EE6663B4A}" ) && si.Paths.FullPath.StartsWith( "/sitecore/content" ) )
{
// si is your meeting item
Response.Write( si.Paths.FullPath + "<br />" );
}
}
Execution time for this query is as fast (possibly slightly faster) than the Lucene equivalent, and most definitely faster than your raw Sitecore Query.
Lucene query withan indexof all you meeting items is the way to go.
Will be really fast. Are you on Sitecore 7 or 6? i guess the tag says 6 so use the advanced database crawler from marketplace to set up the index and the query should be pretty straight forward.
Depending on your Sitecore version, you can also use the Fast query:
query:fast:/Sitecore/Content/Home//*[##templatename='Meeting'
and ###Additional Activities#='%{C73FAE38-DBF5-42C9-B872-8E412B99E9DE}%']

Python/Django multidimensional array

Excuse me for the basic question but I come from a PHP background and made use of multidimensional arrays to transfer information around.
What is the best alternative in Python?
$person[1]['name'] = 'bob'
$person[1]['age'] = 27
$person[1]['email'] = 'aaa#aa.com'
What I'm trying to is prepare an array to send to a template, I need to get a list of persons and then calculate when their next meeting/visit should be. I then want to send an array to the template like:
Name Last Meeting Date Next Meeting Date
Bob 01/04/2012 01/05/2015
The Next meeting date is calculated based on many variables so I just want to prepare the array in the view and then pass it to the template.
person = [{'name':'bob', 'age':27, 'email':'aaa#aa.com'}, {...}, {...}]
though if you use django, you might want to check the documentation and how models (user model for instance) work, cause you won't need to declare a list of dicts...
In Python we have different kinds of data structures, you can't just append data like in the example you show. What you need in this specific case is a list (which is an equivalent of a 1-dimensional array) filled with dicts (just as an array of key-value pairs) where you can define your data:
people = [{"name": "Bob", "last_meeting": yesterday, "next_meeting": tomorrow}, {...}, ...]
Check this link for more info on data structures in python: http://docs.python.org/2/tutorial/datastructures.html
Though, #nnaelle is right, if you are using django and not just python, you should check out how the framework manages requests using Forms, Models, Querysets, views and all the useful stuff that powers Django: https://docs.djangoproject.com/en/1.5/
That will for sure ease a lot of your work ;)
Good luck!