Get an unmapped field in a native query in Doctrine2 - doctrine-orm

I have a function in Symfony3 with Doctrine2 which is searching for the nearest partner, using latitude and longitude:
public function findNearestPartner($lat,$lng) {
$rsm=new ResultSetMappingBuilder($this->_em);
$rsm->addRootEntityFromClassMetadata('AppBundle\Entity\Partner','p');
$sqlQuery="SELECT p.*, (6371 * acos(cos(radians(:lat)) * cos(radians(p.latitude)) * cos(radians(p.longitude) - radians(:lng)) + sin(radians(:lat)) * sin(radians(p.latitude)))) AS distance
FROM sp_partner p
ORDER BY distance ASC
LIMIT 0,1";
$query=$this->_em
->createNativeQuery($sqlQuery,$rsm)
->setParameter('lat',$lat)
->setParameter('lng',$lng)
;
return $query->getOneOrNullResult();
}
As you see, I get the nearest Partner-Entity back - but there is also the field "distance", which I don't get back (but it would be very useful). Is there any way to get the value of this field?
I read in the docu (http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/native-sql.html), but I can't find anything useful for this case.

You can make it through addScalarResult.
$rsm=new ResultSetMappingBuilder($this->_em);
$rsm->addRootEntityFromClassMetadata('AppBundle\Entity\Partner','p');
$rsm->addScalarResult('distance', 'distance');
the result will be
array:2 [▼
0 => Partner{...},
distance => xxx
]

Related

How to implement the Luhn alorithm in OCL

I am trying to find the Luhn algorithm in OCL to check the validity of ISIN. Can anyone provide a code example would it be great!
In the German Wikipedia article about the Luhns algorithm (https://de.wikipedia.org/wiki/Luhn-Algorithmus) you can find an example to calculate the value for an ident of 446-667-651. The algorithm below calculates the correct value of 40.
let list = '446667651'.ToCharArray.strToInt in
Sequence{1..list->size}
->Collect(i|
if (list->size-i).Mod(2)=0 then
list.at(i)
else
(list.at(i)*2).Mod(9)
endif)
->Sum
Maybe you need some adaptions for calculating the value for ISINs.
In pure OCL using the example from https://en.wikipedia.org/wiki/Luhn_algorithm
let s = Sequence{7,9,9,2,7,3,9,8,7,1} in
(Sequence{1..s->size()}
->collect(i |
let t = s->at(i) in
if i.mod(2) = 1
then t
else let tt = 2 * t in tt.div(10) + tt.mod(10)
endif)
->sum()*9)
.mod(10)
Create a class:
Attribute NextMult1Or2:Integer
Method MultWith2Or1SumBiggerThan10(v:Integer):Integer
Method GetCheckSum(input:String):Integer
The first method MultWith2Or1SumBiggerThan10:
let res=v*self.NextMult1Or2 in
(
if self.NextMult1Or2=2 then
self.NextMult1Or2:=1
else
self.NextMult1Or2:=2
endif;
if res>10 then
res-9
else
res
endif
)
And the second method GetCheckSum(input:String):Integer
self.NextMult1Or2:=2;
input.ToCharArray->collect(c|
let i=Integer.Parse(c) in (
self.MultWith2Or1SumBiggerThan10(i)
)
)->sum
To calculate the checksum - send in all but check digit to GetCheckSum - the check digit is (((res+10) / 10).Truncate*10)-res (ie the diff from nearest 10:th above)
To check a sequence send in all including check digit to GetCheckSum - if res.Mod(10)= 0 it has passed

Is it possible to create an inner join between two tables showing all B that contain A?

I have two tables: Kanji, and Vocabulary. Imagine the kanji table looks like this:
目
一
人
And the vocabulary table looks like this:
目的
一番目
一人
二人
人々
注目
目標
一匹
I want to generate a table that finds all vocabulary which contains the kanji in the kanji table and list them together. So the end result would look like this:
人 一人
二人
人々
一 一人
一番目
一匹
目 目的
一番目
注目
目標
I'm not sure how to go about this. If I have just one kanji, I can use the QUERY function to generate all of the vocabularies which contain that one kanji. But can I create a dynamic table which essentially inner joins the "kanji" and "vocabulary" tables, looking for every instance of "vocabulary" contains "kanji"?
I tried using a QUERY to combine the two tables, but it won't work because the tables are mismatched in size:
=QUERY({C1:C296,D1:D224}, "SELECT Col2 WHERE Col1 contains Col2")
In the above example, the C column / Col2 is vocabulary, the D column / Col1 is kanji.
Is there a way to do this using Google Sheets?
The simplest workaround is to get intersections by 1 value:
=FILTER(D:D;REGEXMATCH(D:D;"目"))
The picture shows how to use the copy of this function to get all intersections
The other approach is to use big array-formula like:
=TRANSPOSE(SPLIT(TEXTJOIN(",";1;TRANSPOSE(ARRAYFORMULA(IF(REGEXMATCH(A1:A8;TRANSPOSE(B1:B3));A1:A8;))));","))
=ARRAYFORMULA(SORT(TRIM(SPLIT(TRANSPOSE(SPLIT(QUERY(TRANSPOSE(QUERY(TRANSPOSE(
IF(IFERROR(REGEXEXTRACT(IFERROR(REGEXEXTRACT(C1:C, REPT("(.)", LEN(C1:C)))),
TEXTJOIN("|", 1, A1:A)))<>"", "♦"&IFERROR(REGEXEXTRACT(IFERROR(
REGEXEXTRACT(C1:C, REPT("(.)", LEN(C1:C)))), TEXTJOIN("|", 1, A1:A)))&"♣"&C1:C, ))
,,999^99)),,999^99), "♦")), "♣"))))
seriously, much better way, just add a custom function:
/**
* inner join on equality
*
* #param {Range} items1 Table 1
* #param {Range} items2 Table 2
* #param {Integer} ix1 0-based index of key in Table1
* #param {Integer} ix2 0-based index of key in Table2
*
* #customfunction
* #author marc meyer (marqueymarc)
*/
function innerJoinEQ(items1 = [[]], items2 = [[]], ix1= 0, ix2= 0) {
var res = [];
var item2ix = 0;
var map = new Map();
items1 = Array.isArray(items1)? items1: [[items1]];
items2 = Array.isArray(items2)? items2: [[items2]];
items2.forEach((item2) => {
let entries = map.get(item2[ix2]) || [];
entries.push(item2);
map.set(item2[ix2], entries);
});
items1.forEach((item1) => {
let entries = map.get(item1[ix1]) || [];
entries.forEach((rightPart) => {
let cp = rightPart.slice();
cp.splice(ix2, 1);
res.push([...item1, ...cp]);
})
});
return res;
}

Stuck adding formula to dynamically added columns

I have a query that returns a dynamic number of columns. I need to dynamically add the same amount of custom columns. I have successfully gotten this far. I'm stuck creating the formulas for the custom columns. This is what I have so far. (This is not the actual query, this is simplified)
Here is the Code:
Test = List.Accumulate(MyList, Source,
(state, current) => Table.AddColumn(
state, "A Temp" & Number.ToText(current), each [A1])
)
For now, I just added [A1] as a place holder for the formula. I need the formula to accumulate as follows:
A Temp1 = [A1] / [TOTAL]
A Temp2 = [A2] / [TOTAL]
A Temp3 = [A3] / [TOTAL]
Above is not actual code. Just what I need the formulas to do for each custom column.
Is this possible? I have tried everything I could think of. I'm using power query in excel BTW.
This isn't exactly what you asked for, but I think it will help.
Test = List.Accumulate(
List.Select(Table.ColumnNames(Source), each _ <> "TOTAL"),
Source,
(state, current) => Table.AddColumn(state,
"Temp " & current,
each Record.Field(_, current) / [TOTAL]))
It's not exactly what you asked for as it gives column names like Temp A1 instead of A Temp1.

JSDoc describe object values only

Say I've object like that:
const Companies = {Mazda : {revenue:50000, employees:1000},
Honda: {revenue: 102324, employees:2031}}
And this function:
const totalRevenue = (companies) =>
Object.values(companies)
.map(companyObject => companyObject.revenue)
.reduce((total, companyRevenue)=> total + companyRevenue)
How do I use JSDoc to tell the function
totalRevenue that the companies object is an object that every key it has, has a value of the kind {revenue: Number, employees: Number}
I'm specifically interested in something that WebStorm will understand.
You can describe every key in object with the {Object.<string, number>} notation. see more syntax examples here: http://usejsdoc.org/tags-type.html
for your specific scenario:
/**
* #param {Object.<string, {revenue: number, employees: number}>} companies
*/
const totalRevenue = (companies) =>
Object.values(companies)
.map(companyObject => companyObject.revenue)
.reduce((total, companyRevenue)=> total + companyRevenue)

Is Conger's kappa available in Stata?

Is the modified version of kappa proposed by Conger (1980) available in Stata? Tried to google it to no avail.
This is an old question, but in case anyone is still looking--the SSC package kappaetc now calculates that, along with every other inter-rater statistic you could ever want.
Since no one has responded with a Stata solution, I developed some code to calculate Conger's kappa using the formulas provided in Gwet, K. L. (2012). Handbook of Inter-Rater Reliability (3rd ed.), Gaithersburg, MD: Advanced Analytics, LLC. See especially pp. 34-35.
My code is undoubtedly not as efficient as others could write, and I would welcome any improvements to the code or to the program format that others wish to make.
cap prog drop congerkappa
prog def congerkappa
* This program has only been tested with Stata 11.2, 12.1, and 13.0.
preserve
* Number of judges
scalar judgesnum = _N
* Subject IDs
quietly ds
local vlist `r(varlist)'
local removeit = word("`vlist'",1)
local targets: list vlist - removeit
* Sums of ratings by each judge
egen judgesum = rowtotal(`targets')
* Sum of each target's ratings
foreach i in `targets' {
quietly summarize `i', meanonly
scalar mean`i' = r(mean)
}
* % each target rating of all target ratings
foreach i in `targets' {
gen `i'2 = `i'/judgesum
}
* Variance of each target's % ratings
foreach i in `targets' {
quietly summarize `i'2
scalar s2`i'2 = r(Var)
}
* Mean variance of each target's % ratings
foreach i in `targets' {
quietly summarize `i'2, meanonly
scalar mean`i'2 = r(mean)
}
* Square of mean of each target's % ratings
foreach i in `targets' {
scalar mean`i'2sq = mean`i'2^2
}
* Sum of variances of each target's % ratings
scalar sumvar = 0
foreach i in `targets' {
scalar sumvar = sumvar + s2`i'2
}
* Sum of means of each target's % ratings
scalar summeans = 0
foreach i in `targets' {
scalar summeans = summeans + mean`i'2
}
* Sum of meansquares of each target's % ratings
scalar summeansqs = 0
foreach i in `targets' {
scalar summeansqs = summeansqs + mean`i'2sq
}
* Conger's kappa
scalar conkappa = summeansqs -(sumvar/judgesnum)
di _n "Conger's kappa = " conkappa
restore
end
The data structure required by the program is shown below. The variable names are not fixed, but the judge/rater variable must be in the first position in the data set. The data set should not include any variables other than the judge/rater and targets/ratings.
Judge S1 S2 S3 S4 S5 S6
Rater1 2 4 2 1 1 4
Rater2 2 3 2 2 2 3
Rater3 2 5 3 3 3 5
Rater4 3 3 2 3 2 3
If you would like to run this against a test data set, you can use the judges data set from StataCorp and reshape it as shown.
use http://www.stata-press.com/data/r12/judges.dta, clear
sort judge
list, sepby(judge)
reshape wide rating, i(judge) j(target)
rename rating* S*
list, noobs
* Run congerkappa program on demo data set in memory
congerkappa
I have run only a single validation test of this code against the data in Table 2.16 in Gwet (p. 35) and have replicated the Conger's kappa = .23343 as calculated by Gwet on p. 34. Please test this code on other data with known Conger's kappas before relying on it.
I don't know if Conger's kappa for multiple raters is available in Stata, but it is available in R via the irr package, using the kappam.fleiss function and specifying the exact option. For information on the irr package in R, see http://cran.r-project.org/web/packages/irr/irr.pdf#page.12 .
After installing and loading the irr package in R, you can view a demo data set and Conger's kappa calculation using the following code.
data(diagnoses)
print(diagnoses)
kappam.fleiss(diagnoses, exact=TRUE)
I hope someone else here can help with a Stata solution, as you requested, but this may at least provide a solution if you can't find it in Stata.
In response to Dimitriy's comment below, I believe Stata's native kappa command applies either to two unique raters or to more than two non-unique raters.
The original poster may also want to consider the icc command in Stata, which allows for multiple unique raters.