mardi 25 juin 2019

Most elegant way to write a one shot IF

Since C++ 17 one can write an If-block that will get executed exactly once like this:

#include <iostream>
int main() {
    for (unsigned i = 0; i < 10; ++i) {

        if (static bool do_once = true; do_once) { // enter only once
            std::cout << "hello one-shot" << std::endl;
            // possibly much more code
            do_once = false;
        }

    }
}

I know I might be overthinking this, there are other ways to solve this, but still - is it possible to write this somehow like this, so there is no need of the do_once = false at the end?

if (DO_ONCE) {
    // do stuff
}

I'm thinking a helper function do_once() containing the static bool do_once, but what if i wanted to use that same function in different places? Might this be the time and place for a #define? I hope not.

lundi 24 juin 2019

3 conditions are not acceptable in if statement in R

Declare the process is out of control if Y>=UCL1,Y<=LCL1 (UCL1 and LCL1 control limits are called the outer control limits). Declare the process is in control if LCL2<=Y<=UCL2 ( and are called the inner control limits). However if UCL2

for(j in 1:10000){

for(t in 1:10000)`
if(Y>UCL2 | Y<LCL2 & Y>UCL1 | Y<UCL2 & Y>LCL2 | Y<LCL1) { rl[j]=t}   else{ rl[j]=0}

Getting wrong output when checking if 2 date periods overlap

I am trying to make a function which checks if 2 date periods overlap. For example:

1 July 2019 - 5th July 2019 and 2nd July 2019 - 4th July 2019 would return true as the 2 date periods overlap

1 July 2019 - 5th July 2019 and 13th July 2019 - 24th July 2019 would return false as the 2 date periods don't overlap

I get the wrong answer when I compare these 2 dates 24 March 2019 - 27 March 2019 and 27 March 2019 - 29 March 2019. I get the answer false. Though the answer should be true because I count all days inclusive.

How can I fix this?

import java.time.LocalDate;
import java.time.Month;

public class TestClass {

    public static void main(String[] args) {
        LocalDate start1 = LocalDate.of(2019, Month.MARCH, 24);
        LocalDate end1 = LocalDate.of(2019, Month.MARCH, 27);
        LocalDate start2 = LocalDate.of(2019, Month.MARCH, 27);
        LocalDate end2 = LocalDate.of(2019, Month.MARCH, 29);

        boolean ans = dateOverlaps(start1, end1, start2, end2);
        System.out.println(ans);

    }

    public static boolean dateOverlaps(LocalDate start1, LocalDate end1, LocalDate start2, LocalDate end2) {
        return start2.isBefore(end1) && end2.isAfter(start1); 
    }
}

Boolean method return is not considered in the if statement

An object has a name attribute of type String and a dependency attribute of the same type of the object itself. Now if I create an instance of the object and set the same instance as the dependency attribute, then checking if the object is reflexive by comparing its name with the dependencies name does not work in the if statement.

class Job {
    private String name;
    private Job dependency;

    Job(String name) {
        this.name = name;
    }

    String getName() {
        return name;
    }

    Job getDependency() {
        return dependency;
    }

    void setDependency(Job dependency) {
        this.dependency = dependency;
    }

    boolean hasDependency() {
        return dependency != null;
    }
}

 class JobSequence {
    private ArrayList<Job> jobsArrayList;
    private ArrayList<Job> orderedJobsArrayList = new ArrayList<>();

    JobSequence(ArrayList<Job> jobsArrayList) {
        this.jobsArrayList = jobsArrayList;
    }

    void sortByDependency() {
        for (Job job : jobsArrayList) {
            if (!orderedJobsArrayList.contains(job)) orderedJobsArrayList.add(job);

            if (job.hasDependency()) {
                if (!isReflexive(job, job.getDependency())) {
                    if (!orderedJobsArrayList.contains(job.getDependency())) {
                        int index = orderedJobsArrayList.indexOf(job);
                        orderedJobsArrayList.set(index, job.getDependency());
                        orderedJobsArrayList.add(index + 1, job);
                    }
                }
            }
        }
    }

    private boolean isReflexive(Job i, Job j) {
        return i.getName().equals(j.getName());
    }

public class Main {
    public static void main(String[] args) {
        Job a = new Job("a");
        Job b = new Job("b");
        Job c = new Job("c");

        a.setDependency(null);
        b.setDependency(null);
        c.setDependency(c);

        ArrayList<Job> jobArrayList = new ArrayList<>();
        Collections.addAll(jobArrayList, a, b, c);

        JobSequence sequence = new JobSequence(jobArrayList);
        sequence.sortByDependency();
        sequence.getOrderedJobsArrayList().forEach(p -> System.out.println(p.getName()));
    }
}

How can I create an if loop that only runs if a variable is iterable?

I want to make a simple if statement that checks if a variable is iterable and if the variable is iterable then something will print out. I have posted my code below but it's not working:

numbersList = [1,2,3,4,5,6,7]
if iterable(numbersList) = True:
    print("success")

I'm having trouble with a Network error 1001

I’m having troubles with an app that is similar to WhatsApp, but this is a social network for a bank. It has the chance to create a group and add some of your contacts, the issue is appearing when I try to create a group with more than 14 contacts: the loading indicator appears and after about a minute I receive the 1001 network error (kCFURLErrorTimedOut).

The function I use to create the groups is the next one:

private func crearGrupo() {
        if self.contactosSeleccionados.count < 2 {             
            let errorView = PPAlertView(view: self.navigationController!.view)
            errorView.mostrarConMensaje(NSLocalizedString("error_activityCrearGrupo_integrantesGrupo", comment: ""))            
        } else {    
            let hud = self.mostrarLoading(self.navigationController!.view)
            PeperApi.shareClient.agregarGrupo(nombreGrupo: self.nombreGrupo, completion: { (grupoID, error) in
                if let error = error {                
                    let errorView = PPAlertView(view: self.navigationController!.view)
                    errorView.mostrarConMensaje(error.localizedDescription)
                    hud?.dismiss()                    
                } else if let grupoID = grupoID {
                    self.grupoCreado = Grupo()
                    self.grupoCreado?.grupoID = grupoID
                    self.grupoCreado?.nombre = self.nombreGrupo
                    if let imagenGrupo = self.imagenGrupo {
                        PeperApi.shareClient.actualizarFotoGrupo(image: imagenGrupo, groupId: "\(grupoID)", completion: { (urlString, error) in                            
                            if let error = error {
                                let errorView = PPAlertView(view: self.navigationController!.view)
                                errorView.mostrarConMensaje(error.localizedDescription)
                                hud?.dismiss()                        
                            } else {                                
                                self.grupoCreado?.urlImagen = urlString
                                if let user = User.getUser(), let imagenPerfil = user.imageUrl {
                                    PeperApi.shareClient.agregarAmigosAlGrupo(fotoPerfilOwner: imagenPerfil, grupoId: grupoID, contactos: self.contactosSeleccionados, completion: { (error) in
                                        if let error = error {                                             
                                            let errorView = PPAlertView(view: self.navigationController!.view)
                                            errorView.mostrarConMensaje(error.localizedDescription)                                            
                                        } else {                                              
                                            self.grupoCreado?.cantidadIntegrantes = self.contactosSeleccionados.count                                            
                                            let cobroView = PPAlertBotonesVerticalesView(view: self.navigationController!.view, fondoSeleccionable: false)                                            
                                            cobroView.delegate = self
                                            cobroView.botonCerrar.isHidden = true
                                            cobroView.botonAceptar.setTitle(NSLocalizedString("btn_continuar", comment: ""), for: .normal)
                                            cobroView.botonCancelar.setTitle(NSLocalizedString("activityCobroGrupo_et_omitir", comment: ""), for: .normal)                                            
                                            cobroView.mostrarConMensaje(mensaje: NSLocalizedString("activityCobroGrupo_et_realizar_cobro", comment: ""))
                                        }                                        
                                        hud?.dismiss()
                                    })                                
                                } else {
                                    PeperApi.shareClient.agregarAmigosAlGrupo(grupoId: grupoID, contactos: self.contactosSeleccionados, completion: { (error) in
                                        if let error = error {                                             
                                            let errorView = PPAlertView(view: self.navigationController!.view)
                                            errorView.mostrarConMensaje(error.localizedDescription)                                            
                                        } else {                                             
                                            self.grupoCreado?.cantidadIntegrantes = self.contactosSeleccionados.count                                            
                                            let cobroView = PPAlertBotonesVerticalesView(view: self.navigationController!.view)
                                            cobroView.delegate = self
                                            cobroView.botonAceptar.setTitle(NSLocalizedString("btn_continuar", comment: ""), for: .normal)
                                            cobroView.botonCancelar.setTitle(NSLocalizedString("activityCobroGrupo_et_omitir", comment: ""), for: .normal)
                                            cobroView.mostrarConMensaje(mensaje: NSLocalizedString("activityCobroGrupo_et_realizar_cobro", comment: ""))
                                        }                                     
                                        hud?.dismiss()
                                    })
                                }                                
                            }
                        })
                    } else if let user = User.getUser(), let imagenPerfil = user.imageUrl {
                        PeperApi.shareClient.agregarAmigosAlGrupo(fotoPerfilOwner: imagenPerfil, grupoId: grupoID, contactos: self.contactosSeleccionados, completion: { (error) in
                            if let error = error {                                 
                                let errorView = PPAlertView(view: self.navigationController!.view)
                                errorView.mostrarConMensaje(error.localizedDescription)                                
                            } else {                                 
                                self.grupoCreado?.cantidadIntegrantes = self.contactosSeleccionados.count                                
                                let cobroView = PPAlertBotonesVerticalesView(view: self.navigationController!.view, fondoSeleccionable: false)
                                cobroView.delegate = self
                                cobroView.botonCerrar.isHidden = true
                                cobroView.botonAceptar.setTitle(NSLocalizedString("btn_continuar", comment: ""), for: .normal)
                                cobroView.botonCancelar.setTitle(NSLocalizedString("activityCobroGrupo_et_omitir", comment: ""), for: .normal)                                
                                cobroView.mostrarConMensaje(mensaje: NSLocalizedString("activityCobroGrupo_et_realizar_cobro", comment: ""))
                            }                            
                            hud?.dismiss()
                        })
                    } else {
                        PeperApi.shareClient.agregarAmigosAlGrupo(grupoId: grupoID, contactos: self.contactosSeleccionados, completion: { (error) in
                            if let error = error {                                
                                let errorView = PPAlertView(view: self.navigationController!.view)
                                errorView.mostrarConMensaje(error.localizedDescription)                                
                            } else {                                 
                                self.grupoCreado?.cantidadIntegrantes = self.contactosSeleccionados.count                                
                                let cobroView = PPAlertBotonesVerticalesView(view: self.navigationController!.view)
                                cobroView.delegate = self
                                cobroView.botonAceptar.setTitle(NSLocalizedString("btn_continuar", comment: ""), for: .normal)
                                cobroView.botonCancelar.setTitle(NSLocalizedString("activityCobroGrupo_et_omitir", comment: ""), for: .normal)                                
                                cobroView.mostrarConMensaje(mensaje: NSLocalizedString("activityCobroGrupo_et_realizar_cobro", comment: ""))
                            }                            
                            hud?.dismiss()
                        })                    
                    }
                }
            })            
        }
    }

So, can someone help me to understand if I have an error in my logic? Do I’m using a lot of (If-else)? Or do I need to add some (DispatchQueue.main.async)?

If statement in R uses only first condition to all of the statements. Why?

The below Function which is using to count time in some ranges uses only one condition to all of the statements. Why?

I have been trying to use "any" function to vectorize this statements but it still doesn't work


data <- data.frame(date1=c(as.POSIXct("2016-01-15 13:04:00"),
as.POSIXct("2016-02-25 15:04:00"),as.POSIXct("2016-02-25 15:04:00"),
as.POSIXct("2016-02-25 15:04:00"),as.POSIXct("2012-10-10 17:50:00"),
as.POSIXct("2016-04-14 13:15:00"),as.POSIXct("2016-07-13 08:32:00"),
as.POSIXct("2016-07-13 08:35:00"),as.POSIXct("2016-07-13 08:36:00"),
as.POSIXct("2016-08-09 11:57:00")),

date2=c(as.POSIXct("2018-12-20 16:49:00"),as.POSIXct("2018-12-20 16:50:00"),
        as.POSIXct("2018-12-20 16:50:00"),as.POSIXct("2018-12-20 16:54:00"),
        as.POSIXct("2019-01-11 16:52:00"),as.POSIXct("2019-01-22 11:09:00"),
        as.POSIXct("2019-01-22 11:46:00"),as.POSIXct("2019-01-22 11:26:00"),
        as.POSIXct("2019-01-22 11:18:00"),as.POSIXct("2019-01-22 11:19:00")),

Mid.Category=c("A12","BN1","BN1","BN1","A06","A06","A06","A06",
"A06","A06"),

true_time=c(14983.77,12223.78,12223.78,
                            12223.85,31975.05,14179.92,
                            12925.25,12924.87, 12924.72,
                            12543.38))




data$Mid.Category <- as.character(data$Mid.Category)
str(data)



#################### FUNCTION ###############################

function_SLA <- Vectorize(function(date1,date2){

library(lubridate)


dni_wolne <- c("2018-01-01","2018-01-06","2018-04-01","2018-04-02",
              "2018-05-01","2018-05-03","2018-05-20","2018-05-30",
              "2018-08-15","2018-11-01","2018-11-11","2018-11-12",
              "2018-12-25","2018-12-26","2019-01-01","2019-01-06",
              "2019-04-21","2019-04-22","2019-05-01","2019-05-03",
              "2019-06-09","2019-06-20","2019-08-15","2019-11-01",
              "2019-11-11","2019-12-25","2019-12-26")


if(data$Mid.Category %in% c("B06","B12","BN0","BN1")){


dates <- seq(from=date1,to=date2,"mins")
dates <- dates[which(weekdays(dates) %in% c("poniedziałek","wtorek",
"środa","czwartek","piątek","sobota")

                  & hour(dates) >= 8 & hour(dates) <22
                  & !(as.character(dates,format="%Y-%m-%d") %in% dni_wolne))]

dates <- length(dates)/60


} else if(data$Mid.Category %in% c("A06","A12","AN0")){

dates <- seq(from=date1, to=date2, "mins")

dates <- dates[which(hour(dates) >= 8 & hour(dates) < 22)]

dates <- length(dates)/60
}
return(dates)
}


)

data$wynik <- function_SLA(data$date1,data$date2)


Time that is counting based on this function has to be the same as true_time in data frame but it is true only for one condition in this function. Second condition is counting based on other statement