ColdFusion structure initializing many properties at a time - coldfusion

I have seen ColdFusion 9 code which initializes many properties of a structure at a time.
Here is an example:
<!---
pseudo constructor code
--->
<cfset variables.instance = {
first_name = '',
last_name = '',
gender = '',
dateofbirth = ''
} />
Is there a way to do this in coldfusion MX7 ?

No, this syntax was partially introduced in cf8, and further improved in 9. MX7 had no such construct available.

What one can do is to create a small util function thus:
function structBuild(){
return arguments;
}
Which one can then call, thus:
st = structBuild(
first_name = '',
last_name = '',
gender = '',
dateofbirth = ''
);
That pretty much works the same way. Not as nice by any measure, but it's a handy technique to be aware of.

Related

Odoo fields_view_get add dynamic groups

I want to override fields_view_get of odoo to add groups to fields dynamically based on a condition.
#api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
res = super(client_quote, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar,
submenu=submenu)
"""update this method to change the string of fields in different tab of client quote if it changes from vfx sheet """
if view_type == 'form' and ('vfx_shots_ids' in res['fields']):
for field in res['fields']['vfx_shots_ids']['views']['tree']['fields']:
if self._context.get('quote_id'):
vfx_quote_id = self.env['vfx.quote'].browse(self._context['quote_id'])
field_id = self.env['field.name'].search([('name', '=', field)])
if field_id:
line_id = self.env['mapping.template.line'].search([('template_id', '=', vfx_quote_id.template_id.id),
('field_id', '=', field_id.id),
('model_name', '=', 'vfx.shots')
])
if line_id:
string = line_id.heading_id.name
res['fields']['vfx_shots_ids']['views']['tree']['fields'][field]['string'] = _(string)
res['fields']['vfx_shots_ids']['views']['tree']['fields'][field]['groups'] = str('vfx_quote_template.group_empty_fields')
return res
This is my class and fields, i want to change vfx_quote_template.group_executive_producer group based of a condition.
Currently fields_view_get code seems to have no effect.
class vfx_shots(models.Model):
_name = 'vfx.shots'
item_number = fields.Char('Item',groups="vfx_quote_template.group_executive_producer")
You have to use lxml library to modify the XML architecture of the view in the fields_view_get() method.
You can also override the fields definition by overriding the fields_get() method.
You can get examples here : https://bazaar.launchpad.net/~unifield-team/unifield-server/trunk/view/head:/bin/addons/consumption_calculation/history_consumption.py#L457
I know it is in v6 version of the code, but the fields_view_get behavior didn't change a lot since this version.

Rails 4, Lupa: chaining with OR

I'm using Lupa for filtering (Lupa is framework independent, easy to test, benchmarks well against has_scope, etc.).
How can I chain scopes with OR logic in Lupa? This works great when the params are known ahead of time, but not when the filters are user-determined.
Perhaps the solution is in the dates_between section of the docs, but I cannot seem to figure it out.
I have a form that allows users to select the gender of an animal - male, female - using checkboxes. I want users to be able to check one, the other, or both and return the intuitive result.
Lupa's author's blog (#edelpero) nudged me in the right direction, but I feel either I am misunderstanding something or the docs might be improved (probably the former). Maybe some type-o's below as I'm simplifying from an app I'm kicking through, but here is a solution:
form
= form_tag pups_path, method: :get do
= check_box_tag 'male', 'm'
= check_box_tag 'female', 'f'
# add a hidden field so that the gender method in the scope class is called
= hidden_field_tag 'gender', 'anything' # tag must have a value
= submit_tag :search
controller
class PupsController < ApplicationController
def index
#pups = PupSearch.new(Pup.all).search(search_params)
end
protected
def search_params
params.permit(:male, :female, :gender) # permit all three
end
end
scope class
class WalkSearch < Lupa::Search
class Scope
def male
# leave blank to avoid chaining; handled in gender below
end
def female
# leave blank to avoid chaining; handled in gender below
end
def gender
# standard procedure for OR logic
scope.joins(:pup).where('pups.male_female' => [
search_attributes[:male],
search_attributes[:female]
])
end
end
end

Django - Error models with control data

I'm working on writing the models.py file, and I need some controls to perform the automatic compilation of some fields.
MOTIVOINGRESSO = (
(u'sequestro ', u'sequestro'),
(u'fermo ', u'fermo'),
(u'confisca final ', u'confisca final'),
(u'cambio custodian ', u'cambio custodian'),
)
motivo_ingresso = models.CharField (max_length = 50, choices = MOTIVOINGRESSO)
FERMO = (
(u'30 ', u'30'),
(u'60 ', u'60'),
(u'90 ', u'90'),
(u'180 ', u'180'),
(u'1 month ', u'1 month'),
(u'3 months, 'u'3 months'),
(u'indeterminato ', u'indeterminato'),
)
durata_in_giorni_del_fermo = models.CharField (max_length = 20, choices = STOPPED, blank = True)
If the administrator the choice click 'sequestro', in durata_in_giorni_del_fermo will automatically selected 'indeterminato'.
Should I report the values ​​entered? or machine cycles if within the models?
Any Ideas?
Its very easy if you will do it through Jquery in template. I don't know, this can be possible in models.py. Below links are much relevant to your question.
How to implement two dropdowns dependent on each other using Django and jQuery
Dynamic select fields with JQuery and django
Hoping you will got the idea about ajax and Jquery after following above links :)

How do I do a partial field match using Haystack?

I needed a simple search tool for my django-powered web site, so I went with Haystack and Solr. I have set everything up correctly and can find the correct search results when I type in the exact phrase, but I can't get any results when typing in a partial phrase.
For example: "John" returns "John Doe" but "Joh" doesn't return anything.
Model:
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
Search Index:
class PersonIndex(SearchIndex):
text = CharField(document=True, use_template=True)
first_name = CharField(model_attr = 'first_name')
last_name = CharField(model_attr = 'last_name')
site.register(Person, PersonIndex)
I'm guessing there's some setting I'm missing that enables partial field matching. I've seen people talking about EdgeNGramFilterFactory() in some forums, and I've Googled it, but I'm not quite sure of its implementation. Plus, I was hoping there was a haystack-specific way of doing it in case I ever switch out the search backend.
You can achieve that behavior by making your index's text field an EdgeNgramField:
class PersonIndex(SearchIndex):
text = EdgeNgramField(document=True, use_template=True)
first_name = CharField(model_attr = 'first_name')
last_name = CharField(model_attr = 'last_name')
In addition to the EdgeNgramField hint that others mentioned in this page (and of course NgramField, if you work with Asian languages), I think it is worth to mention that in Django_haystack you can run raw queries on Solr via following command:
from haystack.query import SearchQuerySet
from haystack.inputs import Raw
SearchQuerySet().filter(text=Raw(query))
where text is the field you want to search, and the query can be anything based on Query Parser Syntax (version 3.6, or 4.6) of Lucene.
In this way you can easily set the query to ABC* or ABC~ or anything else which fits to the syntax.
I had a similar issue while searching for non english words, for instance:
ABC
ABCD
If I want to search for keywords ABC, I will expect the above two results. I was able to achieve the following by converting the keyword to lowercase and using startswith:
keywords = 'ABC'
results.filter(code__startswith=keywords.lower())
I had the same problem and the only way to get the results I wanted was to modify the solr configuration file to include ngram filtering as the default tokenizer is based on white space. So use NGramTokenizer instead. I'd love to know if there was a haystack way of doing the same thing.
I'm not at my machine right now but this should do the trick.
<tokenizer class="solr.NGramTokenizerFactory" minGramSize="3" maxGramSize="15" />
#riz I can't comment yet or I would and I know it's an old comment but in case anyone else runs past this: Make sure to manage.py update_index
Blockquote #Liarez how did you get this to work? I'm using haystack/elastic search and I wasn't able to get it to work.

how to save django object using dictionary?

is there a way that I can save the model by using dictionary
for e.g.
this is working fine,
p1 = Poll.objects.get(pk=1)
p1.name = 'poll2'
p1.descirption = 'poll2 description'
p1.save()
but what if I have dictionary like { 'name': 'poll2', 'description: 'poll2 description' }
is there a simple way to save the such dictionary direct to Poll
drmegahertz's solution works if you're creating a new object from scratch. In your example, though, you seem to want to update an existing object. You do this by accessing the __dict__ attribute that every Python object has:
p1.__dict__.update(mydatadict)
p1.save()
You could unwrap the dictionary, making its keys and values act like named arguments:
data_dict = {'name': 'foo', 'description': 'bar'}
# This becomes Poll(name='foo', description='bar')
p = Poll(**data_dict)
...
p.save()
I find only this variant worked for me clear.
Also in this case all Signals will be triggered properly
p1 = Poll.objects.get(pk=1)
values = { 'name': 'poll2', 'description': 'poll2 description' }
for field, value in values.items():
if hasattr(p1, field):
setattr(p1, field, value)
p1.save()
You could achieve this by using update on a filterset:
e.g.:
data = { 'name': 'poll2', 'description: 'poll2 description' }
p1 = Poll.objects.filter(pk=1)
p1.update(**data)
Notes:
be aware that .update does not trigger signals
You may want to put a check in there to make sure that only 1 result is returned before updating (just to be on the safe side). e.g.: if p1.count() == 1: ...
This may be a preferable option to using __ methods such as __dict__.