Multiple urls pointing to a single resource with no redundancy - url

In django's urls.py I got this:
url(r'^main$', 'views.send_partial', name='main'),
url(r'^login$', 'views.send_partial', name='login'),
url(r'^signup$', 'views.send_partial', name='signup'),
url(r'^help$', 'views.send_partial', name='help'),
And I hate repeating code, so I would like to get rid of repeating the same function on and on for every url that should be handled by it. I can not find out how this is done anywhere. So what I am expecting is something like:
url('views.send_partial',
r'^main$', name='main,
r'^login$', name='login',
r'^signup$', name='signup',
r'^help$', name='help')
Ideas?

I have found nothing in the documentation (django.conf.urls), but I think it could be solved with a list/dict of patterns and names.
url_dict = {'main': 'r'^main$', 'login': r'^login$',
'signup': r'^signup$', 'help': r'^help$'}
# This part could also be put into a function taking the
# dictionary and the handler and returning urlpatterns
urls = []
for name, pattern in url_dict.items():
urls.append(url(pattern, 'views.send_partial', name=name))
urlpatterns = patterns('', *urls)
First you create a dictionary mapping the names to patterns (could also be something like a list of lists). Then you loop through the dictionary, creating a list of urlpatterns using url(). Finally you let them trough patterns() or do what else you was doing with them.

Related

Get ID from array file_get_contents

How to get ID's from array to get and put contents from urls. Need get data from url's and save it in folder. I'm new in PHP and try something like this, but it's don't work for me:
$array = array("10", "11", "12");
$contents = file_get_contents('http://www.example.cpm/id='.$array.'&type=text');
file_put_contents('folder/'.$array.'.html', $contents);
Sorry I done it, just using foreach() )))

Ruby on Rails statement executed on an array check if subelement string is unique

I have an array objects, for this example lets call it Diff. These diffs have multiple fields that are not all the same (old_image, new_image, url, etc). new_image and old_image in this case have fields on them, most importantly a field called image_file_name.
I want to get an array of all the diffs with an unique old_image.image_file_name i.e. no diff should have an old_image with the same file name.
I believe the logic should look something like this.
unique_diffs = Array.new
#diff.build.diffs.each { |diff|
if diff.old_image.image_file_name != #diff.old_image.image_file_name
unique_diffs.push(diff)
end
}
Or something like this
#unique_diffs = #diff.build.diffs.map{|diff| diff.old_image.image_file_name}.uniq
Any help would be much appreciated.
Try something like this:
Diff = Struct.new(:old_image)
Image = Struct.new(:image_file_name)
diffs = [
Diff.new(Image.new('name1')),
Diff.new(Image.new('name2')),
Diff.new(nil),
Diff.new(Image.new('name1')),
]
uniqs = diffs.select { |diff| diff.old_image }.uniq { |diff| diff.old_image.image_file_name }
p uniqs # prints Diff with name1 and Diff with name 2
The only important line is the one that calls select and uniq.
You need to use select to leave only the diffs with the old image, and then use uniq to drop those with the duplicated image file names.
I ended up using the loop, I was hoping to make this cleaner with the uniq function but it didn't seem to work, it gave me back all the diffs instead of the ones with the unique old image filename.
#diff.build.diffs.each { |diff|
if diff.old_image.image_file_name == #diff.old_image.image_file_name
# Logic went here
end
}
Still open to improving this but for now this will have to do.

Rails code segment explained

I am working on an app which has the below code:
def app
#app ||= begin
if !::File.exist? options[:config]
abort "configuration #{options[:config]} not found"
end
app, myoptions = Rack::Builder.parse_file(self.options[:config], opt_parser)
self.myoptions.merge! myoptions
app
end
end
I am struggling to get my head around several parts of it..
#app||= begin...end
Does this mean that if #app does not exist the block is run?
app ,options = rack::builder
What does the comma do to it?
Please help
Your first assumptions was correct, it does say that if #app is nil, set it to whatever is returned in the block delimited with begin, end.
Regarding the comma, it works like this:
avar, bvar = "atest", "btest"
If you look at the source for Rack:Builder.parse_file then you will notice the last line
return app, options
So it is returning two values.
Hope that helps
#Craig-Taub ansewered the question,
I just want to add some notes:
Ruby commands are expressions which means they return value and you can assign them to variables.
You can read more about expressions and statements on Wikipedia and PragProg.
Second is that when you return more than one value in a code block, Ruby will wrap it into a simple array and return it to the caller.
That's why it works like that.

Dart List within a Map

I have a Map in Dart (originally loaded from JSON) that looks something like this:
somevar = {
'Title': 'Some object',
'items': [{'title': 'Item 1 Title'}, {'title': 'Item 2 Title'}]
}
For some reason somevar['items'] doesn't behave quite like a list.
I get Exception: NoSuchMethodError : method not found: 'iterator' if I attempt to iterate over the list.
I also get a similar error if I try somevar['items'].length
If I manually load this "list" like this: someList = new List(somevar['items']); then it works as expected.
Any idea why this is that case, and what I'm doing wrong? For me the natural expectation would be that a "list" parsed from JSON will behave exactly like the List() object.
Never mind, seems that I had a deeper issue in my code that cause my somevar variable to be null (even though it should have the map.
Anyway, I'm marking this as solved for now so not to waste anyone's time.

Select attribute from node with XPath

I have a file with the following structure
<admin>
<sampleName>Willow oak leaf</sampleName>
<sampleDescription comment="Total genes">
<cvParam cvLabel="Bob" accession="123" name="Oak" />
</sampleDescription>
</admin>
I'm trying to get out the text "Total genes" after the sampleDescription comment, and I have used the following code:
sampleDescription = doc.xpath( "/admin/Description/#comment" )
sampleDescription = doc.xpath( "/admin/Description" ).text
But neither work. What am I missing?
might be a typo... have you tried doc.xpath("/admin/sampleDescription/#comment").text?
It's not working because there's no Description element. As mentioned by Iwe, you need to do something like sampleDescription = doc.xpath("/admin/sampleDescription/#comment").to_s
Also, if it were me, I would just do sampleDescription = doc.xpath("//sampleDescription/#comment").to_s. It's a simpler xpath, but it might be slower.
And as a note, something that trips up a lot of people are namespaces. If your xml document uses namespaces, do sampleDescription = doc.xpath("/xmlns:admin/sampleDescription/#comment").to_s. If your doc uses namespaces and you don't specify it with xmlns:, then Nokogiri won't return anything.
Try this:
doc.xpath("//admin/sampleDescription/#comment").to_s
doc.xpath returns a NodeSet which acts a bit like an array. So you need to grab the first element
doc.xpath("//admin/sampleDescription").first['comment']
You could also use at_xpath which is equivalent to xpath(foo).first
doc.at_xpath("//admin/sampleDescription")['comment']
Another thing to note is that attributes on nodes are accessed like hash elements--with [<key>]

Resources