I am working on migrating a bunch of data from an old database into a new one. In the process of migrating a created a UDF for my script that would give me a bunch of data that I need. When I run a loop that calls the UDF multiple times I find that the first iteration runs fine, but then the UDF disappears from the following iterations.
My code is:
<cffunction name="getCats" access="public">
<cfargument name="assignments" type="any" />
<cfquery name="getCats" datasource="pgdold">
SELECT c1.id AS id1, c1.category AS name1, c2.id AS id2, c2.category AS name2, c3.id AS id3, c3.category AS name3, c4.id AS id4, c4.category AS name4, c5.id AS id5, c5.category AS name5
FROM category c1
LEFT JOIN category AS c2 ON c2.parentid = c1.id
LEFT JOIN category AS c3 ON c3.parentid = c2.id
LEFT JOIN category AS c4 ON c4.parentid = c3.id
LEFT JOIN category AS c5 ON c5.parentid = c4.id
</cfquery>
<cfquery name="get" dbtype="query">
SELECT (name1 + '/' + name2 + '/' + name3 + '/' + name4 + '/' + name5) AS category
FROM getCats
WHERE
<cfloop query="Arguments.assignments">
(id1 = #Arguments.assignments.categoryid# OR id2 = #Arguments.assignments.categoryid# OR id3 = #Arguments.assignments.categoryid# OR id4 = #Arguments.assignments.categoryid# OR id5 = #Arguments.assignments.categoryid#)
<cfif Arguments.assignments.currentrow IS NOT Arguments.assignments.recordCount> OR </cfif>
</cfloop>
</cfquery>
<cfreturn get />
</cffunction>
<cfscript>
olddb = {datasource='pgdold'};
a = new Query(argumentCollection=olddb);
a.setSQL('SELECT * FROM products LIMIT 10');
p = a.execute();
pr = p.getResult();
</cfscript>
<cfscript>
products = arrayNew();
for(i=1;i<=pr.recordCount;i++){
product = {};
if(!reFind('([0-9]+\-)(G|g)(I|i)(F|f)(T|t)',pr['sku'][i])){
b = new Query(argumentCollection=olddb);
b.setSql('SELECT * FROM productpics WHERE sku = :sku ORDER BY picorder');
b.addParam(name='sku',value=pr['sku'][i]);
pics = b.execute().getResult();
picList = '';
for(j=1;j<=pics.recordCount;j++){
picList = picList & ';' & pics['imagename'][j];
}
d = new Query(argumentCollection=olddb);
d.setSql('SELECT * FROM skucategories WHERE sku = :sku');
d.addParam(name='sku', value=pr['sku'][i]);
assignments = d.execute().getResult();
categories = getCats(assignments);
writeDump(categories);
product = {
store = 'admin',
websites = 'base',
attribute_set = 'Default',
categories = '',
type = 'simple',
sku = pr['sku'][i],
name = reReplace(reReplace(pr['title'][i],'\"','&##34;','all'),'\,','&##44;','all'),
price = pr['price'][i],
description = reReplace(reReplace(pr['detail'][i],'\"','&##34;','all'),'\,','&##44;','all'),
short_description = '',
image = pics['imagename'][1],
small_image = pics['imagename'][1],
thumbnail = pics['imagename'][1],
weight = pr['weight'][i],
has_options = 1,
is_in_stock = 1,
qty = 1000,
disabled = 'No',
status = 'Enabled',
options_container = 'Black after info Column',
tax_class_id = 'Taxable Goods',
visibility = 'Catalog,Search',
gallery = right(picList,len(picList)-1) // Seperate images by semicolon (;)
};
arrayAppend(products,product);
}
}
</cfscript>
It is the getCats function that disappears.
* yes the code is ugly and inefficient. It wasn't meant to do anything more than this one job and after it finishes the job it is going to be thrown away, so don't tell me about the ugliness or inefficiencies.
Without reading every line of your code posted, I have a Strong feeling that it has to do with Var scooping... since you are calling that UDF in a Loop.
Please var scope you query variables.
Pre CF9:
<!--- insert after <cfargument> --->
<cfset var getCats = "">
<cfset var get = "">
At, or Post CF9 with Local scope:
<cfquery name="local.getCats" datasource="pgdold">
<cfquery name="local.get" dbtype="query">
You named a variable in the UDF with the same name as the UDF. Either var scope it or rename that query to something else. I recommend naming it something else.
Related
I want an equivalent of this sql query in Django
SELECT Gender, ServCode
FROM [openimisproductTestDb_16_08_22].[dbo].[tblInsuree]
JOIN [openimisproductTestDb_16_08_22].[dbo].[tblServices] ON [openimisproductTestDb_16_08_22].[dbo].[tblInsuree].AuditUserID = [openimisproductTestDb_16_08_22].[dbo].[tblServices].AuditUserID
WHERE Gender = 'F'
AND ServCode = 'F4'
What I have tried:
def assisted_birth_with_cs_query(user, **kwargs):
date_from = kwargs.get("date_from")
date_to = kwargs.get("date_to")
hflocation = kwargs.get("hflocation")
format = "%Y-%m-%d"
date_from_object = datetime.datetime.strptime(date_from, format)
date_from_str = date_from_object.strftime("%d/%m/%Y")
date_to_object = datetime.datetime.strptime(date_to, format)
date_to_str = date_to_object.strftime("%d/%m/%Y")
dictBase = {
"dateFrom": date_from_str,
"dateTo": date_to_str,
}
dictGeo = {}
if hflocation and hflocation!="0" :
hflocationObj = HealthFacility.objects.filter(
code=hflocation,
validity_to__isnull=True
).first()
dictBase["fosa"] = hflocationObj.name
claimItem = Insuree.objects.filter(
validity_from__gte = date_from,
validity_to__lte = date_to,
**dictGeo,
gender = 'F'
).count()
data = Service.objects.filter(code = 'F4').count() | Insuree.objects.filter(gender = 'F').count()
dictGeo['health_facility'] = hflocationObj.id
dictBase["post"]= str(data)
return dictBase
I tried like that but the one just adds when I want the women included in the insured table and the F4 code contained in the service table. both tables have the auditUserID column in common
It would be great if you could add the models to better see the relations between Insuree and Service. Assuming it's a 1-M, I'd go with this query:
Service.objects.filter(code='F4', insuree__gender='F').count()
I have a table TickerStatement, which contains financial statements about companies
class Statements(models.TextChoices):
"""
Supported statements
"""
capital_lease_obligations = 'capital_lease_obligations'
net_income = 'net_income'
price = 'price'
total_assets = 'total_assets'
short_term_debt = 'short_term_debt'
total_long_term_debt = 'total_long_term_debt'
total_revenue = 'total_revenue'
total_shareholder_equity = 'total_shareholder_equity'
class TickerStatement(TimeStampMixin):
"""
Model that represents ticker financial statements
"""
name = models.CharField(choices=Statements.choices, max_length=50)
fiscal_date_ending = models.DateField()
value = models.DecimalField(max_digits=MAX_DIGITS, decimal_places=DECIMAL_PLACES)
ticker = models.ForeignKey(Ticker, on_delete=models.CASCADE, null=False,
related_name='ticker_statements')
And now I'm trying to calculate a multiplier. The formula looks like:
(short_term_debt + total_long_term_debt) / total_shareholder_equity
I wrote a raw SQL query
SELECT "fin_tickerstatement"."fiscal_date_ending",
t2.equity AS "equity",
value AS "debt",
short_term_debt AS "short_term_debt",
(value + short_term_debt) / t2.equity AS "result"
FROM "fin_tickerstatement"
JOIN
(SELECT "fin_tickerstatement"."fiscal_date_ending",
fin_tickerstatement.value AS "equity"
FROM "fin_tickerstatement"
WHERE ("fin_tickerstatement"."ticker_id" = 12
AND "fin_tickerstatement"."fiscal_date_ending" >= date'2015-09-03'
AND "fin_tickerstatement"."name" = 'total_shareholder_equity')
GROUP BY "fin_tickerstatement"."fiscal_date_ending",
fin_tickerstatement.value
ORDER BY "fin_tickerstatement"."fiscal_date_ending" DESC) t2
ON fin_tickerstatement.fiscal_date_ending = t2.fiscal_date_ending
JOIN
(SELECT "fin_tickerstatement"."fiscal_date_ending",
fin_tickerstatement.value AS "short_term_debt"
FROM "fin_tickerstatement"
WHERE ("fin_tickerstatement"."ticker_id" = 12
AND "fin_tickerstatement"."fiscal_date_ending" >= date'2015-09-03'
AND "fin_tickerstatement"."name" = 'short_term_debt')
GROUP BY "fin_tickerstatement"."fiscal_date_ending",
fin_tickerstatement.value
ORDER BY "fin_tickerstatement"."fiscal_date_ending" DESC) t3
ON fin_tickerstatement.fiscal_date_ending = t3.fiscal_date_ending
WHERE ("fin_tickerstatement"."ticker_id" = 12
AND "fin_tickerstatement"."fiscal_date_ending" >= date'2015-09-03'
AND "fin_tickerstatement"."name" = 'total_long_term_debt')
GROUP BY "fin_tickerstatement"."fiscal_date_ending",
equity,
debt,
short_term_debt
ORDER BY "fin_tickerstatement"."fiscal_date_ending" DESC;
and have no idea how to translate it into Django ORM. Maybe you have some ideas or know some Django plugins that can help me.
The only way to solve this problem is to install django-query-builder.
I have a problem to execute this query in oracle apex. Please help me how to fix it. The query will update multiple rows in the table using loop.
begin
UPDATE app
SET APPFLG = 'A',
APRVBY=:app_user
WHERE ACTNUM = APEX_APPLICATION.G_f03 (v_row) and APPFLG = 'N';
IF SQL%NOTFOUND
THEN
raise_application_error (
-20001,
'Unable to Update Customer :' || APEX_APPLICATION.G_f03 (v_row));
ROLLBACK;
RETURN;
ELSE
UPDATE aas
SET opndat = (select opndat from app where actnum = APEX_APPLICATION.G_f03 (v_row)),
SANAD1 = (select SANAD1N from app where actnum = APEX_APPLICATION.G_f03 (v_row)),
CRIRTE = (select CRIRTEN from app where actnum = APEX_APPLICATION.G_f03 (v_row)),
DNPAMT = (select DNPAMTN from app where actnum = APEX_APPLICATION.G_f03 (v_row)),
WHERE BRANCD = :AI_BRANCH_CODE AND actype = 'C88' and actnum = APEX_APPLICATION.G_f03 (v_row);
for i in (select ACTNUM, CERTNO, CURVAL, SECSTS from sd_app where actnum= APEX_APPLICATION.G_f03 (v_row))
loop
update sd
set ACTNUM = i.ACTNUM,
CERTNO = i.CERTNO,
CURVAL = i.CURVAL,
SECSTS = i.SECSTS
where BRANCD = :AI_BRANCH_CODE AND actype = 'C88' and actnum = APEX_APPLICATION.G_f03 (v_row);
end loop ;
END IF;
The actual result can update the sd table.
When I do something like this:
model_list = [Model(name = 'First'), Model(name = 'Second'), Model(name = 'Third')]
Model.objects.bulk_create(model_list)
Can I trust that they will be created in that same order?
That is:
pk1 = Model.objects.get(name = 'First').pk
pk2 = Model.objects.get(name = 'Second').pk
pk3 = Model.objects.get(name = 'Third').pk
(pk3 > pk2) and (pk2 > pk1)
I think you can.
model_list = [Model(name = 'First'),
Model(name = 'Second'),
Model(name = 'Third')]
Model.objects.bulk_create(model_list)
This code will be translated to the following SQL:
INSERT INTO app_model (name) VALUES ('First'), ('Second'), ('Third')
It is very unlikely that regular SQL server will insert these rows in different order.
I am trying to replicate the IRR (internal rate of return) function in excel. I found one cfc in riaforge.com but it doesn't return the same value as the excel's irr.
The newton - raphson method uses derivatives and I am not sure how to calculate derivatives in coldfusion.
year cash flow
---- --------
0 -4000
1 1200
2 1410
3 1875
4 1050
should return 14.3% ( from wikipedia's example )
Has anybody done this before?
thanks
Extending to what Jason said, you would need to implement a code that works efficiently and not rely on the brute force algorithm that Falconeyes suggested. nothing personal here the first time i programmed IRR as a server side script it was using brute force and a day later my web host called me as said they were taking my site offline as the code was consuming 100% system resources
What follows is a step by step IRR calculation using Newton Raphson method and you can follow it and implement the ideas in Cold Fusion
f(x) = -4000(1+i)^0 +1200(1+i)^-1 +1410(1+i)^-2 +1875(1+i)^-3 +1050(1+i)^-4
f'(x) = -1200(1+i)^-2 -2820(1+i)^-3 -5625(1+i)^-4 -4200(1+i)^-5
x0 = 0.1
f(x0) = 382.0777
f'(x0) = -9560.2616
x1 = 0.1 - 382.0777/-9560.2616 = 0.139965195884
Error Bound = 0.139965195884 - 0.1 = 0.039965 > 0.000001
x1 = 0.139965195884
f(x1) = 25.1269
f'(x1) = -8339.5497
x2 = 0.139965195884 - 25.1269/-8339.5497 = 0.142978177747
Error Bound = 0.142978177747 - 0.139965195884 = 0.003013 > 0.000001
x2 = 0.142978177747
f(x2) = 0.126
f'(x2) = -8256.0861
x3 = 0.142978177747 - 0.126/-8256.0861 = 0.142993440675
Error Bound = 0.142993440675 - 0.142978177747 = 1.5E-5 > 0.000001
x3 = 0.142993440675
f(x3) = 0
f'(x3) = -8255.6661
x4 = 0.142993440675 - 0/-8255.6661 = 0.142993441061
Error Bound = 0.142993441061 - 0.142993440675 = 0 < 0.000001
IRR = x4 = 0.142993441061 or 14.3%
I don't know what ColdFusion is, but the idea for finding IRR is very simple.
The IRR is a number r such that
sum i = 0 to N C_i * (1 + r)^(-t_i) = 0
where there are N + 1 cashflows C_0, C_1, ..., C_N at times t_0, t_1, ..., t_N. Define
f(r) = sum i = 0 to N C_i * (1 + r)^(-t_i).
Then
f'(r) = sum i = 0 to N -C_i * (1 + r)^(-t_i - 1).
Choosing an initial guess r_0 and iterate via
r_{n + 1} = r_n - f(r_n) / f'(r_n)
In your specific example, you have
t_0 = 0 C_0 = -4000
t_1 = 1 C_1 = 1200
t_2 = 2 C_2 = 1410
t_3 = 3 C_3 = 1875
t_4 = 4 C_4 = 1050
Try a guess of r_0 = 0.1.
Again, I don't know what ColdFusion is, but it has to be a programming language, and so it should allow this basic math to be computed.
<cffunction name="calcIRR">
<cfargument name="arrCashFlow" type="Array" required="true" hint="array of cashflow">
<cfscript>
var guess = 0.1;
var inc = 0.00001;
do {
guess += inc;
npv = 0; //net present value
for (var i=1; i<=arrayLen(arguments.arrCashFlow); i++) {
npv += arguments.arrCashFlow[i] / ((1 + guess) ^ i);
}
} while ( npv > 0 );
guess = guess * 100;
</cfscript>
<cfreturn guess>
</cffunction>
<cfscript>
cFlow = arrayNew(1);
cFlow[1] = -4000;
cFlow[2] = 1200;
cFlow[3] = 1410;
cFlow[4] = 1875;
cFlow[5] = 1050;
c = calcIRR(cFlow);
</cfscript>
<cfdump var="#cFlow#">
<cfdump var="#c#">
I tried all submited solutions and none of them worked like it should(like in excel).
Here is the code for calculating XIRR that is working like it should. For the IRR you just need to change this line:
<cfset npv = npv + (arguments.values[i] / ((1 + arguments.rate) ^ time_span))>
And here is the whole script
<cfoutput>
#XIRR(values=[-5000,500,110500], dates=["2015-07-06","2016-07-06","2017-07-06"])#
</cfoutput>
<cffunction name="XIRR">
<cfargument name="values" required="true">
<cfargument name="dates" required="true">
<cfset var do_calculation = check_data(values=arguments.values, dates=arguments.dates)>
<cfif do_calculation.is_ok>
<cfset var rate = 1>
<cfset var npv = calculate_NPV(rate=rate, values=arguments.values, dates=arguments.dates)>
<cfloop condition="#npv# gt 10e-6">
<cfset rate = rate + 1>
<cfset npv = calculate_NPV(rate=rate, values=arguments.values, dates=arguments.dates)>
</cfloop>
<cfloop from="1" to="6" index="pow">
<cfset fac = 1 / (10 ^ pow)>
<cfset npv = 0>
<cfloop condition="#npv# lt 10e-6">
<cfset rate = rate - fac>
<cfset npv = calculate_NPV(rate=rate, values=arguments.values, dates=arguments.dates)>
</cfloop>
<cfset rate = rate + fac>
</cfloop>
<cfreturn rate>
<cfelse>
<cfreturn "error: #do_calculation.error#">
</cfif>
</cffunction>
<cffunction name="check_data">
<cfargument name="values" required="true">
<cfargument name="dates" required="true">
<cfset var is_ok = true>
<cfset var has_negative = false>
<cfset var has_positive = false>
<cfset var error = 0>
<cfset var return = structNew()>
<cfset var date_prev = "">
<cfset var date_curr = "">
<cfif arguments.values[1] gte 0>
<cfset is_ok = false>
<cfset error = -1>
</cfif>
<cfloop array="#arguments.values#" item="value">
<cfif value gt 0>
<cfset has_positive = true>
</cfif>
<cfif value lt 0>
<cfset has_negative = true>
</cfif>
</cfloop>
<cfif !has_negative or !has_positive>
<cfset is_ok = false>
<cfset error = -2>
</cfif>
<cfif arrayLen(arguments.values) neq arrayLen(arguments.dates)>
<cfset is_ok = false>
<cfset error = -3>
</cfif>
<cfloop from="2" to="#arrayLen(arguments.dates)#" index="d">
<cfset date_prev = arguments.dates[d-1]>
<cfset date_curr = arguments.dates[d]>
<cfif dateDiff("d", date_prev, date_curr) lte 0>
<cfset is_ok = false>
<cfset error = -4>
</cfif>
</cfloop>
<cfset return.is_ok = is_ok>
<cfset return.error = error>
<cfreturn return>
</cffunction>
<cffunction name="calculate_NPV">
<cfargument name="rate" required="false" default="1">
<cfargument name="values" required="true">
<cfargument name="dates" required="true">
<cfset var npv = arguments.values[1]>
<cfset var time_span = "">
<cfloop from="2" to="#arrayLen(arguments.values)#" index="i">
<cfset time_span = dateDiff('d', arguments.dates[1], arguments.dates[i]) / 365>
<cfset npv = npv + (arguments.values[i] / ((1 + arguments.rate) ^ time_span))>
</cfloop>
<cfreturn npv>
</cffunction>