Log base 2 calculation in python - python-2.7

I am trying to calculate the average disorder in ID trees. My code is below:
Republican_yes = yes.count('Republican')
Democrat_yes = yes.count('Democrat')
Republican_no = no.count('Republican')
Democrat_no = no.count('Democrat')
Indep_yes = yes.count('Independent')
Indep_no = no.count('Independent')
disorder_yes= Republican_yes/len(yes)*(math.log(float(Republican_yes)/len(yes),2))+ Democrat_yes/len(yes)*(math.log(float(Democrat_yes)/len(yes),2))+Indep_yes/len(yes)*(math.log(float(Indep_yes)/len(yes),2))
disorder_no= Republican_no/len(no)*(math.log(float(Republican_no)/len(no),2))+Democrat_no/len(no)*(math.log(float(Democrat_no)/len(no),2))+Indep_no/len(no)*(math.log(float(Indep_no)/len(no),2))
avgdisorder = -len(yes)/(len(yes)+len(no))*disorder_yes - len(no)/(len(yes)+len(no))*disorder_no
return avgdisorder
why do I keep getting math domain error?

Check if the lengths are 0 or not, else you will get MathError.
if len(yes):
disorder_yes= Republican_yes/len(yes)*(math.log(float(Republican_yes)/len(yes),2))+ Democrat_yes/len(yes)*(math.log(float(Democrat_yes)/len(yes),2))+Indep_yes/len(yes)*(math.log(float(Indep_yes)/len(yes),2))
if len(no):
disorder_no= Republican_no/len(no)*(math.log(float(Republican_no)/len(no),2))+Democrat_no/len(no)*(math.log(float(Democrat_no)/len(no),2))+Indep_no/len(no)*(math.log(float(Indep_no)/len(no),2))
if len(yes) or len(no):
avgdisorder = -len(yes)/(len(yes)+len(no))*disorder_yes - len(no)/(len(yes)+len(no))*disorder_no
If you want, you can always add the else clause for all 3 if statements as per your requirement.

Related

I am trying to get the difference of measure values in DAX but getting 0

I will like to get the difference between two measure values using DAX
AADPMAU_Increase = [AADPMAU_End] - [AADPMAU_Start]
But when I do the subtraction, I am getting 0
I have tried different things, but nothing is working
The two values are start and end values that are set by date selector filters. It appears that the calculation is always treating both as equal therefore returning 0
AADPMAU_Start = CALCULATE(AADPTable[AADPMAU_Sum],FILTER(DimDate,DimDate[StartDate] = DimDate[StartDate]))
AADPMAU_End = CALCULATE(AADPTable[AADPMAU_Sum],FILTER(DimDate,DimDate[EndDate] = DimDate[EndDate]))
AADPMAU Increase =
var at_end = AADPTable[AADPMAU_End]
var at_start = AADPTable[AADPMAU_Start]
return at_end - at_start

IF Formula in Power BI DAX

I would like to do a nested if statement within powerbi, I need to have multiple if statements in one column with some returning - value depending on the if statement.
I have tried to below however theyre all coming back as false.
Calculated value = if('TableName'[ColumnName1] = "exp1" && 'TableName'[columnName2] = "exp2", 'TableName'[value]|| if('TableName'[ColumnName1] = "exp1" && 'TableName'[ColumnName2] = "exp3", - 'TableName'[value],""))
In the first if you don't have any output to the false result. I Add an extra empty value in your calculated value as below only to exemplify what you need to add:
Calculated value = if('TableName'[ColumnName1] = "exp1" && 'TableName'[columnName2] = "exp2", 'TableName'[value]|| if('TableName'[ColumnName1] = "exp1" && 'TableName'[ColumnName2] = "exp3", - 'TableName'[value],""),"")
Check the example and tell something about this, please

Crystal Report converting value to number with symbol

I have an issue with a Crystal Report that I'm creating. I am using fields from a database and am pulling in the result value where the analysis field is equal to certain values.
In the condition the first check looks at the analysis field and checks if its equal to "Conf". The result for this is "<10"
The second check looks at the analysis field and checks if its equal to "Original". The result for this is "20".
I want the results to display in the order above however with the following basic logic it returns the result of 20.
if analysis = "conf" then result
else if analysis = "Original" then result
I was having this issue with multiple records however solved it by converting both results to numbers (toNumber(Result)). However this record has the less than symbol contained within the field value which causes the conf result to "be skipped" and will display the original result instead. I've tried a few things without success. Here is the code for the condition of where I'm at below. I fell this is way to complex logic but I've just added to it as I've had ideas and it shows what I've tried.
if {UNITS} = "CFU_G" then
if {ANALYSIS} = "CONF" and
{RESULT}="" or
{RESULT} = "0" then 0
else if {ANALYSIS} = "CONF"
then if isNumeric({RESULT}) then
tonumber({RESULT}) else
tonumber(Replace ({RESULT}, "<", ""))
else
if {UNITS} = "CFU_G" then
if {ANALYSIS} = "Original" and
{RESULT}="" or
{RESULT} = "0" then 0
else if {ANALYSIS} = "Original"
then if isNumeric({RESULT}) then
tonumber({RESULT}) else
tonumber(Replace ({RESULT}, "<", ""))
Thanks,
Tom
This was the solution I came up with.
Field 1
whileprintingrecords;
stringvar vResult := "";
Field 2
whileprintingrecords;
stringvar vResult;
vResult := if {RESULT.UNITS} = "CFU_G"
and {RESULT.ANALYSIS} = "CRA_LIS_ENU_CONF_MPCRAM29"
then {RESULT.FORMATTED_ENTRY}
else if {RESULT.ANALYSIS} = "CRA_LIST_ENU_MPCRAM29"
and {RESULT.UNITS} = "CFU_G"
and vResult = ""
then {RESULT.FORMATTED_ENTRY}
Field 3
whileprintingrecords;
stringvar vResult;
vResult;

“quantize result has too many digits for current context” error on save

I know this has been asked a number of times but somehow that didn't work out. I have this model field in model Song.
sent_score = models.DecimalField(default= 0.0,max_digits=4,decimal_places=2,blank=True)
In my view i update sent score the following ways.
song_item = Song.objects.get(id=id)
com_list = Comment.objects.filter(song_id=id)
com_count = com_list.count()
pos_comments = com_list.filter(sentiment='positive')
pos_count = pos_comments.count()
getcontext().prec = 2
sent_score = Decimal(pos_count)/Decimal(com_count)
However it still gives me this error:
InvalidOperation: quantize result has too many digits for current context
I also tried the quantize method in this way:
sc = Decimal(pos_count)/Decimal(com_count)
Decimal(sc).quantize(Decimal('12.12'), rounding = ROUND_DOWN)
song_item.sent_score = sc
song_item.save()
but it still gives the same error please tell me where am i going wrong
You should not use getcontext().prec = 2 as you did in your first try, because it changes the precision for everything, not just this one calculation.
The issue with your second example is, that Decimal(sc).quantize(Decimal('12.12'), rounding=ROUND_DOWN) and even sc.quantize(Decimal('12.12'), rounding=ROUND_DOWN) do not change sc. Here is an example that works:
sc = Decimal(pos_count)/Decimal(com_count)
sc_adjusted = sc.quantize(Decimal('12.12'), rounding=ROUND_DOWN)
song_item.sent_score = sc_adjusted
song_item.save()

Why does Relation.size sometimes return a Hash in Rails 4

I can run a query in two different ways to return a Relation.
When I interrogate the size of the Relation one query gives a Fixnum as expected the other gives a Hash which is a hash of each value in the Relations Group By statement with the number of occurrences of each.
In Rails 3 I assume it always returned a Fixnum as I never had a problem whereeas with Rails 4 it sometimes returns a Hash and a statement like Rel.size.zero? gives the error:
undefined method `zero?' for {}:Hash
Am I best just using the .blank? method to check for zero records to be sure of avoiding unexpected errors?
Here is a snippet of code with looging statements for the two queries and the resulting log
CODE:
assessment_responses1=AssessmentResponse.select("process").where("client_id=? and final = ?",self.id,false).group("process")
logger.info("-----------------------------------------------------------")
logger.info("assessment_responses1.class = #{assessment_responses1.class}")
logger.info("assessment_responses1.size.class = #{assessment_responses1.size.class}")
logger.info("assessment_responses1.size value = #{assessment_responses1.size}")
logger.info("............................................................")
assessment_responses2=AssessmentResponse.select("distinct process").where("client_id=? and final = ?",self.id,false)
logger.info("assessment_responses2.class = #{assessment_responses2.class}")
logger.info("assessment_responses2.size.class = #{assessment_responses2.size.class}")
logger.info("assessment_responses2.size values = #{assessment_responses2.size}")
logger.info("-----------------------------------------------------------")
LOG
-----------------------------------------------------------
assessment_responses1.class = ActiveRecord::Relation::ActiveRecord_Relation_AssessmentResponse
(0.5ms) SELECT COUNT(`assessment_responses`.`process`) AS count_process, process AS process FROM `assessment_responses` WHERE `assessment_responses`.`organisation_id` = 17 AND (client_id=43932 and final = 0) GROUP BY process
assessment_responses1.size.class = Hash
CACHE (0.0ms) SELECT COUNT(`assessment_responses`.`process`) AS count_process, process AS process FROM `assessment_responses` WHERE `assessment_responses`.`organisation_id` = 17 AND (client_id=43932 and final = 0) GROUP BY process
assessment_responses1.size value = {"6 Month Review(1)"=>3, "Assessment(1)"=>28, "Assessment(2)"=>28}
............................................................
assessment_responses2.class = ActiveRecord::Relation::ActiveRecord_Relation_AssessmentResponse
(0.5ms) SELECT COUNT(distinct process) FROM `assessment_responses` WHERE `assessment_responses`.`organisation_id` = 17 AND (client_id=43932 and final = 0)
assessment_responses2.size.class = Fixnum
CACHE (0.0ms) SELECT COUNT(distinct process) FROM `assessment_responses` WHERE `assessment_responses`.`organisation_id` = 17 AND (client_id=43932 and final = 0)
assessment_responses2.size values = 3
-----------------------------------------------------------
size on an ActiveRecord::Relation object translates to count, because the former tries to get the count of the Relation. But when you call count on a grouped Relation object, you receive a hash.
The keys of this hash are the grouped column's values; the values of this hash are the respective counts.
AssessmentResponse.group(:client_id).count # this will return a Hash
AssessmentResponse.group(:client_id).size # this will also return a Hash
This is true for the following methods: count, sum, average, maximum, and minimum.
If you want to check for rows being present or not, simply use exists? i.e. do the following:
AssessmentResponse.group(:client_id).exists?
Instead of this:
AssessmentResponse.group(:client_id).count.zero?