问:
Query taking too long to execute and a unbelievable cost
I am currently writing a query and I ran explain to check the query cost and time taken to run it. I observed that the cost is too high after I ran explain. Please find the below query.

```<code>create table l1.dm_sc_temp_pl_activity_p as
select rel,licamt,tcamt, spsc, pdn, pmn4, pcs, clsldt, pci, cpdt, orgtin, bt, pcpldt, slc, sps, pm3, "ln", idt, ddt, rps, df, dat, pz, rpn, pih, pipid, pcpn, psa2, ingdt, incid, uqt,
acoid||orgid  as orgid, pn, fn, pc, pm5, pm4, rpnpi, pfdt, sfn, catp, pdcs, pm1, st, pl, cltc, cpat, incn, gn, adjsn, clsfdt, acoid, sstp, orgn, sln, sid, drg, rcdt, tel3, pm2, rpsc, pmn3,
acoid||orgid||orgrid as orgrid, alat, inpn, tel2, drgn, pcpidt, acon, pcpid, id, pcpslid, pd, dob, psa1, orgrn, pcpslidt, pcy, pcpsln, pmn2, pmn5, cid, inpid, adjs, pmn1, eldt, empi, pcpfdt, cltp, tel1, pldt, pstn, spn, spnpi, mn, clid,
efdt, capdt,ssa1,ssa2,sci,sstn,scy,sz,ftsa1,ftstn,ftz,ftci,ad1,ad2,ad3,ad4,ad5,
ad6,ad7,ad8,ad9,ad10,ad11,ad12,ad13,ad14,ad15,ad16,ad17,ad18,ad19,ad20,ad21,ad22,ad23,ad24,ad25,ad26,ad27,ad28,ad29,
adn1,adn2,adn3,adn4,adn5,adn6,adn7,adn8,adn9,adn10,adn11,adn12,adn13,adn14,
adn15,adn16,adn17,adn18,adn19,adn20,adn21,adn22,adn23,adn24,adn25,adn26,adn27,adn28,adn29
from (
select
 c.prov_addr1 as ftsa1,
c.prov_state as ftstn,
c.prov_zip as ftz,
c.prov_city as ftci,
c.iscap as rel,
cast(c.claimsvc_billedamt as decimal(18,2)) as licamt,
cast(c.claim_billedamt as decimal(18,2))  as tcamt,
trim(m.id) as id ,trim(m.tel1) as tel1,trim(m.tel2) as tel2,trim(m.tel3)as tel3,
'' as empi,trim(m.gn) as gn,psa1,psa2,pci,pcpldt,pl,trim(mn) as mn,trim(pz) as pz,trim(ln) as ln,
cast(m.dob as date) as dob,'N' as df,m.pcy,trim(m.fn) as fn,m.pcpfdt,m.pstn,
ssa1,ssa2,sci,sstn,scy,trim(sz) as sz,
--dm_prov
case when (trim(p.npi) in ('NULL','NA','')) then '' else trim(p.npi) end as pcpid,
case when (trim(p.npi) in ('NULL','NA','')) then '' else 'NPI' end as pcpidt,
p.lastname||','||p.firstname||' '||p.middlename as pcpn,
-- dm_vend
case when (trim(v.taxid) in ('NULL','NA','')) then '' else trim(v.taxid) end as pcpslid,
v.vendname as pcpsln,
case when (trim(v.taxid) in ('NULL','NA','')) then '' else 'NPI'  end as pcpslidt,
-- level
case when l."HPName"='Aetna Health of California' then '13'
when l."HPName"='Health Net' then '14'
when l."HPName"='Blue Shield of California' then '12'
when l."HPName"='United Healthcare of California' then '15'
when l."HPName"='Cigna for Health Care Professionals' then '16'
when l."HPName"='Anthem Blue Cross' then '17' end as incid,
l."HPName" as incn,
Case
when l."Progdescr"='DHMNSC United Healthcare Commercial' then '30'
when l."Progdescr"='DHMNSC Blue Shield 65 Plus' then '29'
when l."Progdescr"='DHMNSC United Healthcare Canopy Commercial' then '31'
when l."Progdescr"='DHMNSC United Healthcare Medicare Solutions' then '32'
when l."Progdescr"='DHMNSC Blue Shield Commercial' then '28'
when l."Progdescr"  in ('DHMNSC Health Net SmartCare Commercial','DHMNSC Health Net Canopy UC Blue and Gold Commercial',
'DHMNSC Health Net Canopy Care Commercial') then '33'
when l."Progdescr"='DHMNSC Aetna Commercial' then '34'
when l."Progdescr"='DHMNSC Cigna Commercial' then '35'
when l."Progdescr"='DHMNSC Health Net Commercial' then '36'
when l."Progdescr"='DHMNSC Anthem Blue Cross Commercial' then '37'
when l."Progdescr"='DHMNSC Health Net Seniority Plus' then '38'
when l."Progdescr"='DHMNSC United Healthcare Canopy Medicare Advantage' then '50' end as inpid,
case when l."Progdescr"  in ('DHMNSC Health Net SmartCare Commercial','DHMNSC Health Net Canopy UC Blue and Gold Commercial',
'DHMNSC Health Net Canopy Care Commercial') then 'DHMNSC Health Net SmartCare Commercial'
else l."Progdescr"  end as inpn,
'3' as acoid,
'DHMN-SC' as acon,
case when l."LOB" ='M' then '6'
    when l."LOB" ='C' then '7' else '8' end as orgid,
case when l."LOB"='C' then 'Commercial'when l."LOB"='M' then 'Medicare' else "LOB" end as orgn,
case when  l."HPCode" not in ('PGM000295','PGM000294','PGM000333','PGM000332','PGM000326') then '7'
     when l."HPCode" in ('PGM000295','PGM000294','PGM000333','PGM000332','PGM000326') then '9' else '8' end as orgrid,
case when  l."HPCode" not in ('PGM000295','PGM000294','PGM000333','PGM000332','PGM000326') then 'Non Canopy'
     when l."HPCode" in ('PGM000295','PGM000294','PGM000333','PGM000332','PGM000326') then 'Canopy' else 'Other MedGroup' end as orgrn,
-- hardcode columns
'3a1bcd23-d88c-4c70-8ffa-267673232647' as pipid,
'Claims' as st,
l."HPName" as sstp,
'DataMart.bak' as sfn,
current_date as rcdt,
current_date as ingdt,
'claimline' as cltp,
'5' as sid,
'Patient ID' as idt,
 -- dm_claim
trim(c.claimno) as cid,
trim(c.seq) as clid,
'Professional' as cltc,
case when (trim(c.billtype) in ('','NULL','NA') or trim(c.billtype) is null)
    then '' else trim(c.billtype) end as bt,
case when (trim(c.claim_fromdate) in ('','NULL','NA'))then null
    else cast(c.claim_fromdate as date) end as efdt,
case when (trim(c.claim_todate) in ('','NULL','NA'))then null
    else cast(c.claim_todate as date) end as eldt,
case when (trim(c.claim_recddate) in ('','NULL','NA'))then null
    else cast(c.claim_recddate as date) end as cpdt,
case when (trim(c.claim_paiddate) in ('','NULL','NA'))then null
    else cast(c.claim_paiddate as date) end as capdt,
case when (c.claim_netamt::decimal(18,2)='0' and c.iscap='1') then cast(c.claim_contramt as decimal(18,2))
else cast(c.claim_netamt as decimal(18,2))  end as pih,
case when trim(c.claimno)  like '%A1' then 'A'
     when trim(c.claimno)  like '%A2' then 'A'
     when trim(c.claimno)  like '%A3' then 'A'
    when trim(c.claimno)  like '%A4' then 'A'
     when trim(c.claimno)  like '%R1' then 'C'
     when trim(c.claimno)  like '%R2' then 'C'
     when trim(c.claimno)  like '%R3' then 'C'
     when trim(c.claimno)  like '%R4' then 'C'
     when trim(c.claimno)  like '%R5' then 'C' else 'O' end as adjs,
case when trim(c.claimno)  like '%A1' then 'Adjusted'
     when trim(c.claimno)  like '%A2' then 'Adjusted'
     when trim(c.claimno)  like '%A3' then 'Adjusted'
    when trim(c.claimno)  like '%A4' then 'Adjusted'
     when trim(c.claimno)  like '%R1' then 'Cancelled'
     when trim(c.claimno)  like '%R2' then 'Cancelled'
     when trim(c.claimno)  like '%R3' then 'Cancelled'
     when trim(c.claimno)  like '%R4' then 'Cancelled'
     when trim(c.claimno)  like '%R5' then 'Cancelled' else 'Original' end as adjsn,
case when (trim(c.taxid) in ('','NULL','NA') or trim(c.taxid) is null)
    then '' else trim(c.taxid) end as orgtin,
case when (trim(c.npi ) in ('','NULL','NA') or trim(c.npi) is null)
    then '' else trim(c.npi) end as spnpi,
case when (c.prov_name in ('','NULL','NA') or c.prov_name is null) then p1.name else c.prov_name end as spn,
p1.ptxcd as spsc,
p1.psn as sps,
case when (trim(c.drgcode ) in ('','NULL','NA') or trim(c.drgcode) is null)
    then '' else trim(c.drgcode) end as drg,
c.drg_descr as drgn,
case when (trim(c.claimsvc_fromdate) in ('','NULL','NA'))then null
    else cast(c.claimsvc_fromdate as date) end as clsfdt,
case when (trim(c.claimsvc_todate) in ('','NULL','NA'))then null
    else cast(c.claimsvc_todate as date) end  as clsldt,
case when (trim(c.claimsvc_qty ) in ('','NULL','NA') or trim(c.claimsvc_qty) is null)
    then '' else trim(c.claimsvc_qty) end as uqt,
--cast(c.claimsvc_netamt as decimal(18,2)) as catp,
case when c.iscap='1' then cast(c.claimsvc_contramt as decimal(18,2)) else cast(c.claimsvc_netamt as decimal(18,2)) end as catp,
cast(c.claimsvc_allowedamt as decimal(18,2)) as alat,
cast(c.claimsvc_copayamt as decimal(18,2)) as cpat,
cast(c.claimsvc_deductamt as decimal(18,2)) as dat,
case when (trim(c.svccode ) in ('','NULL','NA') or trim(c.svccode) is null)
    then '' else trim(c.svccode) end as pc,
case when (trim(c.svc_longdescr ) in ('','NULL','NA') or trim(c.svc_longdescr) is null)
    then '' else trim(c.svc_longdescr) end as pn,
    ont.csys as pcs,
case when (trim(c.claimsvc_fromdate) in ('','NULL','NA'))then null
    else cast(c.claimsvc_fromdate as date) end as pfdt,
case when (trim(c.claimsvc_todate) in ('','NULL','NA'))then null
    else cast(c.claimsvc_todate as date) end  as pldt,
mf.pm1 ,
mf.pm2 ,
mf.pm3,
mf.pm4,
mf.pm5 ,
mf.pmn1,
mf.pmn2 ,
mf.pmn3,
mf.pmn4,
mf.pmn5,
case when c.poscode in('01','1') then 'Pharmacy'
when c.poscode in ('02','2') then 'Telehealth'
when c.poscode in('03','3') then 'School'
when c.poscode in ('04','4') then 'Homeless Shelter'
when c.poscode in ('05','5') then 'Indian Health Service Free-standing Facility'
when c.poscode='06' then 'Indian Health Service Provider-based Facility'
when c.poscode in ('07','7') then 'Tribal 638 Free-standing Facility'
when c.poscode in ('08','8') then 'Tribal 638 Provider-based Facility'
when c.poscode in('09','9') then 'Prison/Correctional Facility'
when c.poscode in ('10','77') then 'Unassigned'
when c.poscode='11' then 'Office'
when c.poscode='12' then 'Home'
when c.poscode='13' then 'Assisted Living Facility'
when c.poscode='14' then 'Group Home'
when c.poscode='15' then 'Mobile Unit'
when c.poscode='16' then 'Temporary Lodging'
when c.poscode='17' then 'Walk-in Retail Health Clinic'
when c.poscode='18' then 'Place of Employment-Worksite'
when c.poscode='19' then 'Off Campus-Outpatient Hospital'
when c.poscode='20' then 'Urgent Care facility'
when c.poscode='21' then 'Inpatient Hospital'
when c.poscode='22' then 'On Campus-Outpatient Hospital'
when c.poscode='23' then 'Emergency Room – Hospital'
when c.poscode in ('24','B') then 'Ambulatory Surgical Center'
when c.poscode='25' then 'Birthing Center'
when c.poscode='26' then 'Military Treatment Facility'
when c.poscode='31' then 'Skilled Nursing Facility'
when c.poscode='32' then 'Nursing Facility'
when c.poscode='33' then 'Custodial Care Facility'
when c.poscode='34' then 'Hospice'
when c.poscode='41' then 'Ambulance - Land'
when c.poscode='42' then 'Ambulance – Air or Water'
when c.poscode='49' then 'Independent Clinic'
when c.poscode='50' then 'Federally Qualified Health Center'
when c.poscode='51' then 'Inpatient Psychiatric Facility'
when c.poscode='52' then 'Psychiatric Facility-Partial Hospitalization'
when c.poscode='53' then 'Community Mental Health Center'
when c.poscode='54' then 'Intermediate Care Facility/ Individuals with Intellectual Disabilities'
when c.poscode='55' then 'Residential Substance Abuse Treatment Facility'
when c.poscode='56' then 'Psychiatric Residential Treatment Center'
when c.poscode='57' then 'Non-residential Substance Abuse Treatment Facility'
when c.poscode='60' then 'Mass Immunization Center'
when c.poscode='61' then 'Comprehensive Inpatient Rehabilitation Facility'
when c.poscode='62' then 'Comprehensive Outpatient Rehabilitation Facility'
when c.poscode='65' then 'End-Stage Renal Disease Treatment Facility'
when c.poscode='71' then 'Public Health Clinic'
when c.poscode='72' then 'Rural Health Clinic'
when c.poscode in ('81','A') then 'Independent Laboratory'
when c.poscode in ('99','?','O') then 'Other Place of Service' end as sln,
case when c.poscode in ('O','?') then '99'
when c.poscode='A' then '81'
when c.poscode='B' then '24'
when c.poscode in('1','2','3','4','5','6','7','8','9') then '0'||c.poscode else c.poscode end slc,
case when (trim(c.pd ) in ('','NULL','NA') or trim(c.pd ) is null)
    then '' else trim(c.pd) end as pd,
case when (trim(c.pdn ) in ('','NULL','NA') or trim(c.pdn) is null)
    then '' else trim(c.pdn) end as pdn,
pdcs as pdcs,
case when (trim(c.pd ) in ('','NULL','NA') or trim(c.pd ) is null)
    then Null else (
    case when (trim(c.claimsvc_fromdate) in ('','NULL','NA'))then null
    else cast(c.claimsvc_fromdate as date) end )end as ddt,
case when (trim(c.ref_npi ) in ('','NULL','NA') or trim(c.ref_npi) is null)
    then '' else trim(c.ref_npi) end as rpnpi,
    p2."name" as rpn,
p2.ptxcd as rpsc,
p2.psn as rps,
ad1,ad2,ad3,ad4,ad5,
ad6,ad7,ad8,ad9,ad10,ad11,ad12,ad13,ad14,ad15,ad16,ad17,ad18,ad19,ad20,ad21,ad22,ad23,ad24,ad25,ad26,ad27,ad28,ad29,
adn1,adn2,adn3,adn4,adn5,adn6,adn7,adn8,adn9,adn10,adn11,adn12,adn13,adn14,
adn15,adn16,adn17,adn18,adn19,adn20,adn21,adn22,adn23,adn24,adn25,adn26,adn27,adn28,adn29
from (select * from l1.dm_proc_memb
where hpcode in ('PGM000333','PGM000332','PGM000326','PGM000268', 'PGM000269', 'PGM000270', 'PGM000272', 'PGM000273', 'PGM000274', 'PGM000275', 'PGM000276', 'PGM000294', 'PGM000295')) m
inner join l1.dm_proc_claim_p c
on m.memb_id=c.claim_memb
left join l1.dm_proc_modif mf
on mf.claimsvc_id=c.claimsvc_id
left join l1."dm_prov" p on p.prov_id =m.prov_id
left join l1."dm_vend" v on v.vend_id =m.vend_id
left join (select * from l1."level" where "HPCode" in ('PGM000333','PGM000332','PGM000326','PGM000268', 'PGM000269', 'PGM000270', 'PGM000272', 'PGM000273', 'PGM000274', 'PGM000275', 'PGM000276', 'PGM000294', 'PGM000295')) l
on trim(l."HPCode" )=trim(m.hpcode)
left join l2.pd_npi p1 on trim(c.npi)=trim(p1.npi)
left join (select * from l2.pd_ontology where dtp ='procedure' )ont
on trim(ont.cval) =trim(c.svccode )
--left join l2.pd_ontology ontd
--on trim(ontd.cval) =trim(c.pd) and ontd.dtp ='diagnosis'
left join l2.pd_npi p2 on trim(c.ref_npi )=trim(p2.npi)
)f
</code>```

I ran explain command onto this query and I observed the following op:

```<code>  Merge Cond: ((btrim((p2.npi)::text)) = (btrim((c.ref_npi)::text)))
  ->  Sort  (cost=1761851.74..1785989.13 rows=9654958 width=108)
        Sort Key: (btrim((p2.npi)::text))
        ->  Seq Scan on pd_npi p2  (cost=0.00..641739.58 rows=9654958 width=108)
  ->  Materialize  (cost=159139479153552696279040.00..159226719441637676679168.00 rows=17448057616994486190080 width=3383)
        ->  Sort  (cost=159139479153552696279040.00..159183099297595186479104.00 rows=17448057616994486190080 width=3383)
              Sort Key: (btrim((c.ref_npi)::text))
              ->  Merge Join  (cost=456947875487.57..261731712177051860992.00 rows=17448057616994486190080 width=3383)
                    Merge Cond: ((c.claim_memb)::text = (dm_proc_memb.memb_id)::text)
                    ->  Nested Loop Left Join  (cost=157761.50..10839427546273626.00 rows=2707460197662070 width=2450)
                          Join Filter: (btrim((c.npi)::text) = btrim((p1.npi)::text))
                          ->  Nested Loop Left Join  (cost=157761.50..9586754880584.63 rows=56084349568 width=2353)
                                Join Filter: (btrim((pd_ontology.cval)::text) = btrim((c.svccode)::text))
                                ->  Nested Loop Left Join  (cost=0.56..9362416722695.26 rows=43719408 width=2348)
                                      Join Filter: ((mf.claimsvc_id)::text = (c.claimsvc_id)::text)
                                      ->  Index Scan Backward using l1_dm_proc_claims_p_id_idx on dm_proc_claim_p c  (cost=0.56..17080655.54 rows=43719408 width=2036)
                                      ->  Materialize  (cost=0.00..376215.44 rows=14276496 width=352)
                                            ->  Seq Scan on dm_proc_modif mf  (cost=0.00..304832.96 rows=14276496 width=352)
                                ->  Materialize  (cost=157760.93..760260.39 rows=256565 width=14)
                                      ->  Bitmap Heap Scan on pd_ontology  (cost=157760.93..758977.56 rows=256565 width=14)
                                            Recheck Cond: ((dtp)::text = 'procedure'::text)
                                            ->  Bitmap Index Scan on pd_ont_idx_dtp  (cost=0.00..157696.79 rows=256565 width=0)
                                                  Index Cond: ((dtp)::text = 'procedure'::text)
                          ->  Materialize  (cost=0.00..690014.37 rows=9654958 width=108)
                                ->  Seq Scan on pd_npi p1  (cost=0.00..641739.58 rows=9654958 width=108)
                    ->  Materialize  (cost=456947717726.07..459097227591.84 rows=429901973154 width=972)
                          ->  Sort  (cost=456947717726.07..458022472658.96 rows=429901973154 width=972)
                                Sort Key: dm_proc_memb.memb_id NULLS FIRST
                                ->  Merge Right Join  (cost=82668031.11..6531565545.79 rows=429901973154 width=972)
                                      Merge Cond: ((v.vend_id)::text = (dm_proc_memb.vend_id)::text)
                                      ->  Sort  (cost=88160.95..89633.33 rows=588951 width=96)
                                            Sort Key: v.vend_id
                                            ->  Seq Scan on dm_vend v  (cost=0.00..31716.51 rows=588951 width=96)
                                      ->  Materialize  (cost=82579870.16..83309815.39 rows=145989046 width=940)
                                            ->  Sort  (cost=82579870.16..82944842.77 rows=145989046 width=940)
                                                  Sort Key: dm_proc_memb.vend_id
                                                  ->  Merge Right Join  (cost=165139.84..2405511.13 rows=145989046 width=940)
                                                        Merge Cond: ((p.prov_id)::text = (dm_proc_memb.prov_id)::text)
                                                        ->  Index Scan using dm_prov_prov_id on dm_prov p  (cost=0.42..49937.79 rows=239291 width=160)
                                                        ->  Sort  (cost=165139.42..165444.47 rows=122018 width=844)
                                                              Sort Key: dm_proc_memb.prov_id
                                                              ->  Hash Left Join  (cost=485.00..154830.89 rows=122018 width=844)
                                                                    Hash Cond: (btrim((dm_proc_memb.hpcode)::text) = btrim((level."HPCode")::text))
                                                                    ->  Bitmap Heap Scan on dm_proc_memb  (cost=481.71..153985.68 rows=122018 width=812)
                                                                          Recheck Cond: ((hpcode)::text = ANY ('{PGM000333,PGM000332,PGM000326,PGM000268,PGM000269,PGM000270,PGM000272,PGM000273,PGM000274,PGM000275,PGM000276,PGM000294,PGM000295}'::text[]))
                                                                          ->  Bitmap Index Scan on l1_proc_memb_id_idx  (cost=0.00..451.20 rows=122018 width=0)
                                                                    ->  Hash  (cost=3.13..3.13 rows=13 width=64)
                                                                          ->  Seq Scan on level  (cost=0.00..3.13 rows=13 width=64)
                                                                                Filter: (("HPCode")::text = ANY ('{PGM000333,PGM000332,PGM000326,PGM000268,PGM000269,PGM000270,PGM000272,PGM000273,PGM000274,PGM000275,PGM000276,PGM000294,PGM000295}'::text[]))
</code>```

The cost taken by the query is too much. How can I reduce the cost and save time.
P.S I analyzed and found that left joins are increasing the cost. Please tell me how to manage this.

The max size of the tables is 32 GB.

Thanks!!

答:
In addition to what O.Jones indicated, all those instances where you DO have TRIM() calls, you should be STORING your data pre-trimmed to prevent calling trim all over the place.

An additional item to make things easier is to have some lookup tables if they are not already present.  You have all those CASE/WHEN context checks, such as for HPName, Progdesc and HPCode values.  You should be able to have those in a lookup table and JOIN to those to get the given ID.  And more typical than not, it would better to have one lookup table of the ID and the Name/Description once so you are not repeating all records with the literal value 'Aetna Health of California' or 'Blue Shield of California'.  Your child-level table should have the providers ID of 12, 13, 14, etc vs the long name.  That is where things SHOULD be going.

Good luck moving forward.

Body:
I am currently writing a query and I ran explain to check the query cost and time taken to run it. I observed that the cost is too high after I ran explain. Please find the below query.

create table l1.dm_sc_temp_pl_activity_p as
select rel,licamt,tcamt, spsc, pdn, pmn4, pcs, clsldt, pci, cpdt, orgtin, bt, pcpldt, slc, sps, pm3, "ln", idt, ddt, rps, df, dat, pz, rpn, pih, pipid, pcpn, psa2, ingdt, incid, uqt,
acoid||orgid  as orgid, pn, fn, pc, pm5, pm4, rpnpi, pfdt, sfn, catp, pdcs, pm1, st, pl, cltc, cpat, incn, gn, adjsn, clsfdt, acoid, sstp, orgn, sln, sid, drg, rcdt, tel3, pm2, rpsc, pmn3,
acoid||orgid||orgrid as orgrid, alat, inpn, tel2, drgn, pcpidt, acon, pcpid, id, pcpslid, pd, dob, psa1, orgrn, pcpslidt, pcy, pcpsln, pmn2, pmn5, cid, inpid, adjs, pmn1, eldt, empi, pcpfdt, cltp, tel1, pldt, pstn, spn, spnpi, mn, clid,
efdt, capdt,ssa1,ssa2,sci,sstn,scy,sz,ftsa1,ftstn,ftz,ftci,ad1,ad2,ad3,ad4,ad5,
ad6,ad7,ad8,ad9,ad10,ad11,ad12,ad13,ad14,ad15,ad16,ad17,ad18,ad19,ad20,ad21,ad22,ad23,ad24,ad25,ad26,ad27,ad28,ad29,
adn1,adn2,adn3,adn4,adn5,adn6,adn7,adn8,adn9,adn10,adn11,adn12,adn13,adn14,
adn15,adn16,adn17,adn18,adn19,adn20,adn21,adn22,adn23,adn24,adn25,adn26,adn27,adn28,adn29
from (
select
 c.prov_addr1 as ftsa1,
c.prov_state as ftstn,
c.prov_zip as ftz,
c.prov_city as ftci,
c.iscap as rel,
cast(c.claimsvc_billedamt as decimal(18,2)) as licamt,
cast(c.claim_billedamt as decimal(18,2))  as tcamt,
trim(m.id) as id ,trim(m.tel1) as tel1,trim(m.tel2) as tel2,trim(m.tel3)as tel3,
'' as empi,trim(m.gn) as gn,psa1,psa2,pci,pcpldt,pl,trim(mn) as mn,trim(pz) as pz,trim(ln) as ln,
cast(m.dob as date) as dob,'N' as df,m.pcy,trim(m.fn) as fn,m.pcpfdt,m.pstn,
ssa1,ssa2,sci,sstn,scy,trim(sz) as sz,
--dm_prov
case when (trim(p.npi) in ('NULL','NA','')) then '' else trim(p.npi) end as pcpid,
case when (trim(p.npi) in ('NULL','NA','')) then '' else 'NPI' end as pcpidt,
p.lastname||','||p.firstname||' '||p.middlename as pcpn,
-- dm_vend
case when (trim(v.taxid) in ('NULL','NA','')) then '' else trim(v.taxid) end as pcpslid,
v.vendname as pcpsln,
case when (trim(v.taxid) in ('NULL','NA','')) then '' else 'NPI'  end as pcpslidt,
-- level
case when l."HPName"='Aetna Health of California' then '13'
when l."HPName"='Health Net' then '14'
when l."HPName"='Blue Shield of California' then '12'
when l."HPName"='United Healthcare of California' then '15'
when l."HPName"='Cigna for Health Care Professionals' then '16'
when l."HPName"='Anthem Blue Cross' then '17' end as incid,
l."HPName" as incn,
Case
when l."Progdescr"='DHMNSC United Healthcare Commercial' then '30'
when l."Progdescr"='DHMNSC Blue Shield 65 Plus' then '29'
when l."Progdescr"='DHMNSC United Healthcare Canopy Commercial' then '31'
when l."Progdescr"='DHMNSC United Healthcare Medicare Solutions' then '32'
when l."Progdescr"='DHMNSC Blue Shield Commercial' then '28'
when l."Progdescr"  in ('DHMNSC Health Net SmartCare Commercial','DHMNSC Health Net Canopy UC Blue and Gold Commercial',
'DHMNSC Health Net Canopy Care Commercial') then '33'
when l."Progdescr"='DHMNSC Aetna Commercial' then '34'
when l."Progdescr"='DHMNSC Cigna Commercial' then '35'
when l."Progdescr"='DHMNSC Health Net Commercial' then '36'
when l."Progdescr"='DHMNSC Anthem Blue Cross Commercial' then '37'
when l."Progdescr"='DHMNSC Health Net Seniority Plus' then '38'
when l."Progdescr"='DHMNSC United Healthcare Canopy Medicare Advantage' then '50' end as inpid,
case when l."Progdescr"  in ('DHMNSC Health Net SmartCare Commercial','DHMNSC Health Net Canopy UC Blue and Gold Commercial',
'DHMNSC Health Net Canopy Care Commercial') then 'DHMNSC Health Net SmartCare Commercial'
else l."Progdescr"  end as inpn,
'3' as acoid,
'DHMN-SC' as acon,
case when l."LOB" ='M' then '6'
    when l."LOB" ='C' then '7' else '8' end as orgid,
case when l."LOB"='C' then 'Commercial'when l."LOB"='M' then 'Medicare' else "LOB" end as orgn,
case when  l."HPCode" not in ('PGM000295','PGM000294','PGM000333','PGM000332','PGM000326') then '7'
     when l."HPCode" in ('PGM000295','PGM000294','PGM000333','PGM000332','PGM000326') then '9' else '8' end as orgrid,
case when  l."HPCode" not in ('PGM000295','PGM000294','PGM000333','PGM000332','PGM000326') then 'Non Canopy'
     when l."HPCode" in ('PGM000295','PGM000294','PGM000333','PGM000332','PGM000326') then 'Canopy' else 'Other MedGroup' end as orgrn,
-- hardcode columns
'3a1bcd23-d88c-4c70-8ffa-267673232647' as pipid,
'Claims' as st,
l."HPName" as sstp,
'DataMart.bak' as sfn,
current_date as rcdt,
current_date as ingdt,
'claimline' as cltp,
'5' as sid,
'Patient ID' as idt,
 -- dm_claim
trim(c.claimno) as cid,
trim(c.seq) as clid,
'Professional' as cltc,
case when (trim(c.billtype) in ('','NULL','NA') or trim(c.billtype) is null)
    then '' else trim(c.billtype) end as bt,
case when (trim(c.claim_fromdate) in ('','NULL','NA'))then null
    else cast(c.claim_fromdate as date) end as efdt,
case when (trim(c.claim_todate) in ('','NULL','NA'))then null
    else cast(c.claim_todate as date) end as eldt,
case when (trim(c.claim_recddate) in ('','NULL','NA'))then null
    else cast(c.claim_recddate as date) end as cpdt,
case when (trim(c.claim_paiddate) in ('','NULL','NA'))then null
    else cast(c.claim_paiddate as date) end as capdt,
case when (c.claim_netamt::decimal(18,2)='0' and c.iscap='1') then cast(c.claim_contramt as decimal(18,2))
else cast(c.claim_netamt as decimal(18,2))  end as pih,
case when trim(c.claimno)  like '%A1' then 'A'
     when trim(c.claimno)  like '%A2' then 'A'
     when trim(c.claimno)  like '%A3' then 'A'
    when trim(c.claimno)  like '%A4' then 'A'
     when trim(c.claimno)  like '%R1' then 'C'
     when trim(c.claimno)  like '%R2' then 'C'
     when trim(c.claimno)  like '%R3' then 'C'
     when trim(c.claimno)  like '%R4' then 'C'
     when trim(c.claimno)  like '%R5' then 'C' else 'O' end as adjs,
case when trim(c.claimno)  like '%A1' then 'Adjusted'
     when trim(c.claimno)  like '%A2' then 'Adjusted'
     when trim(c.claimno)  like '%A3' then 'Adjusted'
    when trim(c.claimno)  like '%A4' then 'Adjusted'
     when trim(c.claimno)  like '%R1' then 'Cancelled'
     when trim(c.claimno)  like '%R2' then 'Cancelled'
     when trim(c.claimno)  like '%R3' then 'Cancelled'
     when trim(c.claimno)  like '%R4' then 'Cancelled'
     when trim(c.claimno)  like '%R5' then 'Cancelled' else 'Original' end as adjsn,
case when (trim(c.taxid) in ('','NULL','NA') or trim(c.taxid) is null)
    then '' else trim(c.taxid) end as orgtin,
case when (trim(c.npi ) in ('','NULL','NA') or trim(c.npi) is null)
    then '' else trim(c.npi) end as spnpi,
case when (c.prov_name in ('','NULL','NA') or c.prov_name is null) then p1.name else c.prov_name end as spn,
p1.ptxcd as spsc,
p1.psn as sps,
case when (trim(c.drgcode ) in ('','NULL','NA') or trim(c.drgcode) is null)
    then '' else trim(c.drgcode) end as drg,
c.drg_descr as drgn,
case when (trim(c.claimsvc_fromdate) in ('','NULL','NA'))then null
    else cast(c.claimsvc_fromdate as date) end as clsfdt,
case when (trim(c.claimsvc_todate) in ('','NULL','NA'))then null
    else cast(c.claimsvc_todate as date) end  as clsldt,
case when (trim(c.claimsvc_qty ) in ('','NULL','NA') or trim(c.claimsvc_qty) is null)
    then '' else trim(c.claimsvc_qty) end as uqt,
--cast(c.claimsvc_netamt as decimal(18,2)) as catp,
case when c.iscap='1' then cast(c.claimsvc_contramt as decimal(18,2)) else cast(c.claimsvc_netamt as decimal(18,2)) end as catp,
cast(c.claimsvc_allowedamt as decimal(18,2)) as alat,
cast(c.claimsvc_copayamt as decimal(18,2)) as cpat,
cast(c.claimsvc_deductamt as decimal(18,2)) as dat,
case when (trim(c.svccode ) in ('','NULL','NA') or trim(c.svccode) is null)
    then '' else trim(c.svccode) end as pc,
case when (trim(c.svc_longdescr ) in ('','NULL','NA') or trim(c.svc_longdescr) is null)
    then '' else trim(c.svc_longdescr) end as pn,
    ont.csys as pcs,
case when (trim(c.claimsvc_fromdate) in ('','NULL','NA'))then null
    else cast(c.claimsvc_fromdate as date) end as pfdt,
case when (trim(c.claimsvc_todate) in ('','NULL','NA'))then null
    else cast(c.claimsvc_todate as date) end  as pldt,
mf.pm1 ,
mf.pm2 ,
mf.pm3,
mf.pm4,
mf.pm5 ,
mf.pmn1,
mf.pmn2 ,
mf.pmn3,
mf.pmn4,
mf.pmn5,
case when c.poscode in('01','1') then 'Pharmacy'
when c.poscode in ('02','2') then 'Telehealth'
when c.poscode in('03','3') then 'School'
when c.poscode in ('04','4') then 'Homeless Shelter'
when c.poscode in ('05','5') then 'Indian Health Service Free-standing Facility'
when c.poscode='06' then 'Indian Health Service Provider-based Facility'
when c.poscode in ('07','7') then 'Tribal 638 Free-standing Facility'
when c.poscode in ('08','8') then 'Tribal 638 Provider-based Facility'
when c.poscode in('09','9') then 'Prison/Correctional Facility'
when c.poscode in ('10','77') then 'Unassigned'
when c.poscode='11' then 'Office'
when c.poscode='12' then 'Home'
when c.poscode='13' then 'Assisted Living Facility'
when c.poscode='14' then 'Group Home'
when c.poscode='15' then 'Mobile Unit'
when c.poscode='16' then 'Temporary Lodging'
when c.poscode='17' then 'Walk-in Retail Health Clinic'
when c.poscode='18' then 'Place of Employment-Worksite'
when c.poscode='19' then 'Off Campus-Outpatient Hospital'
when c.poscode='20' then 'Urgent Care facility'
when c.poscode='21' then 'Inpatient Hospital'
when c.poscode='22' then 'On Campus-Outpatient Hospital'
when c.poscode='23' then 'Emergency Room – Hospital'
when c.poscode in ('24','B') then 'Ambulatory Surgical Center'
when c.poscode='25' then 'Birthing Center'
when c.poscode='26' then 'Military Treatment Facility'
when c.poscode='31' then 'Skilled Nursing Facility'
when c.poscode='32' then 'Nursing Facility'
when c.poscode='33' then 'Custodial Care Facility'
when c.poscode='34' then 'Hospice'
when c.poscode='41' then 'Ambulance - Land'
when c.poscode='42' then 'Ambulance – Air or Water'
when c.poscode='49' then 'Independent Clinic'
when c.poscode='50' then 'Federally Qualified Health Center'
when c.poscode='51' then 'Inpatient Psychiatric Facility'
when c.poscode='52' then 'Psychiatric Facility-Partial Hospitalization'
when c.poscode='53' then 'Community Mental Health Center'
when c.poscode='54' then 'Intermediate Care Facility/ Individuals with Intellectual Disabilities'
when c.poscode='55' then 'Residential Substance Abuse Treatment Facility'
when c.poscode='56' then 'Psychiatric Residential Treatment Center'
when c.poscode='57' then 'Non-residential Substance Abuse Treatment Facility'
when c.poscode='60' then 'Mass Immunization Center'
when c.poscode='61' then 'Comprehensive Inpatient Rehabilitation Facility'
when c.poscode='62' then 'Comprehensive Outpatient Rehabilitation Facility'
when c.poscode='65' then 'End-Stage Renal Disease Treatment Facility'
when c.poscode='71' then 'Public Health Clinic'
when c.poscode='72' then 'Rural Health Clinic'
when c.poscode in ('81','A') then 'Independent Laboratory'
when c.poscode in ('99','?','O') then 'Other Place of Service' end as sln,
case when c.poscode in ('O','?') then '99'
when c.poscode='A' then '81'
when c.poscode='B' then '24'
when c.poscode in('1','2','3','4','5','6','7','8','9') then '0'||c.poscode else c.poscode end slc,
case when (trim(c.pd ) in ('','NULL','NA') or trim(c.pd ) is null)
    then '' else trim(c.pd) end as pd,
case when (trim(c.pdn ) in ('','NULL','NA') or trim(c.pdn) is null)
    then '' else trim(c.pdn) end as pdn,
pdcs as pdcs,
case when (trim(c.pd ) in ('','NULL','NA') or trim(c.pd ) is null)
    then Null else (
    case when (trim(c.claimsvc_fromdate) in ('','NULL','NA'))then null
    else cast(c.claimsvc_fromdate as date) end )end as ddt,
case when (trim(c.ref_npi ) in ('','NULL','NA') or trim(c.ref_npi) is null)
    then '' else trim(c.ref_npi) end as rpnpi,
    p2."name" as rpn,
p2.ptxcd as rpsc,
p2.psn as rps,
ad1,ad2,ad3,ad4,ad5,
ad6,ad7,ad8,ad9,ad10,ad11,ad12,ad13,ad14,ad15,ad16,ad17,ad18,ad19,ad20,ad21,ad22,ad23,ad24,ad25,ad26,ad27,ad28,ad29,
adn1,adn2,adn3,adn4,adn5,adn6,adn7,adn8,adn9,adn10,adn11,adn12,adn13,adn14,
adn15,adn16,adn17,adn18,adn19,adn20,adn21,adn22,adn23,adn24,adn25,adn26,adn27,adn28,adn29
from (select * from l1.dm_proc_memb
where hpcode in ('PGM000333','PGM000332','PGM000326','PGM000268', 'PGM000269', 'PGM000270', 'PGM000272', 'PGM000273', 'PGM000274', 'PGM000275', 'PGM000276', 'PGM000294', 'PGM000295')) m
inner join l1.dm_proc_claim_p c
on m.memb_id=c.claim_memb
left join l1.dm_proc_modif mf
on mf.claimsvc_id=c.claimsvc_id
left join l1."dm_prov" p on p.prov_id =m.prov_id
left join l1."dm_vend" v on v.vend_id =m.vend_id
left join (select * from l1."level" where "HPCode" in ('PGM000333','PGM000332','PGM000326','PGM000268', 'PGM000269', 'PGM000270', 'PGM000272', 'PGM000273', 'PGM000274', 'PGM000275', 'PGM000276', 'PGM000294', 'PGM000295')) l
on trim(l."HPCode" )=trim(m.hpcode)
left join l2.pd_npi p1 on trim(c.npi)=trim(p1.npi)
left join (select * from l2.pd_ontology where dtp ='procedure' )ont
on trim(ont.cval) =trim(c.svccode )
--left join l2.pd_ontology ontd
--on trim(ontd.cval) =trim(c.pd) and ontd.dtp ='diagnosis'
left join l2.pd_npi p2 on trim(c.ref_npi )=trim(p2.npi)
)f

I ran explain command onto this query and I observed the following op:

  Merge Cond: ((btrim((p2.npi)::text)) = (btrim((c.ref_npi)::text)))
  ->  Sort  (cost=1761851.74..1785989.13 rows=9654958 width=108)
        Sort Key: (btrim((p2.npi)::text))
        ->  Seq Scan on pd_npi p2  (cost=0.00..641739.58 rows=9654958 width=108)
  ->  Materialize  (cost=159139479153552696279040.00..159226719441637676679168.00 rows=17448057616994486190080 width=3383)
        ->  Sort  (cost=159139479153552696279040.00..159183099297595186479104.00 rows=17448057616994486190080 width=3383)
              Sort Key: (btrim((c.ref_npi)::text))
              ->  Merge Join  (cost=456947875487.57..261731712177051860992.00 rows=17448057616994486190080 width=3383)
                    Merge Cond: ((c.claim_memb)::text = (dm_proc_memb.memb_id)::text)
                    ->  Nested Loop Left Join  (cost=157761.50..10839427546273626.00 rows=2707460197662070 width=2450)
                          Join Filter: (btrim((c.npi)::text) = btrim((p1.npi)::text))
                          ->  Nested Loop Left Join  (cost=157761.50..9586754880584.63 rows=56084349568 width=2353)
                                Join Filter: (btrim((pd_ontology.cval)::text) = btrim((c.svccode)::text))
                                ->  Nested Loop Left Join  (cost=0.56..9362416722695.26 rows=43719408 width=2348)
                                      Join Filter: ((mf.claimsvc_id)::text = (c.claimsvc_id)::text)
                                      ->  Index Scan Backward using l1_dm_proc_claims_p_id_idx on dm_proc_claim_p c  (cost=0.56..17080655.54 rows=43719408 width=2036)
                                      ->  Materialize  (cost=0.00..376215.44 rows=14276496 width=352)
                                            ->  Seq Scan on dm_proc_modif mf  (cost=0.00..304832.96 rows=14276496 width=352)
                                ->  Materialize  (cost=157760.93..760260.39 rows=256565 width=14)
                                      ->  Bitmap Heap Scan on pd_ontology  (cost=157760.93..758977.56 rows=256565 width=14)
                                            Recheck Cond: ((dtp)::text = 'procedure'::text)
                                            ->  Bitmap Index Scan on pd_ont_idx_dtp  (cost=0.00..157696.79 rows=256565 width=0)
                                                  Index Cond: ((dtp)::text = 'procedure'::text)
                          ->  Materialize  (cost=0.00..690014.37 rows=9654958 width=108)
                                ->  Seq Scan on pd_npi p1  (cost=0.00..641739.58 rows=9654958 width=108)
                    ->  Materialize  (cost=456947717726.07..459097227591.84 rows=429901973154 width=972)
                          ->  Sort  (cost=456947717726.07..458022472658.96 rows=429901973154 width=972)
                                Sort Key: dm_proc_memb.memb_id NULLS FIRST
                                ->  Merge Right Join  (cost=82668031.11..6531565545.79 rows=429901973154 width=972)
                                      Merge Cond: ((v.vend_id)::text = (dm_proc_memb.vend_id)::text)
                                      ->  Sort  (cost=88160.95..89633.33 rows=588951 width=96)
                                            Sort Key: v.vend_id
                                            ->  Seq Scan on dm_vend v  (cost=0.00..31716.51 rows=588951 width=96)
                                      ->  Materialize  (cost=82579870.16..83309815.39 rows=145989046 width=940)
                                            ->  Sort  (cost=82579870.16..82944842.77 rows=145989046 width=940)
                                                  Sort Key: dm_proc_memb.vend_id
                                                  ->  Merge Right Join  (cost=165139.84..2405511.13 rows=145989046 width=940)
                                                        Merge Cond: ((p.prov_id)::text = (dm_proc_memb.prov_id)::text)
                                                        ->  Index Scan using dm_prov_prov_id on dm_prov p  (cost=0.42..49937.79 rows=239291 width=160)
                                                        ->  Sort  (cost=165139.42..165444.47 rows=122018 width=844)
                                                              Sort Key: dm_proc_memb.prov_id
                                                              ->  Hash Left Join  (cost=485.00..154830.89 rows=122018 width=844)
                                                                    Hash Cond: (btrim((dm_proc_memb.hpcode)::text) = btrim((level."HPCode")::text))
                                                                    ->  Bitmap Heap Scan on dm_proc_memb  (cost=481.71..153985.68 rows=122018 width=812)
                                                                          Recheck Cond: ((hpcode)::text = ANY ('{PGM000333,PGM000332,PGM000326,PGM000268,PGM000269,PGM000270,PGM000272,PGM000273,PGM000274,PGM000275,PGM000276,PGM000294,PGM000295}'::text[]))
                                                                          ->  Bitmap Index Scan on l1_proc_memb_id_idx  (cost=0.00..451.20 rows=122018 width=0)
                                                                    ->  Hash  (cost=3.13..3.13 rows=13 width=64)
                                                                          ->  Seq Scan on level  (cost=0.00..3.13 rows=13 width=64)
                                                                                Filter: (("HPCode")::text = ANY ('{PGM000333,PGM000332,PGM000326,PGM000268,PGM000269,PGM000270,PGM000272,PGM000273,PGM000274,PGM000275,PGM000276,PGM000294,PGM000295}'::text[]))

The cost taken by the query is too much. How can I reduce the cost and save time.
P.S I analyzed and found that left joins are increasing the cost. Please tell me how to manage this.

The max size of the tables is 32 GB.

Thanks!!


来源: stackexchange

问:
Add consecutive count to this ef core query
I have the below query in Entity Framework Core that reports on amounts of sales, grouped by customer, between given dates.

```<code>IEnumerable<SalesDataModel> currentSales =
(from s in sales
where s.Date >= [StartDate] && u.Date <= [EndDate]
join c in customers on s.Acct equals c.Account
group s by new { s.Name, c.City } into g
select new SalesDataModel {
    CustName = g.Key.Name,
    City = g.Key.City,
    MaxBorrowed = g.Max(x => x.Price),
    Average = g.Average(x => x.Price),
    NumDays =
        g.Sum(x => x.Price > 0 ? 1 : 0),
    ConsecutiveDays = //???
}).ToList();
</code>```

Basically I want to count the number of times within the date span that a given customer made a purchase two days or more in a row. So, start with Day 1, and compare it to Day 2; if Price > 0 for both days, iterate a counter by one. Then check Day 2 against Day 3 with the same criteria, and repeat for as many records as I have for that customer. The counter should not reset to zero if a zero or null Price value is encountered, but it should reset for the next customer.

I found this SO Post asking something similar, but there's got to be an easier way. I'm  using EF Core 5.

Also, full disclosure, this post is a continuation from a previous post. Since the answer to this question might not be as simple as I hope, a second post seemed the better way.

答: This query is going to require a FromSqlRaw execution of an SP to make this work.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have the below query in Entity Framework Core that reports on amounts of sales, grouped by customer, between given dates.

IEnumerable<SalesDataModel> currentSales =
(from s in sales
where s.Date >= [StartDate] && u.Date <= [EndDate]
join c in customers on s.Acct equals c.Account
group s by new { s.Name, c.City } into g
select new SalesDataModel {
    CustName = g.Key.Name,
    City = g.Key.City,
    MaxBorrowed = g.Max(x => x.Price),
    Average = g.Average(x => x.Price),
    NumDays =
        g.Sum(x => x.Price > 0 ? 1 : 0),
    ConsecutiveDays = //???
}).ToList();

Basically I want to count the number of times within the date span that a given customer made a purchase two days or more in a row. So, start with Day 1, and compare it to Day 2; if Price > 0 for both days, iterate a counter by one. Then check Day 2 against Day 3 with the same criteria, and repeat for as many records as I have for that customer. The counter should not reset to zero if a zero or null Price value is encountered, but it should reset for the next customer.

I found this SO Post asking something similar, but there's got to be an easier way. I'm  using EF Core 5.

Also, full disclosure, this post is a continuation from a previous post. Since the answer to this question might not be as simple as I hope, a second post seemed the better way.


问:
Ansible double loop using subelements
I'm writing an Ansible playbook and I have the following variable:

```<code>contracts:
  - name: 'https'
    subjects:
      - name: 'permit'
        filters:
          - filter: tcp_443
</code>```

A contract has multiple subjects and a subject can have multiple filters. The playbook needs to loop over this variable.

I'm currently doing the following:

```<code>- name: Task - Contract Subjects Have Filters
  contract_subject_to_filter:
    state: "present"
    tenant: "{{ tenant }}"
    contract: "{{ item..0.name }}"
    subject: "{{ item.1.name }}"
    filter: "{{ item.2.filter }}"
  loop: "{{ contracts | subelements('subjects') | subelements('filters') }}"
  tags: contract
</code>```

{"msg": "Unexpected templating type error occurred on ({{ contracts |
subelements('subjects') | subelements('filters') }}): the key filters
should point to a dictionary, got '({'name': 'https', 'subjects':
[{'name': 'permit', 'filters': [{'filter': 'tcp_443'}]}]}, {'name':
'permit', 'filters': [{'filter': 'tcp_443'}]})'"}

How can I do a double loop (contracts has subjects and subjects have filters) in an Ansible playbook? I cannot change the variable structure or use a different Ansible module.

答:
Flatten the list, e.g.

    - set_fact:
        my_list: "{{ _my_list|from_yaml }}"
      vars:
        _my_list: |-
          {% for i in contracts %}
          {% for j in i.subjects %}
          {% for k in j.filters %}
          - {name: {{ i.name }}, subject: {{ j.name }}, filter: {{ k.filter }}}
          {% endfor %}
          {% endfor %}
          {% endfor %}
```
<p>gives</p>
<pre class="lang-yaml prettyprint-override"><code>  my_list:
  - filter: tcp_443
    name: https
    subject: permit
</code>```

Then, the iteration is trivial

    - name: Task - Contract Subjects Have Filters
      debug:
        msg: |-
          state: "present"
          tenant: "tenant"
          contract: "{{ item.name }}"
          subject: "{{ item.subject }}"
          filter: "{{ item.filter }}"
      loop: "{{ my_list }}"
```
<p>gives</p>
<pre class="lang-yaml prettyprint-override"><code>  msg: |-
    state: "present"
    tenant: "tenant"
    contract: "https"
    subject: "permit"
    filter: "tcp_443"
</code>```

Title: Ansible double loop using subelements

Body:
I'm writing an Ansible playbook and I have the following variable:

contracts:
  - name: 'https'
    subjects:
      - name: 'permit'
        filters:
          - filter: tcp_443

A contract has multiple subjects and a subject can have multiple filters. The playbook needs to loop over this variable.

I'm currently doing the following:

- name: Task - Contract Subjects Have Filters
  contract_subject_to_filter:
    state: "present"
    tenant: "{{ tenant }}"
    contract: "{{ item..0.name }}"
    subject: "{{ item.1.name }}"
    filter: "{{ item.2.filter }}"
  loop: "{{ contracts | subelements('subjects') | subelements('filters') }}"
  tags: contract

{"msg": "Unexpected templating type error occurred on ({{ contracts |
subelements('subjects') | subelements('filters') }}): the key filters
should point to a dictionary, got '({'name': 'https', 'subjects':
[{'name': 'permit', 'filters': [{'filter': 'tcp_443'}]}]}, {'name':
'permit', 'filters': [{'filter': 'tcp_443'}]})'"}

How can I do a double loop (contracts has subjects and subjects have filters) in an Ansible playbook? I cannot change the variable structure or use a different Ansible module.

Body:
Flatten the list, e.g.

    - set_fact:
        my_list: "{{ _my_list|from_yaml }}"
      vars:
        _my_list: |-
          {% for i in contracts %}
          {% for j in i.subjects %}
          {% for k in j.filters %}
          - {name: {{ i.name }}, subject: {{ j.name }}, filter: {{ k.filter }}}
          {% endfor %}
          {% endfor %}
          {% endfor %}

gives

  my_list:
  - filter: tcp_443
    name: https
    subject: permit

Then, the iteration is trivial

    - name: Task - Contract Subjects Have Filters
      debug:
        msg: |-
          state: "present"
          tenant: "tenant"
          contract: "{{ item.name }}"
          subject: "{{ item.subject }}"
          filter: "{{ item.filter }}"
      loop: "{{ my_list }}"

gives

  msg: |-
    state: "present"
    tenant: "tenant"
    contract: "https"
    subject: "permit"
    filter: "tcp_443"


问:
Check if one date is between two dates or not
I have the following three dates

```<code>Date1 = 2022-02-07 20:06:14.379392
Date2 = 2021-02-07 20:06:14.379393
Date3 = 2022-02-06 00:00:00.000
</code>```

and I want to check, if Date3 is between Date1 and Date2.

As of right now the Date3 is between Date1 and Date2, but how can I check this?

Currently I am trying something like this

```<code>if (Date1.isBefore(Date3) &&
    Date2.isAfter(Date3)) {
  print("date3 is between date1 and date2");
} else {
  print("date3 isn't between date1 and date2");
}
</code>```

But it's always showing, that the Date3 is not between Date1 and Date2.

答:
You have interchanged the dates in the if-condition.

Instead of checking, if 2022-02-06 is before 2022-02-07, you are currently checking 2022-02-07 is before 2022-02-06. Which is obviously wrong.

So you have to adjust your check.

For Example:

```<code>void main() {
  var now = DateTime.now();
  var lastYear = DateTime.now().add(Duration(days: -365));

  var dateToCheck = DateTime.now().add(Duration(days: -1));

  if( dateToCheck.isAfter(lastYear) && dateToCheck.isBefore(now))
  {
    print("dateToCheck is between now and lastYear");
  }
  else
  {
    print("dateToCheck is not between now and lastYear");
  }
}
</code>```

or if you want to write dateToCheck within the function call, you could write it like this:

```<code>void main() {
  var now = DateTime.now();
  var lastYear = DateTime.now().add(Duration(days: -365));

  var dateToCheck = DateTime.now().add(Duration(days: -1));

  if( lastYear.isBefore(dateToCheck) && now.isAfter(dateToCheck) )
  {
    print("dateToCheck is between now and lastYear");
  }
  else
  {
    print("dateToCheck is not between now and lastYear");
  }
}
</code>```

Body:
I have the following three dates

Date1 = 2022-02-07 20:06:14.379392
Date2 = 2021-02-07 20:06:14.379393
Date3 = 2022-02-06 00:00:00.000

and I want to check, if Date3 is between Date1 and Date2.

As of right now the Date3 is between Date1 and Date2, but how can I check this?

Currently I am trying something like this

if (Date1.isBefore(Date3) &&
    Date2.isAfter(Date3)) {
  print("date3 is between date1 and date2");
} else {
  print("date3 isn't between date1 and date2");
}

But it's always showing, that the Date3 is not between Date1 and Date2.

Body:
You have interchanged the dates in the if-condition.

Instead of checking, if 2022-02-06 is before 2022-02-07, you are currently checking 2022-02-07 is before 2022-02-06. Which is obviously wrong.

So you have to adjust your check.

For Example:

void main() {
  var now = DateTime.now();
  var lastYear = DateTime.now().add(Duration(days: -365));

  var dateToCheck = DateTime.now().add(Duration(days: -1));

  if( dateToCheck.isAfter(lastYear) && dateToCheck.isBefore(now))
  {
    print("dateToCheck is between now and lastYear");
  }
  else
  {
    print("dateToCheck is not between now and lastYear");
  }
}

or if you want to write dateToCheck within the function call, you could write it like this:

void main() {
  var now = DateTime.now();
  var lastYear = DateTime.now().add(Duration(days: -365));

  var dateToCheck = DateTime.now().add(Duration(days: -1));

  if( lastYear.isBefore(dateToCheck) && now.isAfter(dateToCheck) )
  {
    print("dateToCheck is between now and lastYear");
  }
  else
  {
    print("dateToCheck is not between now and lastYear");
  }
}


答:
If you parse the dates as DateTime then fix the condition, it should work.
Side note: you should rename your variables to something more explicit, ex. dateMin/dateMax, dateLowerBound/dateUpperBound, etc.</p>
```<code>void main() {
    final date1 = DateTime.parse('2022-02-07 20:06:14.379392');
    final date2 = DateTime.parse('2021-02-07 20:06:14.379393');
    final date3 = DateTime.parse('2022-02-06 00:00:00.000');

    if (date3.isBefore(date1) && date3.isAfter(date2)) {
        print("date3 is between date1 and date2"); // <- this is printed.
    }
    else {
        print("date3 isn't between date1 and date2");
    }
}
</code>```

Title: Check if one date is between two dates or not

Body:
If you parse the dates as DateTime then fix the condition, it should work.
Side note: you should rename your variables to something more explicit, ex. dateMin/dateMax, dateLowerBound/dateUpperBound, etc.

void main() {
    final date1 = DateTime.parse('2022-02-07 20:06:14.379392');
    final date2 = DateTime.parse('2021-02-07 20:06:14.379393');
    final date3 = DateTime.parse('2022-02-06 00:00:00.000');

    if (date3.isBefore(date1) && date3.isAfter(date2)) {
        print("date3 is between date1 and date2"); // <- this is printed.
    }
    else {
        print("date3 isn't between date1 and date2");
    }
}


问:
Flask Run - ImportError was raised
Starting my Flask app using:

```<code>flask run
</code>```

Doesn't appear to work... and I get the error message:

```<code>Error: While importing 'entry', an ImportError was raised.
</code>```

however if I run:

```<code>python entry.py
</code>```

The app will build successfully? Why is this? Both FLASK_APP and FLASK_ENV are set correctly, here is my folder structure:

entry.py:

```<code>from application import create_app

app = create_app()
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)
</code>```

application/init.py:

```<code>import os
from flask import Flask
from config import DevConfig, TestConfig, ProdConfig
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

from application.models import Report

def create_app(testing=False):
    app = Flask(__name__)

    flask_env = os.getenv("FLASK_ENV", None)

    # Configure the application, depending on the environment
    if testing:
        app.config.from_object(TestConfig)
    elif flask_env == "development":
        app.config.from_object(DevConfig)
    elif flask_env == "production":
        app.config.from_object(ProdConfig)
    else:
        raise ValueError("FLASK_ENV is not set or there is an unknown environment type!")

    # init plugins, if any
    db.init_app(app)

    if flask_env == "development":
        with app.app_context():
            db.create_all()
            db.session.commit()

    # register blueprints
    register_blueprints(app)

    return app

def register_blueprints(app):
    from application.main import main_blueprint

    app.register_blueprint(main_blueprint)
</code>```

答:
If you want to start the application through the flask executable, then you have to consider that flask will look for the app.py file containing the app application, if not (as in your case), then you will have to correctly set the value of the environment variable FLASK_APP, which will be equal to FLASK_APP=entry.py:app

On Linux, macOS:

```<code>$ export FLASK_APP=entry.py:app
$ flask run
</code>```

On Windows:

```<code>$ set FLASK_APP=entry.py:app
$ flask run
</code>```

Take a look here: Run The Application.

Here, however, it is explained how flask looks for the application to run

In this case (python entry.py) everything works correctly, because flask is invoked via python inside the main section, which instead is not called if entry.py is executed directly from flask, in fact flask will not enter the main section, but will look for the app.py file and the app variable inside it. (Obviously it will look for entry.py and app if you have configured the environment variable correctly)

Title: Flask Run - ImportError was raised

Body:
Starting my Flask app using:

flask run

Doesn't appear to work... and I get the error message:

Error: While importing 'entry', an ImportError was raised.

however if I run:

python entry.py

The app will build successfully? Why is this? Both FLASK_APP and FLASK_ENV are set correctly, here is my folder structure:

entry.py:

from application import create_app

app = create_app()
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)

application/init.py:

import os
from flask import Flask
from config import DevConfig, TestConfig, ProdConfig
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

from application.models import Report

def create_app(testing=False):
    app = Flask(__name__)

    flask_env = os.getenv("FLASK_ENV", None)

    # Configure the application, depending on the environment
    if testing:
        app.config.from_object(TestConfig)
    elif flask_env == "development":
        app.config.from_object(DevConfig)
    elif flask_env == "production":
        app.config.from_object(ProdConfig)
    else:
        raise ValueError("FLASK_ENV is not set or there is an unknown environment type!")

    # init plugins, if any
    db.init_app(app)

    if flask_env == "development":
        with app.app_context():
            db.create_all()
            db.session.commit()

    # register blueprints
    register_blueprints(app)

    return app

def register_blueprints(app):
    from application.main import main_blueprint

    app.register_blueprint(main_blueprint)

Body:
If you want to start the application through the flask executable, then you have to consider that flask will look for the app.py file containing the app application, if not (as in your case), then you will have to correctly set the value of the environment variable FLASK_APP, which will be equal to FLASK_APP=entry.py:app

On Linux, macOS:

$ export FLASK_APP=entry.py:app
$ flask run

On Windows:

$ set FLASK_APP=entry.py:app
$ flask run

Take a look here: Run The Application.

Here, however, it is explained how flask looks for the application to run

In this case (python entry.py) everything works correctly, because flask is invoked via python inside the main section, which instead is not called if entry.py is executed directly from flask, in fact flask will not enter the main section, but will look for the app.py file and the app variable inside it. (Obviously it will look for entry.py and app if you have configured the environment variable correctly)


问:
why is my int() conversion looking so weird?
I'm trying to take a number and divide it by 100 to get 1%, but when i tried to convert it to integer using the int(), it's giving me some weird output. i have no clue what i'm doing wrong here.

```<code>totalsupply = 1000000000000000000000000000000
onepercent = int((totalsupply/100))

print(totalsupply)
print(onepercent)
</code>```

the output is coming out as such:

```<code>1000000000000000000000000000000
9999999999999999583119736832
[Finished in 68ms]
</code>```

I was expecting the onepercent to be this: 10000000000000000000000000000.

答:
Python has a built-in integer type that has infinite precision. That's what you are creating with your first line

```<code> totalsupply = 1000000000000000000000000000000
</code>```

However, python has two division operators. The standard division "slash" operator ("/") is floating-point operation, whereas the double-slash gives integers.

Hence totalsupply/100 is a floating point number, which has finite precision, and so the closest it can do is 9999999999999999583119736832.

However, if instead you do

```<code>onepercent = totalsupply//100
print(onepercent)
</code>```

you get the expected 100000000000000000000000000000.

Body:
I'm trying to take a number and divide it by 100 to get 1%, but when i tried to convert it to integer using the int(), it's giving me some weird output. i have no clue what i'm doing wrong here.

totalsupply = 1000000000000000000000000000000
onepercent = int((totalsupply/100))

print(totalsupply)
print(onepercent)

the output is coming out as such:

1000000000000000000000000000000
9999999999999999583119736832
[Finished in 68ms]

I was expecting the onepercent to be this: 10000000000000000000000000000.

Body:
Python has a built-in integer type that has infinite precision. That's what you are creating with your first line

 totalsupply = 1000000000000000000000000000000

However, python has two division operators. The standard division "slash" operator ("/") is floating-point operation, whereas the double-slash gives integers.

Hence totalsupply/100 is a floating point number, which has finite precision, and so the closest it can do is 9999999999999999583119736832.

However, if instead you do

onepercent = totalsupply//100
print(onepercent)

you get the expected 100000000000000000000000000000.


问:
Clipping a tensor if below certain treshold
I have a tensor with dim n x 3, containing n 3d vectors. I want to compute a new tensor with dim n x 3. If the norm of a vector drops below a certain treshold I want to set it to the zero vector and get a new tensor which contains the index positions of the changed vectors.

Example: tensor([1, 2, 3], [0, 1, 1], [4, 5, 6], ...) would lead to tensor([1, 2, 3], [0, 0, 0], [4, 5, 6], ...) with tensor([1]) if the treshold was set to 1.5.

How can I achieve that without using a loop? Thanks for your help.

Body:
Simply do a[vector_norm(a,dim=1) < thr] = 0, where thr is your threshold. Here's a demonstration.

import torch
from torch.linalg import vector_norm

n = 10
a = torch.rand(10,3)

print('a before:',a)
thr = 1
ind = vector_norm(a,dim=1) < thr
a[ind] = 0
print('a after:',a)
print('list of indices',ind.nonzero())

Result of an example run:

a before: tensor([[0.0708, 0.7559, 0.3974],
        [0.2969, 0.0974, 0.8652],
        [0.8074, 0.8180, 0.2432],
        [0.9006, 0.2447, 0.1602],
        [0.6289, 0.1976, 0.8543],
        [0.2109, 0.7539, 0.6334],
        [0.9100, 0.2514, 0.2314],
        [0.6657, 0.1940, 0.6565],
        [0.4577, 0.8439, 0.5681],
        [0.5566, 0.9979, 0.1468]])
a after: tensor([[0.0000, 0.0000, 0.0000],
        [0.0000, 0.0000, 0.0000],
        [0.8074, 0.8180, 0.2432],
        [0.0000, 0.0000, 0.0000],
        [0.6289, 0.1976, 0.8543],
        [0.2109, 0.7539, 0.6334],
        [0.0000, 0.0000, 0.0000],
        [0.0000, 0.0000, 0.0000],
        [0.4577, 0.8439, 0.5681],
        [0.5566, 0.9979, 0.1468]])
list of indices tensor([[0],
        [1],
        [3],
        [6],
        [7]])


问:
How to import xml file in wagtail OR migrate to wagtail from wordpress
I am trying to migrate wordpress to wagtail and method i am using is to export wordpress to xml and then import xml in wagtail. If i use this command ./manage.py wordpress_to_wagtail blog --xml=export.xml then command not found error is shown up. Please help me about this and django manangement commands.

答:
Try

```<code>python manage.py import_xml path/to/xml/file.xml parent_page_id
</code>```

Also, use the v2API which is more straightfoward as explained in their pypi package. I would recommend you check out their github

Body:
Try

python manage.py import_xml path/to/xml/file.xml parent_page_id

Also, use the v2API which is more straightfoward as explained in their pypi package. I would recommend you check out their github


问:
Bringing a DIV upwards so it sits behind another DIV
I'm confused here... Here's my site that I'm working on: http://s361608839.websitehome.co.uk/marbleenergy/

The div #main is sitting about 10px below #navigation and I've tried bringing it up 10px by adding:

```<code> #main {
 margin-top: -10px;
 }
</code>```

Had no luck there unfortunately. I'm learning CSS here, what is it I need to do?

Thanks

答:
Add the following to the #main div

```<code>#main {
position: relative;
top:-10px;
}
</code>```

position: relative; Will position the element relative to where it normally sits and aligning -10px from where it would sit will bring it into the gap you have made in your menu div. Haven't checked your site but can't see any reason why this won't work. I prefer not to set my elements to position: absolute; as the above member answered as any content under the div will be pulled up under the absolutely positioned div.

ContentLicense: CC BY-SA 3.0

Body:
I'm confused here... Here's my site that I'm working on: http://s361608839.websitehome.co.uk/marbleenergy/

The div #main is sitting about 10px below #navigation and I've tried bringing it up 10px by adding:

 #main {
 margin-top: -10px;
 }

Had no luck there unfortunately. I'm learning CSS here, what is it I need to do?

Thanks

Body:
Add the following to the #main div

#main {
position: relative;
top:-10px;
}

position: relative; Will position the element relative to where it normally sits and aligning -10px from where it would sit will bring it into the gap you have made in your menu div. Haven't checked your site but can't see any reason why this won't work. I prefer not to set my elements to position: absolute; as the above member answered as any content under the div will be pulled up under the absolutely positioned div.


问:
Mailgun email stuck in "Accepted" state
When I use Mailgun to send emails via API, everything goes well when the recipient is a Gmail address.

But when the recipient's address is my domain's address (contact@mydomain.fr), the mail is stuck in "Accepted" state and never goes to "Delivered" state nor "Failed" state. Here are 2 mails:

All DNS are well configured and I use a free Mailgun plan.

答:
There are 2 possible common cases where this can happen:

If the customer you are sending to does not have MX records set up. When a message is "Accepted" into the system, it will attempt to look up the MX record for the recipient domain to know where to send the "Accepted" message. If the MX record does not exist, it can cause the message to get stuck in an "Accepted" state.

Another instance is if you are sending to your own domain registered with Mailgun (inbound message), with the Mailgun MX records set up. Keep in mind that Mailgun does not have inboxes. In order to ensure the mail goes somewhere, "Routes" must be in place to forward and "deliver" the mail to a destination. If you do not have "Routes" setup, the message will be stuck in an accepted state, as it does not know where to be sent to.

Title: Mailgun email stuck in "Accepted" state


问:
How can I overwrite a text after it's printed a few lines before?
I want to make a task/time manager. I want the list of tasks to be at the top and a question to add a new task if the user wants, but the problem is that I can't keep my to-do list in the top and I can't make it updated. What should I do?

This is my code, this is the form I want and the code I've written:

```<code>TASKS:(I want this to be updated)
1)--------
2)----------
3)----------
|
v
do you want to add a task(YES/NO):
when do you want to start the task (HOUR:MINUTE):
</code>```
```<code>task_num = 0
k = False
print("YOUR TASKS")
if k == True:
    print("\r", tasks)
print("tasks" + ":" + str(task_num), "\n\n")
active = True
while active:
    add_task = input("do you want to add a task(YES/NO):",)
    if add_task != 'YES':
        active = False
    else:
        k = True
        start_time = input("when do you want to start the task (HOUR:MINUTE):")
        end_time = input("when do you want to complete it:")
        task_name = input("what do you want to call it:")
        start_h, start_m = start_time.split(":")
        end_h, end_m = end_time.split(":")
        duration = str(abs(int(end_h) - int(start_h))) + ":" + str(abs(int(end_m) - int(start_m)))
        task = {"task name": task_name, "start time": start_time, "end time": end_time, "duration": duration}
        task_num += 1
        tasks[task_num] = task
        for key in tasks.keys():
            task_key = tasks[key]
            print(key,end=")")
            for key1 in task_key.keys():
                print(key1, ":", task_key[key1], end='|',)
            print('\n')
</code>```

答:
On POSIX systems clear -x command works like a charm. It preserves the current scroll buffer and produces almost zero flickering. Combine that with hiding the cursor, ah it is marvelous.

```<code>import sys
import subprocess

try:
    sys.stdout.write('\033[?25l')  # hide cursor
    subprocess.run(['clear', '-x'])
finally:
    sys.stdout.write('\033[?25h')  # show cursor
    sys.stdout.flush()

</code>```

On Windows, on the other hand, you'll probably need colorama package installed and initialized.
See https://github.com/tartley/colorama

On Windows cmd:

```<code>import sys
import shutil

height = shutil.get_terminal_size().lines
h = height * '\n'
# move cursor down and up.
sys.stdout.write(f'{h}\033[{height}A')
sys.stdout.flush()
</code>```

On Windows Terminal and other modern terminal emulators:

```<code>import sys
import shutil

height = shutil.get_terminal_size().lines
# clear the screen with the ANSI sequence.
sys.stdout.write((height - 1) * '\n' + '\033[2J')
sys.stdout.flush()
</code>```

Play with them and see what works for you.

Body:
I want to make a task/time manager. I want the list of tasks to be at the top and a question to add a new task if the user wants, but the problem is that I can't keep my to-do list in the top and I can't make it updated. What should I do?

This is my code, this is the form I want and the code I've written:

TASKS:(I want this to be updated)
1)--------
2)----------
3)----------
|
v
do you want to add a task(YES/NO):
when do you want to start the task (HOUR:MINUTE):

task_num = 0
k = False
print("YOUR TASKS")
if k == True:
    print("\r", tasks)
print("tasks" + ":" + str(task_num), "\n\n")
active = True
while active:
    add_task = input("do you want to add a task(YES/NO):",)
    if add_task != 'YES':
        active = False
    else:
        k = True
        start_time = input("when do you want to start the task (HOUR:MINUTE):")
        end_time = input("when do you want to complete it:")
        task_name = input("what do you want to call it:")
        start_h, start_m = start_time.split(":")
        end_h, end_m = end_time.split(":")
        duration = str(abs(int(end_h) - int(start_h))) + ":" + str(abs(int(end_m) - int(start_m)))
        task = {"task name": task_name, "start time": start_time, "end time": end_time, "duration": duration}
        task_num += 1
        tasks[task_num] = task
        for key in tasks.keys():
            task_key = tasks[key]
            print(key,end=")")
            for key1 in task_key.keys():
                print(key1, ":", task_key[key1], end='|',)
            print('\n')

Body:
On POSIX systems clear -x command works like a charm. It preserves the current scroll buffer and produces almost zero flickering. Combine that with hiding the cursor, ah it is marvelous.

import sys
import subprocess

try:
    sys.stdout.write('\033[?25l')  # hide cursor
    subprocess.run(['clear', '-x'])
finally:
    sys.stdout.write('\033[?25h')  # show cursor
    sys.stdout.flush()

On Windows, on the other hand, you'll probably need colorama package installed and initialized.
See https://github.com/tartley/colorama

On Windows cmd:

import sys
import shutil

height = shutil.get_terminal_size().lines
h = height * '\n'
# move cursor down and up.
sys.stdout.write(f'{h}\033[{height}A')
sys.stdout.flush()

On Windows Terminal and other modern terminal emulators:

import sys
import shutil

height = shutil.get_terminal_size().lines
# clear the screen with the ANSI sequence.
sys.stdout.write((height - 1) * '\n' + '\033[2J')
sys.stdout.flush()

Play with them and see what works for you.


问:
Add "No results found" message on div search
I'm making an audio player, and I have a list of divs acting as my playlist... I'm using JS to make the list, and I'm using this script to search through them:

```<code>/*Search Songs*/
function searchSongs(){
  let input = _('#songSearch').value.toLowerCase();
  let items = _all('.item');
  let dividers = _all(".divider");

  for (let i = 0; i < items.length; i++) {
    if (!items[i].innerHTML.toLowerCase().includes(input)) {
      items[i].style.display = "none";
    }
    else {
      items[i].style.display = "";
    }
  }

  // add noresults message at end if all list divs are hidden
  if (!items.innerHTML.toLowerCase().includes(input)) {
    _('.noResults').innerHTML = `<p>No results found for "${input}"`
  }
}
</code>```

I have a paragraph element at the end of my list (with nothing in it) and I want to show the message (
No results found for "${input}") is there some js I can use to accomplish this? The script above is working for the searching, but not working for the message.

答:
I've made a little modification in your function. I hope this will solve your issue.</p>
```<code>/*Search Songs*/
function searchSongs(){
  let input = _('#songSearch').value.toLowerCase();
  let items = _all('.item');
  let dividers = _all(".divider");
  let counter = 0;

  for (let i = 0; i < items.length; i++) {
    if (!items[i].innerHTML.toLowerCase().includes(input)) {
      items[i].style.display = "none";
    }
    else {
      items[i].style.display = "";
      counter++;
    }
  }

  // add noresults message at end if all list divs are hidden
  if (counter > 0) {
    _('.noResults').innerHTML = `<p>No results found for "${input}"`
  }
}
</code>```

Body:
I'm making an audio player, and I have a list of divs acting as my playlist... I'm using JS to make the list, and I'm using this script to search through them:

/*Search Songs*/
function searchSongs(){
  let input = _('#songSearch').value.toLowerCase();
  let items = _all('.item');
  let dividers = _all(".divider");

  for (let i = 0; i < items.length; i++) {
    if (!items[i].innerHTML.toLowerCase().includes(input)) {
      items[i].style.display = "none";
    }
    else {
      items[i].style.display = "";
    }
  }

  // add noresults message at end if all list divs are hidden
  if (!items.innerHTML.toLowerCase().includes(input)) {
    _('.noResults').innerHTML = `<p>No results found for "${input}"`
  }
}

I have a paragraph element at the end of my list (with nothing in it) and I want to show the message (
No results found for "${input}") is there some js I can use to accomplish this? The script above is working for the searching, but not working for the message.

Body:
I've made a little modification in your function. I hope this will solve your issue.

/*Search Songs*/
function searchSongs(){
  let input = _('#songSearch').value.toLowerCase();
  let items = _all('.item');
  let dividers = _all(".divider");
  let counter = 0;

  for (let i = 0; i < items.length; i++) {
    if (!items[i].innerHTML.toLowerCase().includes(input)) {
      items[i].style.display = "none";
    }
    else {
      items[i].style.display = "";
      counter++;
    }
  }

  // add noresults message at end if all list divs are hidden
  if (counter > 0) {
    _('.noResults').innerHTML = `<p>No results found for "${input}"`
  }
}


问:
C++ Why does one need to mark a constant-expression eligible function as constexpr?
Why do I need to mark functions that satisfy the criteria for constant-expression as constexpr to actually use them as constant expression?

Take this example (from here):

template<int N>
 class list
 { };

 constexpr int sqr1(int arg)
 { return arg * arg; }

 int sqr2(int arg)
 { return arg * arg; }

 int main()
 {
   const int X = 2;
   list<sqr1(X)> mylist1;  // OK: sqr1 is constexpr
   list<sqr2(X)> mylist2;  // wrong: sqr2 is not constexpr
 }

```

why do I have to mark sqr2 as constexpr? Isn't the compiler able to understand that that function satisfies the criteria for constant-expression? If it does the check for sqr1, why can't it do it for sqr2 and allow sqr2 to be used as a constant expression even without explicitly marking it?

答:
All template parameters must be known at compile time. Template is just recipe to create code. Code is generated when template is instantiated with all required template parameters.

So list<sqr2(X)> fails, since sqr2 can't be evaluated at compile time. Only constexpr (or consteval) functions can be evaluated at compile time.

Body:
Why do I need to mark functions that satisfy the criteria for constant-expression as constexpr to actually use them as constant expression?

Take this example (from here):

template<int N>
 class list
 { };

 constexpr int sqr1(int arg)
 { return arg * arg; }

 int sqr2(int arg)
 { return arg * arg; }

 int main()
 {
   const int X = 2;
   list<sqr1(X)> mylist1;  // OK: sqr1 is constexpr
   list<sqr2(X)> mylist2;  // wrong: sqr2 is not constexpr
 }

why do I have to mark sqr2 as constexpr? Isn't the compiler able to understand that that function satisfies the criteria for constant-expression? If it does the check for sqr1, why can't it do it for sqr2 and allow sqr2 to be used as a constant expression even without explicitly marking it?


问:
How to check url is image or video?
I fetch  API response and parse  pick  url in swift  . but i need to check is image url or video url :

If i get image url then show image and if get video url then play video :

```<code> if let url = postMedia?.url{

    //need to check here
  }
</code>```

For example

Here is my video url :

https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4

https://clips.vorwaerts-gmbh.de/big_buck_bunny.mov

here is image url :

https://clips.vorwaerts-gmbh.de/big_buck_bunny.png

https://clips.vorwaerts-gmbh.de/big_buck_bunny.jpg

note : i know how to show image and play video

答:
if you are sure that the file can only be a photo or a video you can use this simple code:</p>
```<code>if let data = try? Data(contentsOf: YOUR_LOCAL_URL) {
    if let _: UIImage = UIImage(data: (data)) {
        print("image!")
    } else {
        print("video!")
    }
}
</code>```

Title: How to check url is image or video?

Body:
I fetch  API response and parse  pick  url in swift  . but i need to check is image url or video url :

If i get image url then show image and if get video url then play video :

 if let url = postMedia?.url{

    //need to check here
  }

For example

Here is my video url :

https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4

https://clips.vorwaerts-gmbh.de/big_buck_bunny.mov

here is image url :

https://clips.vorwaerts-gmbh.de/big_buck_bunny.png

https://clips.vorwaerts-gmbh.de/big_buck_bunny.jpg

note : i know how to show image and play video

Body:
if you are sure that the file can only be a photo or a video you can use this simple code:

if let data = try? Data(contentsOf: YOUR_LOCAL_URL) {
    if let _: UIImage = UIImage(data: (data)) {
        print("image!")
    } else {
        print("video!")
    }
}


问:
occurrence to score
I get a frequency of words I would like to convert number_of_occuerence to a number between 0-10.</p>
```<code>word     number_of_occurrence      score
and      200                       10
png      2                         1
where    50                        6
news     120                       7
</code>```

答:
If you want to rate terms frequencies in a corpus, I suggest you to read this wikipedia article : Term frequency–inverse document frequency.

There are many ways to count the term frequency.

I understood want to rate it between 0 to 10.

I didn't get how you calculated you score values examples.

Anyway I suggest you an usual method: the log function.

#count the occurrences of you terms
freq_table = {}
  words = tokenize(sentence)
  for word in words:
    word = word.lower()
    #stem the word if you can, using nltk
    if word in stopWords:#do you really want to count the occurrences of 'and'?
      continue

    if word in freq_table:
      freq_table[word] += 1
    else:
      freq_table[word] = 1
#log normalize the occurrences
for wordCount in freq_table.values():
  wordCount = 10*math.log(1+wordCount)
```
<p>of course instead of log normalization you can use a normalization by the maximum.<br />
<img src="https://latex.codecogs.com/svg.image?0&space;%3C&space;%5Cfrac&space;%7B&space;f_%7Bt,d%7D&space;%7D%7B%5Cmax_%7B%7Bt%27&space;%5Cin&space;d%7D%7D&space;%7Bf_%7Bt%27,d%7D%7D%7D%3C&space;1" alt="" /></p>
<pre class="lang-py prettyprint-override"><code>#ratio max normalize the occurrences
max = max(freq_table.values())
for wordCount in freq_table.values():
  wordCount = 10*wordCount/max
</code>```

Or if you need a threshold effect,you can use a sigmoid function you could customize:

For more word processing check the Natural Language Toolkit. For a good term frequency count stematisation is good choice (stopwords are also useful)!

Title: occurrence to score

Body:
I get a frequency of words I would like to convert number_of_occuerence to a number between 0-10.

word     number_of_occurrence      score
and      200                       10
png      2                         1
where    50                        6
news     120                       7

Body:
If you want to rate terms frequencies in a corpus, I suggest you to read this wikipedia article : Term frequency–inverse document frequency.

There are many ways to count the term frequency.

I understood want to rate it between 0 to 10.

I didn't get how you calculated you score values examples.

Anyway I suggest you an usual method: the log function.

#count the occurrences of you terms
freq_table = {}
  words = tokenize(sentence)
  for word in words:
    word = word.lower()
    #stem the word if you can, using nltk
    if word in stopWords:#do you really want to count the occurrences of 'and'?
      continue

    if word in freq_table:
      freq_table[word] += 1
    else:
      freq_table[word] = 1
#log normalize the occurrences
for wordCount in freq_table.values():
  wordCount = 10*math.log(1+wordCount)

of course instead of log normalization you can use a normalization by the maximum.

#ratio max normalize the occurrences
max = max(freq_table.values())
for wordCount in freq_table.values():
  wordCount = 10*wordCount/max

Or if you need a threshold effect,you can use a sigmoid function you could customize:

For more word processing check the Natural Language Toolkit. For a good term frequency count stematisation is good choice (stopwords are also useful)!


问:
Can't connect RabbitMQ to my app from docker
I am currently stuck with this problem for about a week and really can't find an appropriate solution. The problem is that when I try to connect to dockerized RabbitMQ it gives me the same error every time:

```<code>wordofthedayapp-wordofthedayapp-1  | [40m[1m[33mwarn[39m[22m[49m: MassTransit[0]
wordofthedayapp-wordofthedayapp-1  |       Connection Failed: rabbitmq://localhost/
wordofthedayapp-wordofthedayapp-1  |       RabbitMQ.Client.Exceptions.BrokerUnreachableException: None of the specified endpoints were
 reachable
wordofthedayapp-wordofthedayapp-1  |        ---> System.AggregateException: One or more errors occurred. (Connection failed)
wordofthedayapp-wordofthedayapp-1  |        ---> RabbitMQ.Client.Exceptions.ConnectFailureException: Connection failed
wordofthedayapp-wordofthedayapp-1  |        ---> System.TimeoutException: The operation has timed out.
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.Impl.TaskExtensions.TimeoutAfter(Task task, TimeSpan timeout)
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectOrFail(ITcpClient socket, AmqpTcpEndpo
int endpoint, TimeSpan timeout)
wordofthedayapp-wordofthedayapp-1  |          --- End of inner exception stack trace ---
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectOrFail(ITcpClient socket, AmqpTcpEndpo
int endpoint, TimeSpan timeout)
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectUsingAddressFamily(AmqpTcpEndpoint end
point, Func`2 socketFactory, TimeSpan timeout, AddressFamily family)
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectUsingIPv4(AmqpTcpEndpoint endpoint, Fu
nc`2 socketFactory, TimeSpan timeout)
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.Impl.SocketFrameHandler..ctor(AmqpTcpEndpoint endpoint, Func`2 socket
Factory, TimeSpan connectionTimeout, TimeSpan readTimeout, TimeSpan writeTimeout)
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.Framing.Impl.IProtocolExtensions.CreateFrameHandler(IProtocol protoco
l, AmqpTcpEndpoint endpoint, Func`2 socketFactory, TimeSpan connectionTimeout, TimeSpan readTimeout, TimeSpan writeTimeout)
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.ConnectionFactory.CreateFrameHandler(AmqpTcpEndpoint endpoint)
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.EndpointResolverExtensions.SelectOne[T](IEndpointResolver resolver, F
unc`2 selector)
wordofthedayapp-wordofthedayapp-1  |          --- End of inner exception stack trace ---
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.EndpointResolverExtensions.SelectOne[T](IEndpointResolver resolver, F
unc`2 selector)
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver
, String clientProvidedName)
wordofthedayapp-wordofthedayapp-1  |          --- End of inner exception stack trace ---
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver
, String clientProvidedName)
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.ConnectionFactory.CreateConnection(IList`1 hostnames, String clientPr
ovidedName)
wordofthedayapp-wordofthedayapp-1  |          at MassTransit.RabbitMqTransport.Integration.ConnectionContextFactory.CreateConnection(I
Supervisor supervisor)
</code>```

Here you can find my docker-compose.yml:

```<code>version: '3.9'
services:
  rabbitmq:
    image: rabbitmq:3.9-management
    hostname: rabbitmq
    volumes:
      - "~/.docker-conf/rabbitmq/data/:/var/lib/rabbitmq/"
      - "~/.docker-conf/rabbitmq/log/:/var/log/rabbitmq"
    ports:
      - 5672:5672
      - 15672:15672
    expose:
     - 5672
     - 15672
    environment:
      - RABBITMQ_DEFAULT_USER=guest
      - RABBITMQ_DEFAULT_PASS=guest
    healthcheck:
        test: [ "CMD", "rabbitmqctl", "status", "-f", "http://localhost:15672"]
        interval: 5s
        timeout: 20s
        retries: 5
    networks:
      - app

  ms-sql-server:
    container_name: ms-sql-server
    image: mcr.microsoft.com/mssql/server:2019-latest
    user: root
    volumes:
      - "appdb:/var/opt/mssql/data"
    environment:
      ACCEPT_EULA: "Y"
      SA_PASSWORD: "Password123!"
      MSSQL_PID: Express
    ports:
      - 1433:1433
    healthcheck:
        test: ["CMD" ,"ping", "-h", "localhost"]
        timeout: 20s
        retries: 10
    networks:
      - app

  wordofthedayapp:
    build:
      dockerfile: WordOfTheDay.Api/Dockerfile
    image: wordofthedayapp
    environment:
      DbServer: "ms-sql-server"
      DbPort: "1433"
      DbUser: "sa"
      Password: "Password123!"
      Database: "appdb"
    ports:
      - 5001:80
    restart: on-failure
    depends_on:
      - rabbitmq
    networks:
      - app

volumes:
  appdb:

networks:
  app:
</code>```

My appsettings string:

```<code>{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "WordContext": "Server=ms-sql-server;Database=master;User=sa;Password=Password123!;MultipleActiveResultSets=true;Integrated Security=false;TrustServerCertificate=true",
    "RabbitMQHost": "amqp://elias:123456@localhost:5672"
  }
}
</code>```

This is how it works in the app using MassTransit:

```<code>public static void AddConfiguredMassTransit(this IServiceCollection services, string host)
        {
            services.AddMassTransit(Configuration =>
            {
                Configuration.UsingRabbitMq((context, config) =>
                {
                    config.Host(host);
                });
            });

            services.AddMassTransitHostedService();
        }
</code>```
```<code>services.AddConfiguredMassTransit(Configuration.GetConnectionString("RabbitMQHost"));
</code>```

I hope at least anyone knows what is wrong with this code because I really tired trying to fix it and browsing internet for solution. Thank you in advance!

P.S. Important information! Everything works perfect when I test it locally without a docker, but when I try to dockerize the app this happens.

答:
If you are testing locally, the host is likely localhost since Docker is exposing the port to the local machine. When running in a container, however, the virtual network should have a hostname of rabbitmq, which would need to be used instead of localhost when running inside a container on the same network.

Since the log shows:

Connection Failed: rabbitmq://localhost/

I'm guessing you aren't updating the host name when running inside a container.

You can determine if your application is running in a container easily:

bool IsRunningInContainer => bool.TryParse(Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER"), out var inDocker) && inDocker;
```

Then, in your configuration:

var host = IsRunningInContainer ? "rabbitmq" : "localhost";

Body:
I am currently stuck with this problem for about a week and really can't find an appropriate solution. The problem is that when I try to connect to dockerized RabbitMQ it gives me the same error every time:

wordofthedayapp-wordofthedayapp-1  | [40m[1m[33mwarn[39m[22m[49m: MassTransit[0]
wordofthedayapp-wordofthedayapp-1  |       Connection Failed: rabbitmq://localhost/
wordofthedayapp-wordofthedayapp-1  |       RabbitMQ.Client.Exceptions.BrokerUnreachableException: None of the specified endpoints were
 reachable
wordofthedayapp-wordofthedayapp-1  |        ---> System.AggregateException: One or more errors occurred. (Connection failed)
wordofthedayapp-wordofthedayapp-1  |        ---> RabbitMQ.Client.Exceptions.ConnectFailureException: Connection failed
wordofthedayapp-wordofthedayapp-1  |        ---> System.TimeoutException: The operation has timed out.
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.Impl.TaskExtensions.TimeoutAfter(Task task, TimeSpan timeout)
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectOrFail(ITcpClient socket, AmqpTcpEndpo
int endpoint, TimeSpan timeout)
wordofthedayapp-wordofthedayapp-1  |          --- End of inner exception stack trace ---
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectOrFail(ITcpClient socket, AmqpTcpEndpo
int endpoint, TimeSpan timeout)
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectUsingAddressFamily(AmqpTcpEndpoint end
point, Func`2 socketFactory, TimeSpan timeout, AddressFamily family)
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectUsingIPv4(AmqpTcpEndpoint endpoint, Fu
nc`2 socketFactory, TimeSpan timeout)
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.Impl.SocketFrameHandler..ctor(AmqpTcpEndpoint endpoint, Func`2 socket
Factory, TimeSpan connectionTimeout, TimeSpan readTimeout, TimeSpan writeTimeout)
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.Framing.Impl.IProtocolExtensions.CreateFrameHandler(IProtocol protoco
l, AmqpTcpEndpoint endpoint, Func`2 socketFactory, TimeSpan connectionTimeout, TimeSpan readTimeout, TimeSpan writeTimeout)
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.ConnectionFactory.CreateFrameHandler(AmqpTcpEndpoint endpoint)
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.EndpointResolverExtensions.SelectOne[T](IEndpointResolver resolver, F
unc`2 selector)
wordofthedayapp-wordofthedayapp-1  |          --- End of inner exception stack trace ---
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.EndpointResolverExtensions.SelectOne[T](IEndpointResolver resolver, F
unc`2 selector)
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver
, String clientProvidedName)
wordofthedayapp-wordofthedayapp-1  |          --- End of inner exception stack trace ---
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver
, String clientProvidedName)
wordofthedayapp-wordofthedayapp-1  |          at RabbitMQ.Client.ConnectionFactory.CreateConnection(IList`1 hostnames, String clientPr
ovidedName)
wordofthedayapp-wordofthedayapp-1  |          at MassTransit.RabbitMqTransport.Integration.ConnectionContextFactory.CreateConnection(I
Supervisor supervisor)

Here you can find my docker-compose.yml:

version: '3.9'
services:
  rabbitmq:
    image: rabbitmq:3.9-management
    hostname: rabbitmq
    volumes:
      - "~/.docker-conf/rabbitmq/data/:/var/lib/rabbitmq/"
      - "~/.docker-conf/rabbitmq/log/:/var/log/rabbitmq"
    ports:
      - 5672:5672
      - 15672:15672
    expose:
     - 5672
     - 15672
    environment:
      - RABBITMQ_DEFAULT_USER=guest
      - RABBITMQ_DEFAULT_PASS=guest
    healthcheck:
        test: [ "CMD", "rabbitmqctl", "status", "-f", "http://localhost:15672"]
        interval: 5s
        timeout: 20s
        retries: 5
    networks:
      - app

  ms-sql-server:
    container_name: ms-sql-server
    image: mcr.microsoft.com/mssql/server:2019-latest
    user: root
    volumes:
      - "appdb:/var/opt/mssql/data"
    environment:
      ACCEPT_EULA: "Y"
      SA_PASSWORD: "Password123!"
      MSSQL_PID: Express
    ports:
      - 1433:1433
    healthcheck:
        test: ["CMD" ,"ping", "-h", "localhost"]
        timeout: 20s
        retries: 10
    networks:
      - app

  wordofthedayapp:
    build:
      dockerfile: WordOfTheDay.Api/Dockerfile
    image: wordofthedayapp
    environment:
      DbServer: "ms-sql-server"
      DbPort: "1433"
      DbUser: "sa"
      Password: "Password123!"
      Database: "appdb"
    ports:
      - 5001:80
    restart: on-failure
    depends_on:
      - rabbitmq
    networks:
      - app

volumes:
  appdb:

networks:
  app:

My appsettings string:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "WordContext": "Server=ms-sql-server;Database=master;User=sa;Password=Password123!;MultipleActiveResultSets=true;Integrated Security=false;TrustServerCertificate=true",
    "RabbitMQHost": "amqp://elias:123456@localhost:5672"
  }
}

This is how it works in the app using MassTransit:

public static void AddConfiguredMassTransit(this IServiceCollection services, string host)
        {
            services.AddMassTransit(Configuration =>
            {
                Configuration.UsingRabbitMq((context, config) =>
                {
                    config.Host(host);
                });
            });

            services.AddMassTransitHostedService();
        }

services.AddConfiguredMassTransit(Configuration.GetConnectionString("RabbitMQHost"));

I hope at least anyone knows what is wrong with this code because I really tired trying to fix it and browsing internet for solution. Thank you in advance!

P.S. Important information! Everything works perfect when I test it locally without a docker, but when I try to dockerize the app this happens.

Body:
If you are testing locally, the host is likely localhost since Docker is exposing the port to the local machine. When running in a container, however, the virtual network should have a hostname of rabbitmq, which would need to be used instead of localhost when running inside a container on the same network.

Since the log shows:

Connection Failed: rabbitmq://localhost/

I'm guessing you aren't updating the host name when running inside a container.

You can determine if your application is running in a container easily:

bool IsRunningInContainer => bool.TryParse(Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER"), out var inDocker) && inDocker;

Then, in your configuration:

var host = IsRunningInContainer ? "rabbitmq" : "localhost";


问:
no instance(s) of type variable(s) T exist so that Block conforms to Supplier<T>
I was just coding from a course,  when there was this error:

no instance(s) of type variable(s) T exist so that Block conforms to Supplier<T>

I don't know what it is, but here is my code:

package com.berriz44.breloaded.block;

import com.berriz44.breloaded.util.Registration;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.SoundType;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.material.Material;
import net.minecraftforge.registries.RegistryObject;

import java.util.function.Supplier;

public class ModBlocks {

    public static RegistryObject<Block> SMOOTH_BRICK = register("smooth_brick", new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(2f,6f)));

    private static <T extends Block>RegistryObject<T> register(String name, Supplier<T> block) {
        RegistryObject<T> toReturn = Registration.BLOCKS.register(name, block);
        Registration.ITEMS.register(name, () -> new BlockItem(toReturn.get(), new Item.Properties().tab(CreativeModeTab.TAB_BUILDING_BLOCKS)));
        return toReturn;
    }

}

```

Send help.

答:
The method register takes a Supplier<Block>, not a Block.

You are trying to pass it a Block here instead of a Supplier<Block>:

```<code>public static RegistryObject<Block> SMOOTH_BRICK = register("smooth_brick",
    new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(2f,6f)));
</code>```

You can implement Supplier<Block> with a lambda expression:

```<code>public static RegistryObject<Block> SMOOTH_BRICK = register("smooth_brick",
    () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(2f,6f)));
</code>```

Body:
I was just coding from a course,  when there was this error:

no instance(s) of type variable(s) T exist so that Block conforms to Supplier<T>

I don't know what it is, but here is my code:

package com.berriz44.breloaded.block;

import com.berriz44.breloaded.util.Registration;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.SoundType;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.material.Material;
import net.minecraftforge.registries.RegistryObject;

import java.util.function.Supplier;

public class ModBlocks {

    public static RegistryObject<Block> SMOOTH_BRICK = register("smooth_brick", new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(2f,6f)));

    private static <T extends Block>RegistryObject<T> register(String name, Supplier<T> block) {
        RegistryObject<T> toReturn = Registration.BLOCKS.register(name, block);
        Registration.ITEMS.register(name, () -> new BlockItem(toReturn.get(), new Item.Properties().tab(CreativeModeTab.TAB_BUILDING_BLOCKS)));
        return toReturn;
    }

}

Send help.

Body:
The method register takes a Supplier<Block>, not a Block.

You are trying to pass it a Block here instead of a Supplier<Block>:

public static RegistryObject<Block> SMOOTH_BRICK = register("smooth_brick",
    new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(2f,6f)));

You can implement Supplier<Block> with a lambda expression:

public static RegistryObject<Block> SMOOTH_BRICK = register("smooth_brick",
    () -> new Block(BlockBehaviour.Properties.of(Material.STONE).sound(SoundType.STONE).strength(2f,6f)));