text:
Q: Preventing adjacent/overlapping entries with EXCLUDE in PostgreSQL I am creating a database which stores arbitrary date/time ranges in PostgreSQL 9.2.4. I want to place a constraint on this database which forces the date/time ranges to be non-overlapping, and non-adjacent (since two adjacent ranges can be expressed as a single continuous range).
To do this, I am using an EXCLUDE constraint with a GiST index. Here is the constraint I have currently:
ADD CONSTRAINT overlap_exclude EXCLUDE USING GIST (
    box(
        point (
            extract(EPOCH FROM "from") - 1,
            extract(EPOCH FROM "from") - 1
        ),
        point (
            extract(EPOCH FROM "to"),
            extract(EPOCH FROM "to")
        )
    ) WITH &&
);

The columns from and to are both TIMESTAMP WITHOUT TIME ZONE, and are date/times stored in UTC (I convert to UTC before inserting data into these columns in my application, and I have my database's timezone set to "UTC" in postgresql.conf).
The problem I am thinking I might have, though, is that this constraint is making the (incorrect) assumption that there are no time increments smaller than one second.
It is worth noting that, for the particular data I am storing, I only need second resolution. However, I feel that I may still need to deal with this since the SQL types timestamp and timestamptz are both higher resolution than one second.
My question is either: is there any problem with simply assuming second resolution, since that's all my application needs (or wants), or, if there is, how can I alter this constraint to deal with fractions-of-a-second in a robust way?

A: Range types consist of lower and upper bound, and each can be included or excluded.
The canonical form (and default for range types) is to include the lower and exclude the upper bound.
Inclusive bounds '[]'
You could include lower and upper bound ([]), and enforce it with a CHECK constraint using range functions.
Then "adjacent" ranges overlap. Excluding overlapping ranges seems clear. There is a code example in the manual.
CREATE TABLE tbl (
   tbl_id serial PRIMARY KEY
 , tsr tsrange
 , CONSTRAINT tsr_no_overlap EXCLUDE USING gist (tsr WITH &&)
 , CONSTRAINT tsr_enforce_incl_bounds CHECK (lower_inc(tsr) AND upper_inc(tsr))  -- all bounds inclusive!
);
Only ranges with inclusive bounds are allowed:
INSERT INTO tbl(tsr) VALUES ('[2013-10-22 00:00, 2013-10-22 01:00]');

db<>fiddle here
Canonical bounds '[)'
Enforce [) bounds (including lower and excluding upper).
In addition, create another exclusion constraint employing the adjacent operator -|- to also exclude adjacent entries. Both are based on GiST indexes as GIN is currently not supported for this.
CREATE TABLE tbl (
   tbl_id serial PRIMARY KEY
 , tsr tsrange
 , CONSTRAINT tsr_no_overlap  EXCLUDE USING gist (tsr WITH &&)
 , CONSTRAINT tsr_no_adjacent EXCLUDE USING gist (tsr WITH -|-)
 , CONSTRAINT tsr_enforce_bounds CHECK (lower_inc(tsr) AND NOT upper_inc(tsr))
);
db<>fiddle here
Old sqlfiddle
Unfortunately, this creates two identical GiST indexes to implement both exclusion constraints, where one would suffice, logically.

A: You can rewrite the exclude with the range type introduced in 9.2. Better yet, you could replace the two fields with a range. See "Constraints on Ranges" here, with an example that basically amounts to your use case:
http://www.postgresql.org/docs/current/static/rangetypes.html

A:
The problem I am thinking I might have, though, is that this
  constraint is making the (incorrect) assumption that there are no time
  increments smaller than one second.

You're OK there, consider:
select
  extract ('epoch' from now())
  , extract ('epoch' from now()::timestamp(0))


text:
Q: How to pass data between Nextjs server files Assume this code
// puppeteer-manager.ts

import { Browser, executablePath, Page } from "puppeteer";
import puppeteerExtra from "puppeteer-extra";
import stealthPlugin from "puppeteer-extra-plugin-stealth";

puppeteerExtra.use(stealthPlugin());

interface PuppeteerInstance {
  browser: Browser;
  page: Page;
}

let instances: { [sessionId: string]: PuppeteerInstance } = {};

async function createPuppeteerInstance(
  sessionId: string
): Promise<PuppeteerInstance> {
  if (!instances[sessionId]) {
    const browser = await puppeteerExtra.launch({
      args: ["--no-sandbox"],
      headless: false,
      ignoreHTTPSErrors: true,
      executablePath: executablePath(),
    });
    const page = await browser.newPage();
    instances[sessionId] = { browser, page };
  }
  return instances[sessionId];
}

async function closePuppeteerInstance(sessionId: string): Promise<void> {
  if (instances[sessionId]) {
    const { browser } = instances[sessionId];
    await browser.close();
    delete instances[sessionId];
  }
}

export { createPuppeteerInstance, closePuppeteerInstance };

So this code is responsible for creating new instances of puppeteer and storing them in a variable called instances and sessionId as the key.
So I'm building a NextJS app that let every connected user have their own puppeteer instance to achieve what the app is intended to.
So I will assume if I call createPuppeteerInstance in file A and pass it sessionId 1234 as session iD I will assume when I run createPuppeteerInstance in file B with the same sessionId I should get the same instance of puppeteer but for some reason, the variable instances in puppeteer-manager.ts not storing the different instance and createPuppeteerInstance keeps on creating a new instance every time I call it. I know this will just work in Express server so I'm asking/wondering could the problem be with NextJS that causes instances variable to go back to an empty object.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Something wrong with predicate in prolog-same results for every date I have the below code in Prolog and the problem is that when i run the code it returns for every data the same result.
?- run(Diagnosis).
Diagnosis='There is no problem with anemia'.

The KB is in another file and load it and in start predicate i load patient3 for example and it should return
Diagnosis ='Iron deficiency'

Note that the start predicate is only for check if the code works right for now!
When i run this file with trace it shows that first tries the first rules.. It fails in check_RTC when it tries to go to the other rule the predicate symptoms returns symptomNeg..but why?
It should take from the beginning all the data and make the checks for the every next rule, until to find the rules that doesn't fail.
:- ['kb_anemia_V4.pl'].

run(Diagnosis) :-
  clause(kb_da(patient3,DataCom,PersData,
    [Symptoms,FullBloodTest,SpecBloodTest,ElectricalHb]),Body),
  rule(kb_da(patient3,DataCom,PersData,
    [Symptoms,FullBloodTest,SpecBloodTest,ElectricalHb]),Diagnosis).

rule(kb_da(UserId,DataCom,PersData,
    [Symptoms,FullBloodTest,SpecBloodTest,ElectricalHb]), Diagnosis) :-
        symptoms(Symptoms,symptPos),  %OK
        check_WBC_PLT(FullBloodTest,noPancytopenia),
        check_RTC(FullBloodTest,rtcUp2),
        check_HBS(ElectricalHb,hbSZero),
        Diagnosis  = 'Spherocytcocis.'.

rule(kb_da(UserId,DataCom,PersData,
    [Symptoms,FullBloodTest,SpecBloodTest,ElectricalHb]), Diagnosis) :-
        symptoms(Symptoms,symptPos),
        check_WBC_PLT(FullBloodTest,noPancytopenia) ,
        check_RTC(FullBloodTest,rtcUp2),
        check_HBS(ElectricalHb,hbsUpZero),
        Diagnosis  = 'Drepanocytocis.'.

rule(kb_da(UserId,DataCom,PersData,
    [Symptoms,FullBloodTest,SpecBloodTest,ElectricalHb]), Diagnosis) :-
        symptoms(Symptoms,symptPos),
        check_WBC_PLT(FullBloodTest,noPancytopenia) ,
        check_RTC(FullBloodTest,rtcUp2),
        check_HBS(ElectricalHb,hbSZero) ;
        check_HBS(ElectricalHb,hbsUpZero),
        Diagnosis  = 'No problem with Spherocytocis or Drepanocytocis.'.

rule(kb_da(UserId,DataCom,PersData,
    [Symptoms,FullBloodTest,SpecBloodTest,ElectricalHb]), Diagnosis) :-
        symptoms(Symptoms,symptPos),
        check_WBC_PLT(FullBloodTest,noPancytopenia) ,
        check_RTC(FullBloodTest,rtcLess2),
        check_MCV(FullBloodTest,mcvLow),
        checkFerritin(FullBloodTest,ferHigh),
        checkElectrofHb([Symptoms,ElectricalHb],yesElectr),
        Diagnosis='Thalassemia'.

rule(kb_da(UserId,DataCom,PersData,
    [Symptoms,FullBloodTest,SpecBloodTest,ElectricalHb]), Diagnosis) :-
        symptoms(Symptoms,symptPos),
        check_WBC_PLT(FullBloodTest,noPancytopenia) ,
        check_RTC(FullBloodTest,rtcLess2),
        check_MCV(FullBloodTest,mcvLow),
        checkFerritin(FullBloodTest,ferHigh),
        checkElectrofHb([Symptoms,ElectricalHb],noElectr),
        Diagnosis  = 'There is not problem with anemia,probably hemochromatosis,because of High feritin.'.

rule(kb_da(UserId,DataCom,PersData,
    [Symptoms,FullBloodTest,SpecBloodTest,ElectricalHb]), Diagnosis) :-
        symptoms(Symptoms,symptPos),
        check_WBC_PLT(FullBloodTest,noPancytopenia) ,
        check_RTC(FullBloodTest,rtcLess2),
        check_MCV(FullBloodTest,mcvLow),
        checkFerritin(FullBloodTest,ferLow),
        check_HCT_Hb_FE([FullBloodTest,PersData],hctLow),
        checkRBC([FullBloodTest,PersData],rbcLow),
        Diagnosis  = 'Iron Deficiency'.

rule(kb_da(UserId,DataCom,PersData,
    [Symptoms,FullBloodTest,SpecBloodTest,ElectricalHb]), Diagnosis) :-
        symptoms(Symptoms,symptPos),
        check_WBC_PLT(FullBloodTest,noPancytopenia) ,
        check_RTC(FullBloodTest,rtcLess2),
        check_MCV(FullBloodTest,mcvLow),
        checkFerritin(FullBloodTest,ferLow),
        check_HCT_Hb_FE([FullBloodTest,PersData],hctLow),
        checkRBC([FullBloodTest,PersData],rbcHigh),
        checkElectrHb([[Symptoms,ElectricalHb]],electro),
        Diagnosis  = 'Minor Thalassemia'.

rule(kb_da(UserId,DataCom,PersData,
    [Symptoms,FullBloodTest,SpecBloodTest,ElectricalHb]), Diagnosis) :-
        symptoms(Symptoms,symptPos),
        check_WBC_PLT(FullBloodTest,noPancytopenia) ,
        check_RTC(FullBloodTest,rtcLess2),
        check_MCV(FullBloodTest,mcvLow),
        checkFerritin(FullBloodTest,ferLow),
        check_HCT_Hb_FE([FullBloodTest,PersData],hctHigh),
        checkRBC([FullBloodTest,PersData],rbcHigh),
        checkElectrHb([[Symptoms,ElectricalHb]],electro),
        Diagnosis  = 'Minor Thalassemia'.

rule(kb_da(UserId,DataCom,PersData,
    [Symptoms,FullBloodTest,SpecBloodTest,ElectricalHb]), Diagnosis) :-
        symptoms(Symptoms,symptNeg),
            Diagnosis  = 'There is not problem with anemia.'.

rule(kb_da(UserId,DataCom,PersData,
    [Symptoms,FullBloodTest,SpecBloodTest,ElectricalHb]), Diagnosis) :-
        symptoms(Symptoms,symptPos),
        check_WBC_PLT(FullBloodTest,noPancytopenia) ,
        check_RTC(FullBloodTest,rtcLess2),
        check_MCV(FullBloodTest,mcvNormal),
        checkFerritin(FullBloodTest,ferHigh),
        checkElectrofHb([Symptoms,ElectricalHb],yesElectr),
        Diagnosis='Thalassemia'.

rule(kb_da(UserId,DataCom,PersData,
    [Symptoms,FullBloodTest,SpecBloodTest,ElectricalHb]), Diagnosis) :-
        symptoms(Symptoms,symptPos),
        check_WBC_PLT(FullBloodTest,noPancytopenia) ,
        check_RTC(FullBloodTest,rtcLess2),
        check_MCV(FullBloodTest,mcvHigh),
        check_B12_RBC([PersData,FullBloodTest,SpecBloodTest],b12Low),
        Diagnosis = 'B12 Anemia'.

rule(kb_da(UserId,DataCom,PersData,
    [Symptoms,FullBloodTest,SpecBloodTest,ElectricalHb]), Diagnosis) :-
        symptoms(Symptoms,symptPos),
        check_WBC_PLT(FullBloodTest,noPancytopenia) ,
        check_RTC(FullBloodTest,rtcLess2),
        check_MCV(FullBloodTest,mcvHigh),
        check_Folic(SpecBloodTest,folic),
        Diagnosis = 'Folic Acid Anemia'.

rule(kb_da(UserId,DataCom,PersData,
    [Symptoms,FullBloodTest,SpecBloodTest,ElectricalHb]), Diagnosis) :-
        symptoms(Symptoms,symptPos),  %OK
        check_WBC_PLT(FullBloodTest,yesPancytopenia),
        Diagnosis = 'Check bone marrow'.

symptoms(Symptoms,symptPos) :-
    check_symptomList(Symptoms), !.
symptoms(Symptoms,symptNeg).

check_symptomList([H|T]) :-
    SymptomList = ['Πονοκέφαλος', 'Αδυναμία', 'Έλλειψη αυτοσυγκέντρωσης',
        'Απώλεια βάρους', 'Απώλεια όρεξης', 'Ωχρότητα',
        'Επώδυνη σπλήνα', 'Ταχυκαρδία', 'Δύσπνοια','Γλωσσίτιδα','Πληγές',
        'Ελλειπής διατροφή', 'πατερας_Στίγμα', 'πατερας_Μεσογειακή',
        'μητερα_Στίγμα', 'μητερα_Μεσογειακή', 'Ιδιαίτερο'],
    member(H,SymptomList).
check_symptomList([H|T]) :-
     check_symptomList(T).

check_WBC_PLT([WBC,RTC,MCV,RBC,FE,Ferritin,TIBC,Hct,Hb,PLT], noPancytopenia) :-
     number(WBC), number(PLT),
        (WBC > 4500, PLT>150)
;       number(WBC), number(PLT),(WBC > 4500, PLT=<150)
;       number(WBC), number(PLT),(WBC =< 4500, PLT>150).

check_WBC_PLT([WBC,RTC,MCV,RBC,FE,Ferritin,TIBC,Hct,Hb,PLT],yesPancytopenia) :-
    number(WBC), number(PLT),
        (WBC =< 4500, PLT=<150).

check_RTC([WBC,RTC,MCV,RBC,FE,Ferritin,TIBC,Hct,Hb,PLT],rtcLess2):-
        number(RTC),RTC=<2.
check_RTC([WBC,RTC,MCV,RBC,FE,Ferritin,TIBC,Hct,Hb,PLT],rtcUp2):-
        number(RTC),RTC>2.

check_MCV([WBC,RTC,MCV,RBC,FE,Ferritin,TIBC,Hct,Hb,PLT],mcvLow):-
        number(MCV), MCV=<79.

check_MCV([WBC,RTC,MCV,RBC,FE,Ferritin,TIBC,Hct,Hb,PLT],mcvNormal):-
        number(MCV), MCV>79,MCV<97.

check_MCV([WBC,RTC,MCV,RBC,FE,Ferritin,TIBC,Hct,Hb,PLT],mcvHigh):-
        number(MCV), MCV=<97.

check_HBS([HbA1,HbA2,HbS,HbF,Schema_RBC],hbSZero):-
        number(HbS), HbS=0,
        Schema_RBC='Σφαίρα'.

check_HBS([HbA1,HbA2,HbS,HbF,Schema_RBC],hbSZero):-
        number(HbS), HbS=0.

check_HBS([HbA1,HbA2,HbS,HbF,Schema_RBC],hbsUpZero):-
        number(HbS), HbS>0,
        Schema_RBC=='Δρεπάνι'.
check_HBS([HbA1,HbA2,HbS,HbF,Schema_RBC],hbsUpZero):-
        number(HbS), HbS>0.

checkFerritin([WBC,RTC,MCV,RBC,FE,Ferritin,TIBC,Hct,Hb,PLT],ferLow):-
        number(Ferritin),Ferritin=<20.
checkFerritin([WBC,RTC,MCV,RBC,FE,Ferritin,TIBC,Hct,Hb,PLT],ferHigh):-
        number(Ferritin),Ferritin>20.

checkElectrofHb([Symptoms, ElectricalHb],electro):-
     Symptoms = ['Πονοκέφαλος', 'Αδυναμία', 'Έλλειψη αυτοσυγκέντρωσης',
        'Απώλεια βάρους', 'Απώλεια όρεξης', 'Ωχρότητα',
        'Επώδυνη σπλήνα', 'Ταχυκαρδία', 'Δύσπνοια','Γλωσσίτιδα','Πληγές',
        'Ελλειπής διατροφή', 'πατερας_Στίγμα', 'πατερας_Μεσογειακή',
        'μητερα_Στίγμα', 'μητερα_Μεσογειακή', 'Ιδιαίτερο'],
        ElectricalHb = [HbA1,HbA2,HbS,HbF,Schema_RBC],
        member('Ιδιαίτερο', Symptoms),
        (member('πατερας_Στίγμα', Symptoms),
            member('μητερα_Μεσογειακή', Symptoms))
    ;   (member('πατερας_Μεσογειακή', Symptoms),
             member('μητερα_Στίγμα', Symptoms))
    ;   (member('πατερας_Μεσογειακή', Symptoms),
            member('μητερα_Μεσογειακή', Symptoms)),
        number(HbF),HbF>2,HbF<9,
        number(HbA1), HbA1<5.

check_HCT_Hb_FE([[WBC,RTC,MCV,RBC,FE,Ferritin,TIBC,Hct,Hb,PLT],[Hlikia,Filo,Egkimosini]],hctLow):-
        (Filo='male',number(Hct),number(Hb),number(Fe),Hct<40,Hb<14,Fe<55
        ; Filo='female',number(Hct),number(Hb),number(Fe),Hct<36,Hb<10,Fe<45
        ; Filo='male',Egkimosini=yes,number(Hct),number(Hb),number(Fe),Hct<36,Hb<12,Fe<55).

check_HCT_Hb_FE([[WBC,RTC,MCV,RBC,FE,Ferritin,TIBC,Hct,Hb,PLT],[Hlikia,Filo,Egkimosini]],hctHigh).

checkRBC([[WBC,RTC,MCV,RBC,FE,Ferritin,TIBC,Hct,Hb,PLT],[Hlikia,Filo,Egkimosini]],rbcLow):-
        (Filo='male',number(RBC),RBC<4.5);
        (Filo='female',number(RBC),RBC<3.8).

checkRBC([[WBC,RTC,MCV,RBC,FE,Ferritin,TIBC,Hct,Hb,PLT],[Hlikia,Filo,Egkimosini]],rbcHigh):-
        (Filo='male',number(RBC),RBC>6);
        (Filo='female',number(RBC),RBC>4.9).

checkElectrHb([Symptoms, ElectricalHb],electro):-
     Symptoms = ['Πονοκέφαλος', 'Αδυναμία', 'Έλλειψη αυτοσυγκέντρωσης',
        'Απώλεια βάρους', 'Απώλεια όρεξης', 'Ωχρότητα',
        'Επώδυνη σπλήνα', 'Ταχυκαρδία', 'Δύσπνοια','Γλωσσίτιδα','Πληγές',
        'Ελλειπής διατροφή', 'πατερας_Στίγμα', 'πατερας_Μεσογειακή',
        'μητερα_Στίγμα', 'μητερα_Μεσογειακή', 'Ιδιαίτερο'],
        ElectricalHb = [HbA1,HbA2,HbS,HbF,Schema_RBC],
         member('πατερας_Στίγμα', Symptoms);
         member('μητερα_Στίγμα', Symptoms);
         member('μητερα_Μεσογειακή', Symptoms);
         member('πατερας_Μεσογειακή', Symptoms),
        number(HbF),HbF>2,HbF<9,
        number(HbA1), HbA1<1.

check_B12_RBC([[Hlikia,Filo,Egkimosini],[WBC,RTC,MCV,RBC,FE,Ferritin,TIBC,Hct,Hb,PLT],[B12,Folic_acid,tSH,Kreatinin]],b12Low):-
        (Filo='male',number(RBC),RBC>6);
        (Filo='female',number(RBC),RBC>4.9),
        number(B12), B12<130.

check_Folic([B12,Folic_acid,tSH,Kreatinin],folic):-
        number(Folic_acid), Folic_acid<3.1.

The kb code file is
:- dynamic kb_da/4.

kb_da(patient1,['Ιωάννης Ιωάννου','Φλέμινγκ3 71410 Ηράκλειο','2810123456'],
     [50,male,na],[['Πονοκέφαλος','Aδυναμία','Έλλειψη αυτοσυγκέντρωσης'],_,_,_]).

     %Sidiropenik Anaimia
kb_da(patient2,
    ['Δημήτρης Παπαδημητρίου','Αρχαγγέλου 17 Κοκκινοτριμιθιά Λευκωσίας','0035797273515'],
       [27,male,na], [['Πονοκέφαλος','Κούραση','Ταχυκαρδία','Δύσπνοια'],
    [4800,1,75,4.3,45,18,280,33,12,125],_,_]).

kb_da(patient3,['Δέσποινα Μπασδέκη','Πανός 19 71410 Ηράκλειο',6955457845],[24,female,no],
        [['Πονοκέφαλος','Έλλειψη αυτοσυγκέντρωσης','Ελλειπής διατροφή','Δύσπνοια','Ταχυκαρδία'],
        [4300,1,75,3.7,41,18,250,30,10,180],_,_]).

kb_da(patient4,['Δήμητρα Περπερίδου','Καραμανώλη 5 55142 Θεσσαλονίκη',6977458521],[32,female,yes],
        [['Πονοκέφαλος','Έλλειψη αυτοσυγκέντρωσης','Ελλειπής διατροφή','Δύσπνοια','Ταχυκαρδία','Ταχυκαρδία'],
        [4800,1,72,3.7,50,15,280,32,10,180],_,_]).

 %Stigma Mesogeiaki Anaimia

kb_da(patient5,['Manolis Manolaou','Epaminondos 24 55142 Θεσσαλονίκη',6985245125],[50,male,na],
        [['Πονοκέφαλος','Δύσπνοια','Ταχυκαρδία','Ταχυκαρδία','μητερα_Στίγμα'],
        [4800,1,78,7,45,15,320,39,13,125],_,_]).

kb_da(patient6,['Manolis Pavlou','Venizelou 24 59100 Veroia',6977148545],[25,male,na],
        [['Πονοκέφαλος','Δύσπνοια','Ταχυκαρδία','πατερας_Μεσογειακή',],
        [4800,1,78,7.8,45,15,320,39,13,155],_,_]).

kb_da(patient7,['Maria Papadopoulou','Venizelou 24 59100 Veroia',6985478452],[42,female,na],
        [['Πονοκέφαλος','Δύσπνοια','Ταχυκαρδία','Ελλειπής διατροφή','μητερα_Μεσογειακή'],
        [4800,1,78,7.8,45,15,320,39,13,155],_,_]).

% Mesogeiaki Anaimia

kb_da(patient8,['Μαρία Παπανικολάου','Βετσοπούλου 24 59100 Αλεξάνδρεια',6974582545],[42,female,no],
        [['Πονοκέφαλος','Δύσπνοια','Αδυναμία','Ταχυκαρδία','Ελλειπής διατροφή','πατερας_Στίγμα','μητερα_Μεσογειακή','Ιδιαίτερη'],
        [4800,1,85,5.5,45,22,320,39,13,155],_,
        [3,hbA2,hbS,5,schema_RBC]]).

kb_da(patient9,['Γεώργιος Παπαδήμου','Παπανικολάου 58 47854 Βόλος',6974585124],[85,male,na],
        [['Πονοκέφαλος','Ωχρότητα','πατερας_Μεσογειακή','πατερας_Μεσογειακή','Ιδιαίτερο'],
        [4800,1,85,5.5,45,22,320,39,13,155],_,
        [3,hbA2,hbS,5,schema_RBC]]).

kb_da(patient10,['Γεώργιος Καρανικόλας','Χαριλάου Τρικούπη 58 56954 Θεσσαλονίκη',6974585412],[45,male,na],
        [['Πονοκέφαλος','Ωχρότητα','πατερας_Μεσογειακή','μητερα_Στίγμα','Ιδιαίτερη'],
        [4400,1,75,5.5,45,22,320,39,13,125],_,
        [4,hbA2,hbS,2,schema_RBC]]).

%Β12

kb_da(patient11,['Παναγιώτης Μπομπότης','Αιγαίου 3 17122 Ν.Σμύρνη Αττικης ',6974585123],[22,male,no],
        [['Πονοκέφαλος','Ωχρότητα','Απώλεια βάρους','Απώλεια όρεξης'],
        [4400,1,100,3.5,45,22,320,39,13,125],
        [125,3.5,tSH,creatinine],_]).

kb_da(patient12,['Δήμητρα Καρανικόλα','Χαριλάου Τρικούπη 58 56954 Θεσσαλονίκη',6974585412],[24,female,na],
        [['Απώλεια βάρους','Απώλεια όρεξης'],
        [4800,1,100,3.7,45,22,320,39,13,170],
        [125,2,tSH,creatinine],_]).

%Foliko O3i

kb_da(patient13,['Κίμωνας Ιωαννίδης','Βρυλήσια Αττικής',6984575625],[65,male,no],
        [['Απώλεια βάρους','Απώλεια όρεξης'],
        [4800,1,100,5.5,45,22,320,39,13,170],
        [125,2,tSH,creatinine],_]).

kb_da(patient14,['Ιουλια Αναστασιάδου','Κουντουριωτη 3 54625 Θεσσαλονίκη',6958475202],[35,female,yes],
        [['Απώλεια βάρους','Ωχρότητα','Απώλεια όρεξης'],
        [4800,1,100,3.7,45,22,320,39,13,170],
        [145,2,tSH,creatinine],_]).

%Drepanokitarwsi

kb_da(patient15,['Βασίλης Παπακωσταντίνου','Μητροπόλεως 18 74125 Ν. Ιωνία',6955447751],[35,male,no],
        [['Απώλεια βάρους','Απώλεια όρεξης'],
        [4800,2,100,3.7,45,22,320,39,13,170],
        [hbA1,hbA2,1,hbF,'Δρεπάνι'],_]).

kb_da(patient16,['Θοδωρής Onir','Καραμανλή 45 74125 Ν.Ιωνία',6977457845],[38,male,no],
        [['Απώλεια βάρους','Ωχρότητα','Απώλεια όρεξης'],
        [4400,2,100,3.7,45,22,320,39,13,170],
        [hbA1,hbA2,2,hbF,'Δρεπάνι'],_]).

%Σφαιροκυττάρωση

kb_da(patient17,['Όλγα Σαμανίδου','Κηφισιάς 45 74125 Κηφισιά',6985544125],[29,female,yes],
        [['Πονοκέφαλος','Δύσπνοια','Αδυναμία','Απώλεια βάρους','Ωχρότητα','Απώλεια όρεξης'],
        [4900,2,100,3.2,45,28,320,39,13,120],
        [hbA1,hbA2,0,hbF,'Σφαίρα'],_]).

kb_da(patient18,['Σοφία Χατζηπαυλή','Γεωργίου Βλαστού 12 45785 Κώς',6974545455],[18,female,no],
        [['Πονοκέφαλος','Αδυναμία','Ωχρότητα','Απώλεια όρεξης'],
        [4900,2,100,3.2,45,28,320,39,13,170],
        [hbA1,hbA2,0,hbF,'Σφαίρα'],_]).

%Den iparxei provlima

kb_da(patient19,['Βλάση Μπονάτσο','Παπαμιχαήλ 54 14585 Αθήνα',6985545212],[58,male,no],
        [['Αδυναμία','Ωχρότητα','Απώλεια όρεξης'],
        [4900,2,100,3.2,45,28,320,39,13,170],
        [hbA1,hbA2,0,hbF,'Κανονικό'],_]).

kb_da(patient20,['Μαρία Παπαμιχαήλ','Κονίτσης 54 59100 Βέροια',6984525154],[42,female,no],
        [['Αδυναμία','Ωχρότητα','Απώλεια όρεξης'],
        [4900,2,99,3.2,45,28,320,45,13,170],
        [hbA1,hbA2,2,hbF,'Κανονικό'],_]).

A: Here are some remarks.
1mo, always take the warnings a system generates seriously and remove them.  You have all kinds of singleton variables some of which are problems and some are not. And in fact, in rule check_HCT_Hb_FE there is FE and Fe.
check_HCT_Hb_FE([[WBC,RTC,MCV,RBC,Fe,Ferritin,TIBC,Hct,Hb,PLT],[Hlikia,Filo,Egkimosini]],hctLow):-
%                                 ^^ was FE
        (  Filo='male', * ...
        ;  Filo='female',number(Hct),number(Hb),number(Fe), Hct<36,Hb<10,Fe<45
        ;  Filo='male', * ...
        ).

2do, it is not clear to me that using number/1 makes much sense. Arithmetic predicates like the Fe<45 are testing for a valid value anyway and produce an error in case something is wrong.
3tio, there is some odd syntax (which is otherwise unrelated). Search for person6 and ,].
4to, to localize the problem I added the following lines to your program:
:- op(950, fy, *).
*_.

In this case it was quite easy since you said that Iron deficiency is expected:

rule(kb_da(UserId,DataCom,PersData,
    [Symptoms,FullBloodTest,SpecBloodTest,ElectricalHb]), Diagnosis) :-
        * symptoms(Symptoms,symptPos),
        * check_WBC_PLT(FullBloodTest,noPancytopenia),
        * check_RTC(FullBloodTest,rtcLess2),
        * check_MCV(FullBloodTest,mcvLow),
        * checkFerritin(FullBloodTest,ferLow),
        check_HCT_Hb_FE([FullBloodTest,PersData],hctLow),
        * checkRBC([FullBloodTest,PersData],rbcLow),
        Diagnosis  = 'Iron Deficiency'.

The highly generalized program already failed, so it was evident that the problem was within that goal check_HCT_Hb_FE/2 in particular the failing goal was
check_HCT_Hb_FE([[4300,1,75,3.7,41,18,250,30,10,180],[24,female,no]],hctLow)

However, the three conditions Hct<36,Hb<10,Fe<45 are not true in this case, in fact they are instantiated to 30<36,10<10,41<45 and 10<10 does not hold.


text:
Q: How to find the function $f$ given $f(f(x)) = 2x$? I was wondered how to find the function in this equality:
$f(f(x))=2x$.  Also $f$ is continuous.
I don't need the answer, how to find it is more important.

A: For another class of solutions, try $f(x) = -c x$ for $x \ge 0$, $-(2/c) x$ for $x < 0$, where $c > 0$ is constant.  Still more generally, let  $h(x) = x p(\log_2(x))$ for $x > 0$ where $p$ is continuous and  periodic with period 1 and $p(t) +  p'(t)/\ln(2) > 0$ everywhere.  Thus $h$ is an increasing continuous function from $(0,\infty)$ onto itself, thus invertible on $(0,\infty)$.
Let $f(x) = - h(x)$ for $x > 0$, $f(0) = 0$, $f(x) = 2 h^{-1}(-x)$ if $x < 0$.

A: Nevermind!  I became focused on solving $f(2x)=2f(x)$, which is a consequence of the original equation, but not equivalent.  I'll leave this here in case it helps with an actual solution.

As has been noted, $f(0)=0$.  Let $f(1)=a$.
As noted in my comment,  $$f(2x)=2f(x)$$  Inductively, for all $n\in\mathbb{Z}$, $$f(2^nx)=2^nf(x)$$  In particular, $f(2^n)=2^na$.  That is, upon choosing a value $a$ for $f$ at $1$, the function's values at $\{\ldots,\frac14,\frac12,1,2,4,\ldots\}$ are immediately determined.
Now I claim that any continuous function on $[1,2]$ with $f(1)=a$ and $f(2)=2a$ extends to a function $f$ on $(0,\infty)$, using the relation $f(2^nx)=2^nf(x)$.
Similalary,we could choose a completely different continuous function on $[-2,-1]$ with $f(-1)=b$ and $f(-2)=2b$, and extend to $(-\infty,0)$.  Combined with the observation that $f(0)=0$, this gives a very big space of solutions defined on $(-\infty,\infty)$.
As an example of how exotic these solutions could be, consider $f(x)=(\sin(2\pi\log_2(x))+5)x$.

A: There are many constructions already of continuous functions satisfying the hypothesis. Even better, I believe that Robert gives examples where the function is differentiable everywhere in $\mathbb R \setminus \{0\}$. I will show that this situation is tight.
In particular, I show that if $f$ is such that

*

*$f(f(x))=2x$, and

*$f$ is differentiable at $0$,

then $f(x) = cx$ for all $x$, where $c := f'(0)$. Note that we do not require continuity anywhere but at the origin. Moreover, substituting $f(x)=cx$ in the functional equation, it is clear that the only possible values of $c$ are $\pm \sqrt{2}$.
We have already showed that $f(0) = 0 = c \cdot 0$, so fix $t \in \mathbb R \setminus \{0\}$. Define the sequence $x_n$ by $x_n := \frac{t}{2^n}$. Then from alex.jordan's observation that $f(2x) = 2f(x)$, it is evident that the sequence
$$
\frac{f(x_n)}{x_n} = \frac{f(t)}{t}
$$
for all $n$. In particular, the limit is the above expression as well.
On the other hand, notice that $x_n \to 0$, and by hypothesis $f'(0) = c$. Therefore, $$
\frac{f(t)}{t} = \lim_{n \to \infty} \frac{f(x_n)}{x_n} = \lim\limits_{n\to \infty} \frac{f(x_n) - f(0)}{x_n} = \lim\limits_{x\to 0} \frac{f(x) - f(0)}{x} = f'(0) = c,
$$
which gives the claim.

A: This is not a general solution, but I think there are more continuous solution the functional equation. Consider, for e.g.,
$$
f(x) =
\begin{cases}
x \left( \frac{11}{6} - \frac{x}{3} \right), &\text{ for } x \in \left[ 1, \frac{3}{2} \right],
\\
\frac{11}{2} - \sqrt{\frac{121}{4} - 12x}, &\text{ for } x \in \left[ \frac{3}{2}, 2 \right],
\end{cases}
$$
We can extend the definition to all positive numbers by declaring:
$$
f(x) =
\begin{cases}
\frac{1}{2}f(2x), & \ 0 < x < 1,
\\
2f \Big(\frac{x}{2} \Big), & \ x > 2,
\end{cases}
$$
Finally, we extend the function to negative numbers and zero, by declaring the function to be odd. So $f(0) = 0$ and $f(-x) = -f(x)$ for all $x > 0$.
If I haven't done any mistakes, then this function is continuous and satisfied $f(f(x)) = 2x$.

We should check that the function is continuous, and it satisfies $f(f(x)) =  2x$. I am not spelling out the details here now, because it is quite tedious :-). I will think whether is a direct way to verify our requirements. Meanwhile, if there's any demand to show specific properties, I can certainly do so.

A: More generally, suppose we want to find a "composition square root" of $ax^b$, where $a$ and $b$ are positive real numbers. Let's assume there is a solution of the form $f(x)=cx^d$ for some real numbers $c$ and $d$ and see where that takes us. From $f\left(f(x)\right) = ax^b,$ we get
$$c \cdot \left(cx^{d} \right)^{d} \; = \; ax^{b}$$
Therefore, $c^{d+1}=a$ and $d^{2}=b$, which we can easily solve for $c$ and $d$ in terms of $a$ and $b$ to get
$$f(x) \; = \; a^{\frac{1}{{\sqrt b}\; +\; 1}} \cdot x^{\sqrt b}$$

A: $f$ is injective. Assume that $f(x) = f(y)$ for some $x \neq y$, then $2x = f(f(x)) = f(f(y)) = 2y$. As $f(\mathbb{R}) = \mathbb{R}$ by definition, $f$ is surjective and hence bijective. $f$ is also monotonous.
From here on I'd like to follow up alex.jordan's answer.
From $f(1) = a$ we get $f(a) = 2$, another necessary condition.
For $a \geq 0$, three cases are possible:

*

*$1 < a < 2$

*$0 < a \leq 1$ ($a=0$ is not possible)

*$a \geq 2$

For case 1., I claim that any continuous and bijective function $f$ with the following properties solves the assignment:

*

*$f(0)=0, f(1)=a, f(a)=2, f(2)=2a$

*For $x \in (1, a)$, $f(x) \in (a, 2)$ so that  $f(f(x)) = 2x \in (2, 2a)$.

*(from alex.jordan's answer): $f(2^n x) = 2^n f(x)$.

*(from alex.jordan's answer): Likewise for $x < 0$ with $f(-1) = b$ and $f(-2) = 2b$.

Informally speaking, any deviation from $f(x) = ax$ imposed by the first application of $f$ is undone by its second application. IMO, this is more restrictive than the solution provided by alex.jordan. Moreover, I believe that the above conditions are necessary as well: 1., 3. and 4. have been proven necessary by alex.jordan, 2. is necessary due to bijectivity and monotony which has been proven necessary above.
Case 2. is impossible: $a \leq 1 < 2$, but $f(a) \geq f(2) > f(1)$.
Case 3. is impossible, too: $1 < 2 \leq a$, but $f(a) \leq f(1) < f(2)$.
A similar, but much more convoluted solution is possible for the case $a < 0$, yielding $-2 < a < -1$. Here, $f((1, -a)) = (b, -2)$, and $f((b, -2)) = (2, -2a)$; likewise, $f((-a, 2)) = (-2, 2b)$ and $f((-2, 2b)) = (4, -4a)$.
$f(x) = \pm \sqrt{2} x$ are special cases of the above generic solution.
Edit: Now I see that this has been proposed by Robert Israel before.

A: If $f$ has a power series, you could try composing the power series.  Since $f(0)=0$, we don't need to translate:
$$
f(x) = a_1x+a_2x^2+a_3x^3+\dots
$$
Therefore,
$$
\begin{align}
f(f(x)) &= a_1(a_1x+a_2x^2+a_3x^3+\dots)\\
&+a_2(a_1x+a_2x^2+a_3x^3+\dots)^2\\
&+a_3(a_1x+a_2x^2+a_3x^3+\dots)^3\\
&+\dots\\
&=a_1^2x+a_1a_2(1+a_1)x^2+a_1(2a_2^2+a_3+a_1^2a_3)x^3+\dots\tag{1}
\end{align}
$$
Using $(1)$, we get that $a_1=\sqrt{2}$ or $a_1=-\sqrt{2}$, then $a_2=0$, and $a_3=0$.  Checking, we see that both $f(x)=\sqrt{2}\;x$ and $f(x)=-\sqrt{2}\;x$ work.
Addition: Using alex.jordan's comment that $f(2x)=2f(x)$, if $f^{\;\prime}\in\operatorname{Lip}(\alpha)$ for some $\alpha>0$, i.e. $f\in\operatorname{Lip}(1+\alpha)$, then these two solutions are the only solutions.


text:
Q: How to execute a get request over ssl with a specified ca file As an experiment I'm trying to do a GET request to https://google.com with a specified ca file.
The certificate of Google was retrieved through the following openssl command:
openssl s_client -showcerts -connect google.com:443 </dev/null 2>/dev/null|openssl x509 -outform PEM >mycertfile.pem

Using this certificate, I make a GET request with the following code:
cafile = "mycertfile.pem"
r = requests.get("https://google.com", verify=cafile)
print(r.status_code)

Why does this not work and result in an SSL certificate verification failure?
Traceback (most recent call last):
  File "C:/Users/jarno/Projects/pyplayground/main.py", line 6, in <module>
    r = requests.get("https://google.com", verify=cafile)
  File "C:\Users\jarno\Projects\flasktest\venv\lib\site-packages\requests\api.py", line 76, in get
    return request('get', url, params=params, **kwargs)
  File "C:\Users\jarno\Projects\flasktest\venv\lib\site-packages\requests\api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\jarno\Projects\flasktest\venv\lib\site-packages\requests\sessions.py", line 530, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\jarno\Projects\flasktest\venv\lib\site-packages\requests\sessions.py", line 643, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\jarno\Projects\flasktest\venv\lib\site-packages\requests\adapters.py", line 514, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='google.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1076)')))


text:
Q: addEventListener memory leak due to frames I have a GreaseMonkey script that works on a site that uses frames as an integral part of its interface.  This script leaks memory like a sieve, and I believe it is due to my use of addEventListener within one of the frames.  Quite simply, I attach a variety of event listeners, then the frame reloads and I attach the event listeners, and then the frame reloads, around and around for hundreds or possibly thousands of iterations as you interact with various elements in this frame or others.  By the end of it, Firefox has gone from ~300M of memory to as much as 2G (or crashes before it gets there).
I read somewhere that doing a full page reload would allow FireFox's garbage collection routines to kick in and recover all the memory from orphaned event handlers, and sure enough when I hit F5 after my script has run for a while, within about 10 seconds the memory is back down to 300M.  Unfortunately this breaks a different frame in the site (a very popular chat window), so while it does seem to confirm my suspicion that addEventListener is to blame, it's not really an option as a solution.
Is there something else I can do to free up the memory properly without forcing a full page refresh?
(Currently using GM 1.5 and FF 17, but the issue has existed since GM 0.8/FF 4 or thereabouts.)

A: Without seeing your complete script, or a Short, Self Contained, Compilable Example, we can't be sure of what is going on.  It may be that addEventListener is not the problem.
Here are some strategies for better code, with fewer memory leaks:

*

*Inline/anonymous functions are often a culprit, especially with event handlers.
Poor / Leaky:
elem.onclick = function () {/*do something*/};
elem.addEventListener ("click", function() {/*do something*/}, false);
$("elem").click ( function () {/*do something*/} );

Not leaky and also easier to maintain:
elem.onclick = clickHandler;
elem.addEventListener ("click", clickHandler, false);
$("elem").click (clickHandler);

function clickHandler (evt) {
    /*do something*/
}

Note that for userscripts you should avoid onclick, etc. anyway.

*Likewise do not use JS on HTML attributes.  EG don't use <span onclick="callSomeFunction()">, etc.

*Minimize the code that runs in iframes to only that code you explicitly want.

*

*Use the @include, @exclude, and @match directives to block as many unwanted iframes as possible.

*Wrap all code that doesn't need to run in iframes in a block like so:
if (window.top === window.self) {
  // Not in a frame
}

*Do not use innerHTML.

*For lots of elements, or elements that come and go with AJAX, do not use addEventListener() or jQuery's .bind(), .click(), etc.
This replicates the listener across, potentially, thousands of nodes.
Use jQuery's .on().  That way the listener is attached only once and triggers appropriately via bubbling.  (Note that in some rare-ish cases .on() can be blocked by the page's javascript.)
In your case, you probably want something like:
$(document).on ("click", "YOUR ELEM SELECTOR", clickHandler);

function clickHandler (evt) {
    /*do something*/
}

*To avoid surprise circular references or orphaned items, use jQuery to add or remove elements, rather than direct DOM methods like createElement(), appendChild(), etc.
jQuery is designed/tested to minimize such things.

*Beware of overusing GM_setValue().  It easily can use lots of global resources or cause a script instance to crash.

*

*For same-domain values, use localStorage.

*Do not use GM_setValue() to store anything but strings.  For anything else, use a serializer such as GM_SuperValue.  Even innocent looking integers can cause the default GM_setValue() to crash.

*Rather than store lots of small variables, it may be better to wrap them in an object and store that with one of the serializers.

*Always check return values and assume that elements can be missing:
This is poor (and, alas, typical):
$("selector").text($("selector").text().match(/foo=([bar]+)/)[1]);

Better:
var salesItemDiv    = $("selector");
var fooMatch        = salesItemDiv.text ().match (/\bfoo\s*=\s*([bar]+)\b/i);
if (fooMatch  &&  fooMatch.length > 1) {
    salesItemDiv.text ( fooMatch[1] );
}

possibly followed by:
salesItemDiv = fooMatch = null;

see below.

*Beware of recursive / inline setTimeout() calls.  Use setInterval() for repeated timing.  Just like with event handlers, do not use inline/anonymous functions.

*Run your code through JSLint.

*Avoid eval() and auto/hidden eval() invocations.

*Set variables to null when you are done with them. See this, for example.

*Reference: "Do you know what may cause memory leaks in JavaScript?"

*Additional reading on JS memory leaks

*Mozilla Performance: Leak Tools


text:
Q: Recommendation for an in-memory database I would like to remove sql dependency of small chunks of data that I load on (almost) each request on a web application. Most of the data is key-value/document structured, but a relational solution is not excluded. The data is not too big so I want to keep it in memory for higher availability.
What solution would you recommend?

A: The simplest and most widely used in-memory Key-value storage is MemcacheD. The introduction page re-iterates what you are asking for:

Memcached is an in-memory key-value store for small chunks of arbitrary data (strings, objects) from results of database calls, API calls, or page rendering.

The client list is impressive. It's been for a long time. Good documentation. It has API for almost every programming language. Horizontal scaling is pretty simple. As my experience goes Memcached is good.
You may also want to look into MemBase.

A: Redis is perfect for this kind of data. It also supports some fundamental datastructures and provides operations on them.
I recently converted my Django forum app to use it for all real-time/tracking data - it's so good to no longer have the icky feeling you get when you do this kind of stuff (SET views = views + 1 and other writes on every page view) with a relational database.
Here's an example of using Redis to store data required for user activity tracking, including keeping an ordered set of last seen users up to date, in Python:
def seen_user(user, doing, item=None):
    """
    Stores what a User was doing when they were last seen and updates
    their last seen time in the active users sorted set.
    """
    last_seen = int(time.mktime(datetime.datetime.now().timetuple()))
    redis.zadd(ACTIVE_USERS, user.pk, last_seen)
    redis.setnx(USER_USERNAME % user.pk, user.username)
    redis.set(USER_LAST_SEEN % user.pk, last_seen)
    if item:
        doing = '%s %s' % (
            doing, item.get_absolute_url(), escape(str(item)))
    redis.set(USER_DOING % user.pk, doing)

A: If you don't mind the sql but want to keep the db in memory, you might want to check out sqlite (see http://www.sqlite.org/inmemorydb.html).
If you don't want the sql and you really only have key-value pairs, why not just store them in a map / hash / associative array and be done with it?

A: If you end up needing an in-memory database, H2 is a very good option.

A: One more database to consider: Berkeley DB. Berkeley DB allows you to configure the database to be in-memory, on-disk or both. It supports both a key-value (NoSQL) and a SQL API. Berkeley DB is often used in combination with web applications because it's embedded, easily deployed (it deploys with your application), highly configurable and very reliable. There are several e-Retail web sites that rely on Berkeley DB for their e-Commerce applications, including Amazon.com.

A: I'm not sure this is what you are looking for but you should look into a caching framework (something that may be included in the tools you are using now). With a repository pattern you ask for the data, there you check if you have it in cache by key. I you don't, you fetch it from the database, if you do, you fetch it from the cache.
It will depend on what kind of data you are handling so it's up to you to decide how long to keep data in cache. Perhaps a sliding timeout is best as you'll keep the data as long as the  key keeps being request. Which means if the cache has data for a user, once the user goes away, the data will expire from the cache.

A: Can you shard this data? Is data access pattern simple and stable (does not change with changing business requirements)? How critical is this data (session context, for example, is not too hard to restore, whereas some preferences a user has entered on a settings page should not be lost)?
Typically, provided you can shard and your data access patterns are simple and do not mutate too much, you choose Redis. If you look for something more reliable and supporting more advanced data access patterns, Tarantool is a good option.

A: Please do check out this :
http://www.mongodb.org/
Its a really good No-SQL database with drivers and support for all major languages.


text:
Q: RegEx for selecting WORD when it's not between double-quotes What is the appropriate RegEx ( javascript ) for selecting 'and' when it's not between double-quotes.
like below:

def abc as "Hello and Welcome" and aaa as "Hi" and bbb as "and"

"and"s which are not included in double-quotes should be selected like below:

def abc as "Hello and Welcome" and aaa as "Hi" and bbb as "and"

Thank you

A: Try this it works like a charm
and(?=[^"]*("[^"]*"[^"]*)*$)
It assumes if there are pairs of double quotes after and then this and is not in double quotes.
For demonstration have a look here


text:
Q: What's the link between optimization and classification? I am learning about machine learning and one of the things that still not clear in my mind is how classification is done via optimization? In the couple of papers I read I just don't get how authors manage to model their problems, how does minimizing a function lead to clustering or classification, how do they know they are dealing with the right function?

A: Optimization in classification tasks
I would suggest to start to check the 0-1 loss, which is the goal of the classification task. In other words, the objective of the classifier is trying to classify objects "correctly" / minimizing the wrong classifications or 0-1 loss.
In real world problems 0-1 loss is hard to optimize directly, therefore there are other loss functions to "approximate" 0-1 loss. (A related discussion can be found here: What are the impacts of choosing different loss functions in classification to approximate 0-1 loss) Logistic loss is one of them. And the classifier based on logistic loss is logistic regression.

Optimization in clustering tasks
The goal of clustering is putting objects into groups/clusters. But what grouping strategy is good? This is the essential question answered by the optimization formulation.
In generally, we want objects in one group are "similar" to each other and between groups are "different". The optimization objective is trying to "maximize" the similarity within groups and "maximize" the difference between groups.

A: There is another, in my mind more intuitive way, of thinking about it:

*

*Optimization algorithms can be thought of as minimizing or maximizing an objective function.

*They can also be thought of as search algorithms: They search through a large space of possible values for the the best set of values.

If you think of optimization as search, then the connection between optimization and classification becomes clear: You are faced with a large space of possible models (as described by their parameters: NNet weights, Regression coefficients, etc....), and your optimization algorithm searches for the best model amongst all possible models.

A: Once you model your classification problem as assigning probabilities to each class (so regressing to a probability distribution over the classes) you can use cross-entropy as a loss function that when minimizing will try to get the probabilities closer to the actual class and further away from the wrong classes. In that regard, classification becomes an optimization problem. Non-gradient based methods could use other objectives. Tree based methods could look for splits that increase the accuracy most, in that regard you are optimizing accuracy.


text:
Q: I'm 27 years old with an Economics BA, is it too late for me to switch to Mathematics? The last 2 years have been very difficult for me, finishing with a very late BA in an area that I really don't like. I found a decent job in clinical trials as a data coordinator, but I was always fascinated with maths and found myself performing quite well in the classes that I managed to get accepted in during my BA (Multivariable Calculus, College Linear Algebra and Analysis). I have been thinking for the last year whether I want to pursue mathematics on a Graduate level (Ph.D and all), but since I turned 27 last month, I'm wondering whether it is already too late, and that I won't really be successful in the field.
Do you guys think that it is still a road worth taking? I was planning on accumulating more math courses at an undergrad level before taking on a Masters, then a PhD...which would take so much time it makes my head spin and scares me to no end.
Thank you.


text:
Q: Simple Differential Equations Question. The question reads:
Let $C_1$ and $C_2$ be arbitrary constants. For each of the following $y(x)$, find a differential equation that y satisfies, with the order of the ODE equal to the number of arbitrary constants in $y(x)$. The ODE should not contain any arbitrary constants.
(a)   $y(x) = cos(x) + C_1x^2$
Could someone explain what is really going on in this question because I can't seem to get the intuition behind it. Thanks in advance for your time and help.

A: If you had to do this with
(i) $y(x) = x + C_1$. Simply deriving $y$ makes $C_1$ disappear, answer would thus be : $y'(x) = 1$.
(ii) $y(x) = C_1 \exp( x)$, answer would be $y'/y = 1$. This time, $y'$ still contains $C_1$, so $y'=C_1 \exp(x)$ is not the answer. But $y'/y = 1$ which doesn't contain $C_1$, so this is a valid answer.
Does it help understand what is expected?

A: i this equation you got only 1 constant, therefor you need to build a first order O.D.E:
$y=cosx+C1x^2 $
so:$ y'=-sinx+2C1x$.
lets mult the second equation by $-0.5x$ to get:
$-0.5xy'=0.5xsinx-C1x^2 $.
adding both equation gives:
$y-0.5xy'=cosx+0.5xsinx$
the solution to this equation is (a).

A: The easiest way is to isolate the constant
$$ \frac{y-\cos x}{x^2} = C_1 $$
Then differentiate both sides
$$ \frac{x^2(y'+\sin x) - 2x(y-\cos x)}{x^4} = 0 $$
$$ \implies x^2(y'+\sin x) - 2x(y-\cos x) = 0 $$
This is your ODE.

A: Isolate the constant, for example with
$$\frac{y(x)}{x^2}=\frac{\cos x}{x^2}+C_1.$$
Then taking the derivative, you eliminate it.
$$\left(\frac{y(x)}{x^2}\right)'=\left(\frac{\cos x}{x^2}\right)'.$$
Now you can expand/reshape this equation (an ODE) the way you like. For example, the linear form
$$x^2y'(x)-2x\,y(x)=-x^2\sin x-2x\cos x.$$

Another example with two constants:
$$y=ax^b.$$
Isolate $a$ by taking the logarithm:
$$\log y=a+b\log x.$$
Differentiate:
$$\frac{y'}y=\frac bx.$$
Isolate $b$:
$$\frac{xy'}y=b.$$
Differentiate:
$$\left(\frac{xy'}y\right)'=0.$$


text:
Q: Exercise 5.14(d), chapter I in Hartshorne Let $f$ be an irreducible polynomial in $k[x,y]$ such that $P=(0,0)$ is a double point of $Y=Z(f)$, that is, $f=f_2+f_3+\cdots$, where $f_i$'s are homogeneous term of degree $i$, $f_2\neq0$, then we want to show that $k[[x,y]]/(f)\cong k[[x,y]]/(y^2-x^r)$ for some $r\geq 2$. (here char $k\neq2$).
If $f_2$ has two different linear factor, by a linear transform, then $k[[x,y]]/(f)\cong k[[x,y]]]/(xy)$. By a linear transform again, we have  $k[[x,y]]]/(xy)\cong k[[x,y]]/(y^2-x^2)$. Hence $k[[x,y]]]/(f)\cong k[[x,y]]/(y^2-x^2)$.
If $f_2$ has only one linear factor, by a linear transform, W.L.O.G., we can assume that $f_2=y^2$. Since $f$ is irreducible in $k[x,y]$, then there exists some $r\geq3$ such that $x^r$ appears in $f_r$, here we can assume that $r$ is the smallest such number. Now I want to find some automatism $\phi$ of $k[[x,y]]$ such that $\phi(y^2-x^r)=f$. But I got stuck.

A: Let's develop the discussion from the comments. Remember, we're trying to finish the solution in the case when $f_2=y^2$.

Weierstrass Preperation theorem (Bourbaki's Commutative Algebra, VII.3.8 prop 6): Let $A$ be a complete local ring. If $f=\sum_{n=0}^\infty a_nt^n \in A[[t]]$ so that not all $a_i$ are in the maximal ideal of $A$, there is a unique unit $u\in A[[t]]$ and a unique polynomial $F$ of the form $F=t^s+b_{s-1}t^{s-1}+\cdots+b_0$ with $b_i\in\mathfrak{m}$ so that $f=uF$.

We apply this with $A=k[[x]]$ and $y$ in the role of $t$. The conclusion of the theorem gives us that $f=u \cdot(y^2+y\cdot v(x)+ w(x))$. Next, as $\operatorname{char} k\neq 2$, we may substitute $y=y-\frac{1}{2}v(x)$, which takes $y^2+y\cdot v(x)+w(x)$ to $y^2-w'(x)$. By the assumption that $P$ is a double point, $w'(x)$ has valuation at least two. As $k$ is algebraically closed, we may scale $x$ so that $w'(x)=x^n(1+U(x))$ where $U(x)$ has no constant term. Then we may then use the fact that $\sqrt{1+x}=\sum_{i=0}^\infty \binom{1/2}{i}x^i$ is defined for any field of characteristic not two in order to construct the automorphism $y\mapsto y\cdot\sqrt{1+U(x)}$ and see that $k[[x,y]]/(y^2-w'(x))\cong k[[x,y]]/(y^2-x^n)$ for $n>2$. (Thanks to kindasorta for pointing out the step involving $\sqrt{1+x}$.) By the uniqueness of $u$ and $F$ from the theorem, the uniqueness of the substituiont $y=y-\frac12v(x)$, and the fact that all further transformations don't change the order of the power series in $x$, we see that $n$ is uniquely determined.


text:
Q: How to automatically shutdown laptop if unplugged I want my laptop to shutdown automatically after it gets disconnected from power. Can someone tell me if there exists some app for this for Windows 7

A:

*

*Type "Power Options" in Start Menu search text field and hit enter key.

*Click on "Change Plan Settings" in front of active plan (Balanced, High Performance or Power Saver).

*Click on "Change advanced power settings".

*In the next window scroll down and find the "Battery" option, Expand it.

*Expand "Low battery Level" and change the "on battery" value a high value e.g 95%.

*Expand the "Low battery action" and change the "on battery" option to Shutdown.

Source

A:
For those of you having the problem of a HP laptop shutting off when you unplug the charger and your battery is fully charged, I can help you. There is nothing wrong with the laptop, battery, or computer, it is a power management setting. If you go to display properties, select the screen saver tab, then click the "power" button, in the power schemes field is a drop down window, click on it and select "Rixane Power Scheme", it is a power switching utility that quickly switches between AC and Battery when the power cable/charger is plugged in or unplugged while the laptop is on. If you have it set to "always on" it will shut off when you pull the power cord, even if the battery is charged. This will also happen on many non-HP laptops, if you don't have a HP laptop or there is not a "Rixane" option available, select the "Portable/Laptop" power scheme. Hope this helps!

Source: Click Here


text:
Q: NSFetchedResultsController pushes updates without having pushed any inserts I have a NSFetchedResultsController initialized like so:
  lazy var postsResultsController: NSFetchedResultsController = {
    // Initialize Fetch Request
    let fetchRequest = NSFetchRequest(entityName: "Post")

    // Add Sort Descriptors
    let sortDescriptor = NSSortDescriptor(key: "creationDate", ascending: false)
    let predicate = NSPredicate(format: "owner == %@" , "owner",self.user)
    fetchRequest.sortDescriptors = [sortDescriptor]

    // Initialize Fetched Results Controller
    let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: StateControl.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)

    // Configure Fetched Results Controller
    fetchedResultsController.delegate = self

    return fetchedResultsController
  }()

and I set my controller as the delegate. Here is an overview of the delegate methods:
  func controllerWillChangeContent(controller: NSFetchedResultsController) {
    NSLog("Begin updates")
    userPosts.beginUpdates()
  }

  func controllerDidChangeContent(controller: NSFetchedResultsController) {
    NSLog("End updates")
    userPosts.endUpdates()
  }

  func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {

    switch (type) {
    case .Insert:
      if let indexPath = newIndexPath {
        userPosts.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Left)
      }
    case .Delete:
      if let indexPath = indexPath {
        userPosts.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Left)
      }
    case .Update:
      print("Update request")
      if let indexPath = indexPath {
        userPosts.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
      }
    case .Move:
      if let indexPath = indexPath {
        userPosts.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
      }

      if let newIndexPath = newIndexPath {
        userPosts.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
      }
    }
  }

And below you see my UITableViewDataSource delegate methods:
  func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return postsResultsController.sections?.count ?? 0
  }

  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let sections = postsResultsController.sections {
      let sectionInfo = sections[section]
      return sectionInfo.numberOfObjects
    }
    else {return 0}
  }

  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let post = postsResultsController.objectAtIndexPath(indexPath) as! Post
    let cell = tableView.dequeueReusableCellWithIdentifier(ReuseIdentifiers.PostCollectionViewCell, forIndexPath: indexPath) as! PostCell
    cell.setup(withPost: post, fromUser: user)
    return cell
  }

I set myself as the delegate in my tableView's didSet:
var userPosts: PostsTableView! {
    didSet {
      userPosts.delegate = self
      userPosts.dataSource = self
      userPosts.scrollEnabled = false
    }
  }

However, when I arrive to viewDidLoad:, I do the following:
do {
  try self.postsResultsController.performFetch()
} catch {
  let fetchError = error as NSError
  print("\(fetchError), \(fetchError.userInfo)")
}
userPosts.reloadData()

And yet, my tableView remains completely empty. What I have noticed is that my log shows that userPostsController is pushing update requests but no inserts.
2016-02-29 15:31:52.073 Columize[10373:149421] Begin updates
Update request
2016-02-29 15:31:52.073 Columize[10373:149421] End updates
2016-02-29 15:31:52.074 Columize[10373:149421] Begin updates
Update request
2016-02-29 15:31:52.074 Columize[10373:149421] End updates

So, my best guess is that the NSFetchedResultsController just watches the context and passes on updates (I do a lot of fetching from backend that merge with existing objects, hence the many updates), but it was my understanding that every time I create a new NSFecthedResultsController it would populate and pass on the appropriate delegate calls (mainly inserts).
Furthermore, I'm assuming that means that after a NSManagedObjectContext has interacted with a NSFecthedResultsController, subsequent NSFecthedResultsControllers simply don't push Inserts.
1-Is my reasoning correct?
2-How can I circumvent that? Do I have to create a new context for every NSFecthedResultsController?
UPDATE
So the reason nothing was showing was because my tableView had height of zero (wooops). However nothing will appear if I don't call reloadData after the first fetch, so my question stands, namely, why aren't there any inserts performed by my NSFetchedResultsController?


text:
Q: Caliburn.Micro TryClose closes every window I have the following scenario:

*

*There is a login screen

*When the login is successful, it should close the login screen and start a new screen

I use this code in the Bootstrapper:
public class AppBootstrapper : BootstrapperBase
  {
    public AppBootstrapper()
    {
      Initialize();
    }

    private IWindowManager windowManager = new WindowManager();
    private MainViewModel mainViewModel = new MainViewModel();

    protected override void OnStartup(object sender, System.Windows.StartupEventArgs e)
    {
      Init(new LoginViewModel());
    }

    public void Init(object viewModel)
    {
      windowManager.ShowWindow(viewModel);
    }
    public void Init2()
    {
      windowManager.ShowWindow(mainViewModel);
    }
}

This is my App.xaml.cs:
public partial class App : Application
    {
        public static AppBootstrapper Bootstrapper;

        protected override void OnStartup(StartupEventArgs e)
        {
            Bootstrapper = new AppBootstrapper();
            base.OnStartup(e);
        }
    }

This is the method from Login viewmodel:
public class LoginViewModel: Screen
{
     public void DoLogin()
        {

          if (LoginSuccessful)
          {
            App.Bootstrapper.Init2();
            TryClose();
          }
       }
}

When TryClose is used, the second window is also closed and my application exits.
Why does it happen? How should I prevent it?

A: Checked your code. At this point all I see is that TryClose causes an exception
Cannot set Visibility or call Show, ShowDialog, or WindowInteropHelper.EnsureHandle after a Window has closed.

It seems that Caliburn or even System.Windows.Navigation somehow under the hood goes to a different thread (I see that ManagedThreadId at constructor of MainViewModel differs from ManagedThreadId where Init2 was called).
If you change your code to this one, then all performed as intended (that is not quite perfect solution, just showing that it might work in some conditions)
App.Bootstrapper.Init2();
Task.Factory.StartNew(() => { TryClose(); });

I don't think that it is a good practice to close last available window while trying to show another one. Just use some shell (even hide it if you dont want to see it at first place). And move there all your calls to WindowManager or/and ActivateItem if you would use Conductor inheritance. So you'll never be in such situation because you'll have at least one part of application on background, that would terminate only when you need it and not by accident.


text:
Q: Why can't I call the reducer directly? I read some introduction blog post on redux and its priciples. I still don't know why the reducer should not be called directly, but by calling an action function with data in the parameter. What is the advantage?
action
export function setPerson(personData) {
  return {
   type: actionTypes.SET_PERSON,
   personData
  };
}

A: Several reasons:

*

*The current state value is kept inside the store, so it can only be updated by running the reducer.  The reducer can only be run by calling store.dispatch().  So, part of the answer is "that's how it's designed to work".

*The "Flux Architecture" introduced the idea of plain object actions, and Redux was designed to be an implementation of the Flux Architecture.

*Plain object actions enable many key features of Redux:

*

*A history log of events that occurred over time, and how those events correlate to state changes

*Enabling time-travel debugging, in the form of changing the sequence of dispatched actions

*Allowing middleware to interact with the actions as they are dispatched, enabling logging, modification of actions, and other centralized behavior

*Enabling serialization and persistence of behavior, such as synchronizing multiple stores across a network.


text:
Q: Sorting GeoJSON features array by property value I am looking to sort a GeoJSON file on a property so I can then slice it keeping only the top 5 features. For example, I wish to take this GeoJSON and sort the file in descending order by the incidents property:
{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "MultiPolygon",
        "coordinates": [
          [
            [
              [
                -75.1972382872565,
                39.9294288475177
              ],
              [
    ...
         [
                    -75.1972382872565,
                    39.9294288475177
                  ]
                ]
              ]
            ]
          },
          "properties": {
            "area": "",
            "location": "24th St. & Wolf St.",
            "perimeter": "81903.64182498",
            "dist_numc": "01",
            "sum_area": "",
            "area_sqmi": "216350124.153",
            "district_i": "",
            "objectid": "321",
            "globalid": "c040618c-ac93-4b22-b174-0ea08e0f805d",
            "district_": "1",
            "_feature_id": "1",
            "_feature_id_string": "Police_Districts.1",
            "dist_num": "1",
            "div_code": "SPD",
            "phone": "686-3010",
            "incidents": 11553
          }
        },
    ...

I'm looking to basically rearrange the order of the features array so that it's in descending order and the highest incident features are first.
How would I go about this?
I am used to creating a compare function and then sorting an array with something like this:
//FUNCTION: SORT
 export const compare = ( a, b ) => {
    if ( a.incidents < b.incidents ){
      return -1;
    }
    if ( a.incidents > b.incidents ){
      return 1;
    }
    return 0;
  }

But in this case I need to sort a JSON and only sort an array inside of it so I am unsure how to proceed.

A: As .geojson is a javascript object, apply Array.prototype.sort() on feature, as follow:
const sortArrayofObjects = (property, order) => {
  var sortOrder = order === 'asc' ? 1 : -1;
  return function (a, b) {
      var result = (a['properties'][property] < b['properties'][property]) ? -1 : (a['properties'][property] > b['properties'][property]) ? 1 : 0;
      return result * sortOrder;
  }
};

const rearrangedFeatures = geojson['features'].sort(sortArrayofDicts('property_name', 'asc')) //ascending

This function sorts the array of features based on feature's property in a descending way. If you want an ascending method, use asc as the second argument.
Finally update .geojson.


text:
Q: Infinite dimensional euclidian space with the product topology metrizable? Let $\mathbb{R}^{\omega}$ be the space of real sequenes with the product topology.
Is $\mathbb{R}^{\omega}$ metrizable?

A: Hint: As $\mathbb{R}$ is homeomorphic to $(0 , 2^{-n} )$ for all $n \geq 1$, it follows that $\mathbb{R}^\omega$ (with the product topology) would be homoemorphic to $Y =\prod_{i=1}^\infty ( 0 , 2^{-n} )$.  Can you think of a natural candidate for a metric on $Y$?


text:
Q: DataTables - I don't want the search/filter and length options on some tables How do I initialise specific tables without the search filter and length select menu?
Apparently it can be done with the sDom option, but the documentation is pretty bad and I can't understand exactly what I am supposed to do.
http://datatables.net/usage/options#sDom

A: You can set to false such properties during initialization of datatable:
"bFilter" : false,
"bLengthChange": false

A: Without search filter and length
var options = {"sDom": 'rtip'}
var myDataTable = $('#myDataTable')
myDataTable.dataTable(options)

Here is an example from the official documentation: https://datatables.net/examples/basic_init/dom.html

A: I agree that sDom is tricky, I got the hang of it by practicing. Run the example below and see the "info" will appear in the top.  Replace sDom with "sDom": 'rtlp' and see info disappear.  Now use "sDom": 'rtil' and see info is back at the bottom, but paging is gone.  Keep experimenting and you will get it.
<!DOCTYPE html>

    <link href="demo_table.css" rel="stylesheet">

            Rendering engine
            Browser
            Platform(s)
            Engine version
            CSS grade

A: Since Datatables 1.10 you can use those 2 options :

*

*lengthChange
"lengthChange": false

*searching
"searching": false
Full example :
$('#example').dataTable( {
  "lengthChange": false,
  "searching": false
} );


text:
Q: Render image from ftp server blackberry smartphone client side application I want to display an image from following url using ftp protocol.
ftp://64.207.150.31:21/images/gobali.jpg

The above url have following pattern when we use in app.
ftp://user:password@host:port/path

user: remote
password: 123456789


text:
Q: Codeigniter helpers work locally but not on server I'm doing a simple
$this->load->helper('email');
sendEmail();

and it loads on my local machine that is running php 5.5.12 however on my webserver that is running php 5.4.16 I get
Fatal error: Call to undefined function sendEmail()

Is this a php version issue? Or could it be something else? Everywhere I've read I don't see any issues with running codeigniter on 5.4.16

A: Codeigniter 3 has built-in email helper it is deprecated and is currently only kept for backwards compatibility so CI loads own helper before then yours.
In fact, CI email helper has not a function sendEmail() so you get an error.
You should delete built-in email helper or change your helper name.
CI email helper documentation


text:
Q: ASP.NET behaving strangely with Javascript I'm trying to modify displays and checkboxes from asp.net controls using javascript, cuz the updatepanel is just pure rubbish. But for some absurd reason, this works:
document.getElementById('ctl00_ctl00_MainContainer_WorkContainer_AppointmentFormView_RecurringRow').setAttribute('style', 'display: none');

and this does not:
document.getElementById('ctl00_ctl00_MainContainer_WorkContainer_AppointmentFormView_RecurringRow').style.display = 'none';

if i actually do it the second way, and i debug the value on display, it actually says none, but it's still visible in my UI. Weird stuff...
The same goes with the checked value, if I set this:
document.getElementById('ctl00_ctl00_MainContainer_WorkContainer_AppointmentFormView_Monday').checked = false;

it just doesn't work, the only work around for this is to see if the value is actually checked and then click it, like this:
if (document.getElementById('ctl00_ctl00_MainContainer_WorkContainer_AppointmentFormView_Monday').checked) {
                    document.getElementById('ctl00_ctl00_MainContainer_WorkContainer_AppointmentFormView_Monday').click();
                }

Any ideas of what i need to double check? because this is just not making any sense to me :)

A: change all the above like this
document.getElementById('<% AppointmentFormView_RecurringRow.ClientID %>').setAttribute('style', 'display: none');
  document.getElementById('<% AppointmentFormView_RecurringRow.ClientID %>').style.display = 'none';
document.getElementById('<% AppointmentFormView_Monday.ClientID %>').checked = false;
if(document.getElementById('<%AppointmentFormView_Monday.ClientID%>').checked) {
                document.getElementById('<%AppointmentFormView_Monday.ClientID%>').click();
            }


text:
Q: Replace original record with another on during After / Before Insert Imagine the user clicks a standard New button of a custom objects, populates some fields (in a Standard Layout) and then clicks save.
He then is redirected to the View page of this new record, but is many fields and related lists a populates with values and child records from a hidden template inside the app.
This all would be easy if the structure I am going to deserialize would be stand alone and not dependand on a parent record NOT part of the template.
I therefore required the user to manually populate a parent lookup field and the want to do this in the Before or Aftert Insert trigger:

*

*Get the lookup value from the user's record (temporary)

*Deserialize the serialized record (real) using the lookup value

*Delete the users record

Now my question: How can a trigger cancel inserting the original record and instead insert and redirect to another?

A: Records cannot be removed from a trigger context collection, as it is immutable.
You are going to need to implement a VisualForce workaround to get the functonality you desire. You will then want to use this Page to override the New action on your object.


text:
Q: start-stop-daemon: failed to start `/usr/bin/mongod' I have an alpine machine on my virtual machine and I want to install mongodb. I added the package for mongodb using "apk add mongodb". I started mongo daemon using command mongod in one terminal. Then opened another terminal with mongo shell using mongo --disableJavaScriptJIT. I tried adding files and reading them from the database and that worked fine. But when I do  sudo service mongodb restart  I got the following output.
     * Caching service dependencies ...                                       [ ok ]
     * Starting mongodb ...
     * start-stop-daemon: failed to start `/usr/bin/mongod'                   [ !! ]
     * ERROR: mongodb failed to start

A: The first thing you should do is to read the log file. I think that you'll read here that mongodb doesn't have rights to access some files. When you started it manually, you haven't run it as user mongodb, have you…?
If this hypothesis is right, then the solution is to fix owner (and group) of the /var/lib/mongodb (recursively).


text:
Q: ¿como traer registros de una tabla bajo estas condiciones, con eloquent? laravel 8 tengo 2 tablas, products y notifications, en la tabla notifications hay una columna llamada data, donde guardo en formato json todos los datos de un producto y le agrego un campo llamado type.
ejemplo
{"id":2,"code":"12","name":"caja de bombones","due_date":"2021-11-04","type":"stock","days":"30","description":"qwqq"}

Con el siguiente código se verifica los id de productos que no estén en el campo data
Product::select('products.*', 'notifications.data->id AS jsonidproduct')
 ->leftJoin('notifications','products.id','=','notifications.data->id')
 ->whereNull('notifications.data->id')
 ->orderBy('products.id')
 ->get();

Pero ya no necesito consultar solo los productos que no estén en el campo data, necesito verificar que si no hay un registro con el id de un producto en el campo data me traiga la información de ese producto, pero que si hay un registro con el id de un producto en el campo data no sea con el type ='stock', básicamente es: si un producto no está registrado me traiga ese producto, si un producto está registrado en el campo data con el type = 'stock' que no traiga ese producto, pero si esta registrado con el type = 'fecha' o cualquier otro si lo traiga.
Intenté cambiando el whereNull por solo un where pero no sigue la lógica que necesito, no me trae nada
Product::select('products.*', 'notifications.data->id','notifications.data->type')
 ->leftJoin('notifications','products.id','=','notifications.data->id')
 ->where('notifications.data->type','!=','stock')
 ->orderBy('products.id')
 ->get();


text:
Q: My site, its getting clipped i've made this website, it has a viewport
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=no; target-densityDpi=device-dpi" />

it is still being partially viewed or clipped i guess if i try to view it through a CRT monitor at 800x600 desktop resolution or anything less than 1280x800, even mobile, can i make the site not clip or atleast make it horizontally scrolable but not clipped like it is right now? I guess the issue is with its wrapper, Any solution?
the site : http://techarx.com/
I hope i am safe with this.

A: Your problem is in the css. You currently have:
.page-wrapper {
    width: 80%;
}
#page {
    width: 1100px;
}

So when 80% of the window is less than 1100px things get cut off.
The quickest way to fix this would be:
.page-wrapper {
    width: 80%;
    min-width: 1100px;
}
#page {
    width: 1100px;
}

You could also make your #page div narrower, or make it width: 100%, but then you also need to adjust the inner columns.


text:
Q: PCA and Hotelling's T^2 for confidence intervall in R I made a principal component analysis and took the 2 first principal components. I made a chart of my points based on the score of the 2 PC. I would like to add on this graph a  95% confidence region corresponding to the Hotelling's T^2 test in order to detect the points that are out of the ellipse (outliers)
How is it possible in R?
Do you have any example?
I would do something like this and detect the points out of the ellipse:

A: We can plot the confidence ellipse for PCA with vegan or ggbiplot as below:
set.seed(1)
data <- matrix(rnorm(500), ncol=5) # some random data
data <- setNames(as.data.frame(rbind(data, matrix(runif(25, 5, 10), ncol=5))), LETTERS[1:5]) # add some outliers
class <- sample(c(0,3,6,8), 105, replace=TRUE) # 4 groups

library(vegan)
PC <- rda(data, scale=TRUE)
pca_scores <- scores(PC, choices=c(1,2))
plot(pca_scores$sites[,1], pca_scores$sites[,2],
     pch=class, col=class, xlim=c(-2,2), ylim=c(-2,2))
arrows(0,0,pca_scores$species[,1],pca_scores$species[,2],lwd=1,length=0.2)
ordiellipse(PC,class,conf=0.95)

library(ggbiplot)
PC <- prcomp(data, scale = TRUE)
ggbiplot(PC, obs.scale = 1, var.scale = 1, groups = as.factor(class), ellipse = TRUE,
                                                    ellipse.prob = 0.95)

A: The pcaMethods package has a function simpleEllipse(x, y, alpha, len) that will do this. Given two uncorrelated data vectors it will return an ellipse, where the axes are scaled based on the variance of each score, and the F statistic.


text:
Q: UINavigationController suggestion I have read that UINavigationController are best option when you want to jump from n number of screen to first screen. It takes following  code to do so:
NSMutableArray *array=[[NSMutableArray alloc]initWithArray:self.navigationController.viewController];
[array removeObjectAtIndex:1];
[array removeObjectAtIndex:1];
[array removeObjectAtIndex:1];
self.navigationController.ViewController=array;
[self.navigationController popViewController:YES];

by using this code I can go directly from fourth screen to first screen directly .
If I don't using navigation controller then also by making the object of firstSCreen in fourth screen I can achieve the same thing within couple of lines.Then why one should go for navigation controller? If answer is for memory optimization then we are autoreleasing the the object of firstViewController and now we are using auto referencing.

A: first thing this is wrong approach to pop. true one is
[self.navigationController popToRootViewController:YES];

and second thing is that if you are at 4 screen, then by poping to a specific viewcontroller will no pop all screens. here is memory issue.
another issue is that some times you don't want to lose parent screens data. if you use method of pop to specific viewcontroller, the data will be lost as the object having data is released. you made a new one.
point is that this depends on your conditions what is suit able in your scenario. but the normal and usual approach is that don't use specific popout techniqu as it may cause problems

A: You can use
[self.navigationController popToViewController:(UIViewController *) animated:(BOOL)];
You just need to pass ViewController's object on which you want to move directly... And between view controller's will pop-out automatically
Hope this helps you...

A: agreed with 'The Saad'
one more thing is that if you have various screens with the data coming from server.
it will be quite difficult to render(user interection) screen second while loding data on first.
same with all other sibling views.


text:
Q: Convert cv::mat to string of bytes in OpenCV I need to implement a function which takes an image and return a file say a text file containing a string of bytes.
What I have done yet is :
#include <cv.h>
#include <highgui.h>
using namespace cv;

int main( int argc, char** argv )
{
cv::Mat image;
image = cv::imread("imaje.bmp");
if(image.empty())
return 0;

cv::imshow("Image", image);
cv::waitKey();

return 0;
}

Now I need to convert tha cv:Mat image to an array of bytes. Please guide me how to proceed???
Thanks in advance ... :)

A: I know, it's a bit late to answer... but it may be useful for other people.
You can convert your cv::Mat to a string by doing std::string my_cv_mat(src.begin<unsigned char>(), src.end<unsigned char>());
Then you can get a char* using the .c_str() method of the string. As char and byte have the same size I guess that you just have to cast the char* to byte*.


text:
Q: "tcsetattr(): Inappropriate ioctl for device" when redirecting output to console When redirecting stdout and stderr to a console, I'm getting(?):

tcsetattr(): Inappropriate ioctl for device
tcesetattr ICANON: Inappropriate ioctl for device
tcsetattr ~ICANON: Inappropriate ioctl for device

using: ${DTNG_EXEC} ${DTNG_LOG_FILE} > /dev/tty2 2>&1

I've tried writing other example shell scripts and C/C++ programs to simplify the actual code and script BUT to no avail. All the examples work as expected ... writing stdout and stderr to the console without error.

BTW, I searched on tcesetattr and found naught.  It defaulted to tcsetattr.


text:
Q: IBM Process Center user roles for deploy only I'm new in IBM Process Center (BAW 19.0.0.3).
We have DEV env (Process Center PC) and PROD env (Process Server PS). PS will be connected to the PC for fast deploy snapshots from DEV to PROD.
I'm trying to understand how to create two users using external LDAP (as example): 1st user like developer only (has no grants for deploy snapshot to PROD env) and the 2nd user with deploy only grants (like Project Deployer user).
I know about two adminstrave groups (tw_admins and tw_authors), but I can't understood how it works. Users in tw_authors can delpoy snapshots to Process Server. I have no idea how to create this user with deploy only grants.
Thanks


text:
Q: The relation between In-App strings and ASO (App stores Optimization) My question: Do Google play and/or Apple App store use the in-app strings when users searching for an app on the app store?
Can I programmatically add keywords in my app? Is there any documentation about this?
Clarification
Because some of you tried to close this question: I am looking for an answer that related to coding not store listing. Something that can only be done by a mobile developer not a marketing guy. here is an example of what I am looking for.

A: I don't have a confident answer but I don't think that this type of string matters to ASO. These texts are packaged into the APK/AAB and depend on the localization you are targeting. You could also minify the resources so it won't be an easy task to use them for ASO.
The link you mention is related to exposing intents so the app could be launched from any other place. I think that you could use something like this if you are using some keywords inside the deeplink but it will be more focused on SEO than on ASO.
Disclaimer: As I said, it is just my thought about it and I don't have any proof.
Hope it helps.


text:
Q: Domain name: REDEMPTIONPERIOD There's a domain name I'm willing to register which has Expiration Date: 30-Oct-2009 and Status:REDEMPTIONPERIOD.
Shouldn't it have been already released? Should I just wait or is there anything I could do about this?

A:
Shouldn't it have been already released?

Not necessarily. Procedures vary greatly from registrar to registrar, but domains can often remain registered, in a 'suspended' state for weeks or months after they were due to expire. Their name server information is usually removed, to prevent the domain being routable, but the domain is 'locked', allowing the original owner to pay the fee and claim it again within the grace period offered by the registrar.
If the domain name you're after will prove to be a popular one when it is eventually deleted and released back to the pool of available domains, you'd want to use a service which will automatically purchase it once this happens. Popular, recently expired domains are often monitored by those most interested in the market, so it could be deleted and re-registered very quickly. Procedures vary depending on the registrar as to when the domain will be released back to the available domains pool.
Have a look at this site about expired domains for some more info on these 'deleted domain' services.
You might also consider enquiring with the domain's registrar to determine their procedures for expired domains, and don't forget, the original owner could still re-claim the domain during their grace period!

A: What is RedemptionPeriod?
Basically, the Registrar is just holding on to the domain name for whatever reasons. However, some Registrars abuse the system, apparently. They use this mechanism to hold on to the more popular domain names, in the hopes that someone will offer an above-average fee for the domain. There is a chance that the current Registrar is just reserving the domain for some other usage. Why they would do this, I don't know. Possibly they've linked it to an advertisement page which still gets a lot of hits, thus it generates additional income for them while it's having this status.


text:
Q: A phrase as catchy as 'Feature Creep' but for underestimated projects I'm needing a term or established term to represent a phenomenon our company currently calls a 'Black Hole': a project that takes magnitudes longer than estimated, yet we're already sucked in and HAVE to see it through to completion.
EDIT:
Hoping that the best term will be voted up.

A: I would say "Underscoped".
I am involved with an underscoped project at the moment.

A: I believe the term you are looking for is Death March, though I suppose it doesn't really apply if the project is ultimately successful.

A: "Scope creep" is the phrase I've used.

A: I once interviewed for a position on what had to be the ultimate Death March project. I was at Lockheed Martin at the time. Here's what I discovered at the interview:

*

*The project was almost entirely staffed by engineers pulled off of the layoff list. Pretty much the dregs of the company.

*They were using castoff equipment from the rest of the company for their software development.

*15 hours a week of overtime was mandatory, and would be for the foreseeable future.

*They didn't even have cubicles. Everyone worked in one great big open bullpen with wires strung everywhere.

*They had attempted to deliver this project once before, but the customer rejected it and made them try again.

*They were so far over budget and so late that nobody was even bothering to track it anymore.

*They wanted to cancel the project, but their customer was the government of Egypt and they were threatening to stop a large order of F-15s until this project was delivered. (The project had nothing whatsoever to do with F-15s). So now they were getting pressure to finish from the Chairman of Lockheed Martin on down.

*Engineers visiting the customer site in Egypt had come down with nasty staph infections. One had to be medevacted out to Europe.

I swear I practically ran from the room.

A: Since hours are often associated with cost, perhaps the term you seek is Cost Overrun?
I also like the concept of Optimism Bias as the reason for under estimating.

A: I remember 'logic bombs' applied to compressed files. Mainly, create a (back then, several gigs) file containing only one symbol repeated over and over. Zip the file (will become tiny). Send to user -> balloon effect.
Perhaps balloon project?
Murphy's Project?

A: Spike may be useful in trying to get these under control but it isn't quite what you want.


text:
Q: How to read input line by line, instead of by spacing I'm trying to read a large number of user inputs line by line instead of by spacing.
code:
keyword = (input("\n Please enter the keywords "))
keywords = keyword.split(" ")

words:
a
abandon
ability
able
abortion

A: The input function ends by pressing enter or moving to a new line, so you have to define how you want to finish instead.
If you're looking for a way to enter 5 words like you did in your example, this should be enough:
print("\n Please enter the keywords ")
keywords = [input() for i in range(5)]

You can change range(5) to range(3000) or any other number that you wish.
If you would like in input an infinite amount of words until some special keyword is entered (like "quit") you can do this:
print("\n Please enter the keywords ")
keywords = []
while True:
    k = input()
    if k == 'quit':
        break
    else:
        keywords.append(k)

A: You may want to read from the sys.stdin, for example:
import sys

it = iter(sys.stdin)
while True:
  print(next(it))

Here you have a live example


text:
Q: Rotation of marker over google map with animation like Uber or Ola in React Native I am working on a project similar to UBER or OLA. I have used react-native-maps library for that. I have used React Native geolocation to fetch the current location. I have also taken a reference to this react-native-maps example. but the rotation of the marker is not working. can anyone help? where am I wrong?
And This code works well in Android, But not in iOS
Thanks in advance.
Below I share my code
render(){
     return(
           <MapView
              ref={component => (this.map = component)}
              provider={PROVIDER_GOOGLE}
              style={styles.mapStyle}
            >

              <Marker. Animated
                coordinate={{
                  latitude: this.state.currentLocation.latitude,
                  longitude: this.state.currentLocation.longitude
                }}
                ref={marker => {
                  this.marker = marker;
                }}
                flat
                style={{
                  transform: [
                    {
                      rotate:
                        this.state.currentLocation.heading ===
                   undefined
                          ? "0deg"
                          : `${this.state.currentLocation.heading}deg`
                    }
                  ]
                }}
                image={"rickshaw"}
              />
)}

And I have updated marker location in componentDidUpdate
 componentDidUpdate(prevProps, prevState) {
    if (prevState.currentLocation !== this.state.currentLocation) {
      let newCoordinate = this.state.currentLocation;
      let previousLocation = prevState.currentLocation;
      if (utility.getOS() === "android") {
        console.log("update marker");
        if (this.marker) {
          this.marker._component.animateMarkerToCoordinate(
            this.state.currentLocation,
            1000
          );
        }
      } else {
        if (newCoordinate !== null && previousLocation !== null) {
          const oldCoordinate = new AnimatedRegion({
            latitude: previousLocation.latitude,
            longitude: previousLocation.longitude
          });
          oldCoordinate.timing(newCoordinate).start();
        }
      }
    }
  }


text:
Q: merging two git remote repositories locally I want to make use of this feature -- https://github.com/xetorthio/jedis/pull/160. Although this issue has been closed, it has not been merged with the master. Is it possible to clone the master on my local machine and merge pull request #160 on my local copy? If so, how can I do it?
Master branch is https://github.com/xetorthio/jedis
Thank you.

A: I see you've accepted VonC's answer, but you can do it this way, too. It's a little bit faster.
From: http://help.github.com/send-pull-requests/

Every pull request has a .patch URL where you can grab a textual patch file to feed into the git-am command:

In your case you can go like this:
$ git clone https://github.com/xetorthio/jedis.git
$ curl https://github.com/xetorthio/jedis/pull/160.patch | git am

A: First, keep in mind that this pull request has been closed because:

Thanks a lot for this pull request but this will be fixed by adding overloads with Strings which will fix also issue #74

So your merge might come in conflict with a future patch which will be merged to master.
That being said, a pull request is a patch, so you can view it as a diff (select diff button on the pull request page), copy those diffs in a patch file, and apply it to your local repo (as in "How to apply git diff patch?")


text:
Q: How to determine original vs. reply emails with mail flow rules? Using Exchange via Office365. My organization would like to write mail flow rules on the condition that the email is or is not a reply. All original//initiating emails would get one rule, all replies//responses get another. There doesn't seem to be a way to do this natively (at least I can't find it) -- but did someone find a workaround that has the same effect?

A: Only got voted down here, which is disappointing. I looked all over the bloody internet and found no good answers to this question. Many folks said this could not be done without a third-party tool. But I did come up with something to suit my needs, so I'm posting it here so it's Google-able for the next lost soul:
In order to group email conversations into chains, Exchange injects a bit of metadata into email message headers. The following instructions will create a mail flow rule to check for a value matching a regex expression in that metadata. If Exchange can't find anything, the rule will kick off as normal, but if it does find a value, the email must be a reply and therefore the mail flow rule will not fire.
For a mail flow rule that only should run on an initial email, not a reply:

*

*From Admin -> Exchange -> Mail Flow -> Your Rule, provide a name, conditions, and actions as normal.

*Click "More options..." near the bottom if this has not already been selected.

*Click "Add Exception."

*Under "Except if...", select "A message header matches these text patterns."

*Click "Enter text..." and enter a header name of "In-Reply-To" (no quotes).

*Click "Enter text patterns..." and enter this expression: "<.@.>" (no quotes).

*Save your rule as normal.

Hope this helps someone.


text:
Q: Generically draw shapes on a canvas through a single collection I'm tying to generically draw an ObservableCollection of System.Windows.Shapes.Shape on a canvas using an ItemsControl but I am not sure about how to write the XAML to do it properly.
I've seen many posts regarding this topic, but they all seem to be tied to specific shape types.  For example, from this example I realize I could  define an ItemsContainer and set its template to draw lines, circles, etc.
<ItemsControl ItemsSource="{Binding Lines}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Line X1="{Binding From.X}" Y1="{Binding From.Y}"
                  X2="{Binding To.X}" Y2="{Binding To.Y}"
                  Stroke="DarkGray" StrokeThickness="3"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

But this requires me to expose my shapes as separately typed collections of lines, circles, etc.  -- or at least write some sort of filtering properties that do that.  I was hoping to just expose just one collection of shapes.  (I will be adding new shape types later on and don't want to have to keep adding new collection properties)

*

*Is there a simple, "best" approach I can take to achieve this without exposing separate collection types?

*Should I be looking at ItemTemplateSelector?  It seems to me that would have the same problem of needing specific shape types.

*Some other approach?


text:
Q: SQL using while loop to calculate values for multiple elements I am trying to calculate an average daily stock of each item in a warehouse using Ms SQL.
Every incoming and outgoing quantity is recorded in the same column, let's name it [quantity]. Due to this structure the only way for me to tell the stock level for today is to simply sum all of the quantity from the beginning of time.
i.e.
SELECT [item], SUM(quantity)
FROM item_table

If I want to see the stock level of yesterday I would need to following code:
SELECT [item], SUM(quantity)
FROM item_table
WHERE [date] < DATEADD(day,-1,GETDATE())

And so on for every single day. Of course I'm not going to go through the trouble of manually changing the DATEADD number 360 times in order to get the stock level for the entire year. Hence I am using a While loop as follows:
DECLARE @intFlag INT
DECLARE @s DECIMAL = 0
DECLARE @i varchar(20) --replaced with table (see table part below)
SET @intFlag = 0
WHILE (@intFlag <= 360)
BEGIN
SET @intFlag = @intFlag + 1
SET @i = (SELECT TOP (1) [item] FROM item_table ) --replaced with table (see table part below)
SET @s = (
        SELECT
            SUM(quantity) + @s AS inventory
        FROM item_table
        WHERE
        item IN (@i) --replaced with table (see table part below)
        AND [Date] < dateadd(day, - @intFlag, GETDATE())
        )
IF @intFlag = 360
    BREAK;
END

SELECT
@i AS [item],
@s/360 AS [AVG_stock]

This is working properly so far, but I'm stuck when trying to do the same operation for multiple items.
When I try replacing the @i parameter with a table like this:
DECLARE @items table (number varchar (20))
INSERT INTO @items
SELECT DISTINCT [Item]
FROM items_table

And try to call it in
SET @s = (
        SELECT
            SUM(quantity) + @s AS inventory
        FROM item_table
        WHERE
        item IN (@items)
        AND [Date] < dateadd(day, - @intFlag, GETDATE())
        )

SQL cannot find the @item table and says that it needs to be declared first. At this point I don't know why is this happening and how can I fix it. Also I have my doubts about the performance of that query since there are around 30,000 items that I would perform the stock calculation for.
Maybe there is an easy fix to this problem, or maybe someone can come up with a completely different way of calculating that damned thing. Anyway I could use any help I can get.
Kind Regards.

A: What you want is a cumulative sum.  Even in SQL Server 2008 your while loop is not the best approach.  You might as well do the following:
SELECT it.item, it2.quantity
FROM item_table it OUTER APPLY
     (SELECT SUM(it2.quantity) as quantity
      FROM it2
      WHERE it2.item = it.item AND
            it2.date < it.date
     ) it2;

In this case, the fastest way (apart from upgrading SQL Server) is to do a while loop keeping an incremental value for each day.  However, that might be challenging because you need to handle a separate variable for each item.

A: For ALL items, try this:
    With Ints(aInt) As
      (Select -365 Union All
       Select aInt + 1 From Ints
       Where aInt < 0)
    Select item,
       DateAdd(day, i.aInt, getdate()) tdate
       Sum(quantity) runningTotal
    from item_table it join Ints i
       on it.[Date] < DateAdd(day, i.aInt, getdate())
    group by item, DateAdd(day, i.aInt, getdate())
    Option (MaxRecursion 1000)

to restrict it to some small set of items, just add a where clause
    With Ints(aInt) As
      (Select -365 Union All
       Select aInt + 1 From Ints
       Where aInt < 0)
    Select item,
       DateAdd(day, i.aInt, getdate()) tdate
       Sum(quantity) runningTotal
    from item_table it join Ints i
       on it.[Date] < DateAdd(day, i.aInt, getdate())
    where item in ([set of comma-delimited item values here])
    group by item, DateAdd(day, i.aInt, getdate())
    Option (MaxRecursion 1000)

A: Create a "Numbers" (or "Tally" table).  It is just a single-column table than contains sequential integers.  You can read about how to create one here.  They are useful for replacing while loops.
Once you have that, you can do something like this:
select i.item,
i.date,
sum(i.quantity) over (partition by i.item order by i.date) quantity
from item_table i
join Numbers n on i.date = DATEADD(dd, -1*n.n, convert(date, getdate()))
where n.n <= 365

That should give you a running total of your quantity for each day.
DEMO here


text:
Q: How can I open in the Adobe Reader application("AcroRd32.exe"), a PDF online with url? So my problem is I'm trying to open a PDF file to sign the document, but the document only exists online. To sign the PDF I would like to click in a Button and it would open the PDF that i want, but in the Adobe Reader application. So that the user could do whatever he wants in the PDF.
Need some help on the part of open a pdf that only exists online, but in the application od the adobe Reader.
Thanks any help!!
EDIT1:
So the problem is that my boss do not want the PDF to be download. He wants to click the button and open in the Adobe Reader Application...

A: In order to open the file from AdobeReader locally, you are going to have to copy at minimum a temp file locally. Otherwise, you would have to either create or use a web application that is capable of accessing these files. Either way whatever is accessing the PDF is going to need a copy to display whether it's on your local machine or on a server somewhere.

A: Any PDF that exists online can be downloaded. Once downloaded, you can open it in any PDF reader like AdobeReader. Are you sure you are not able to download it?


text:
Q: Command line list processes using most CPU I am looking for a command line tool / script to periodically capture and store the total cpu usage percentage and processes that are taking most of CPU, similar to sysinternals process explorer screenshot I have pasted below.
I have tried
C:\Windows\system32>typeperf "\process(*)\% processor time" -sc 1

This outputs two rows, with process names in first row and CPU usage in second, e.g.
C:\Windows\system32>typeperf "\process(_Total)\% processor time" "\process(mcshield)\% processor time" -sc 1

"(PDH-CSV 4.0)","\\****\process(_Total)\% processor time","\\****\process(mcshield)\% processor time"
"01/25/2021 09:06:44.599","792.840227","29.364453"

The command completed successfully.

Since the computer has 8 cores, can I simply divide this by 8 to get the "current" CPU usage percentage?
I checked sysinternal pslist. It has one process per row, but I can't figure out what the numbers mean in terms of CPU %.
C:\Windows\system32>pslist -nobanner
Process information for W-2D5TQQ2:

Name                Pid Pri Thd  Hnd   Priv        CPU Time    Elapsed Time
Idle                  0   0   8    0     60     4:38:55.890     1:19:32.649
System                4   8 289 5662    216     0:28:33.656     1:19:32.649
Secure System        72   8   0    0    184     0:00:00.000     1:19:40.412
Registry            128   8   4    0  14012     0:00:13.406     1:19:40.225
smss                620  11   2   53   1188     0:00:01.015     1:19:32.630
csrss               960  13  13  901   1932     0:00:20.796     1:19:08.909
wininit             648  13   1  163   1372     0:00:00.218     1:19:04.494