mercredi 21 avril 2021

Object and array structuring based on form entry values

I have the following two scenarios that I need to build but unsure how to represent this from a JavaScript perspective. I am using React and the user will be presented with a form to enter the following info for both scenarioss, where each day of the week will be presented to the user as follows:

Scenario 1: Weekly

Day of week = Monday (which can have one or more of the following entries)
    Task Name 
    Task Start Time
    Task End Time

    . . . 
       . . . 

Day of week = Sunday (which can have one or more of the following entries)
    Task Name 
    Task Start Time
    Task End Time

For this scenario, I was thinking of the following structure where there would also be a button for the user to add/remove taskDetails:

const weeklyTasks = {
         dayOfWeek: "Monday",
         taskDetails: [
             {
               taskName: "",
               taskStartTime: "",
               taskEndTime: ""
             }
         ],
         dayOfWeek: "Tuesday",
         taskDetails: [
             {
               taskName: "",
               taskStartTime: "",
               taskEndTime: ""
             }
         ],

         . . . 
             . . .
         dayOfWeek: "Sunday",
         taskDetails: [
             {
               taskName: "",
               taskStartTime: "",
               taskEndTime: ""
             }
         ]
       }

Scenario 2: Fornightly

Week 1:
    Day of week = Monday (which can have one or more of the following entries)
        Task Name 
        Task Start Time
        Task End Time
    
        . . . 
           . . . 
    
    Day of week = Sunday (which can have one or more of the following entries)
        Task Name 
        Task Start Time
        Task End Time


Week 2
    Day of week = Monday (which can have one or more of the following entries)
        Task Name 
        Task Start Time
        Task End Time
    
        . . . 
           . . . 
    
    Day of week = Sunday (which can have one or more of the following entries)
        Task Name 
        Task Start Time
        Task End Time

For this scenario, I was thinking of the following structure where there would also be a button for the user to add/remove taskDetails:

const FortnightlyTasks = {
         weekNumber: 1,
         dayOfWeek: "Monday",
         taskDetails: [
             {
               taskName: "",
               taskStartTime: "",
               taskEndTime: ""
             }
         ],
         dayOfWeek: "Tuesday",
         taskDetails: [
             {
               taskName: "",
               taskStartTime: "",
               taskEndTime: ""
             }
         ],

         . . . 
             . . .
         dayOfWeek: "Sunday",
         taskDetails: [
             {
               taskName: "",
               taskStartTime: "",
               taskEndTime: ""
             }
         ],
         weekNumber: 2,
         dayOfWeek: "Monday",
         taskDetails: [
             {
               taskName: "",
               taskStartTime: "",
               taskEndTime: ""
             }
         ],
         dayOfWeek: "Tuesday",
         taskDetails: [
             {
               taskName: "",
               taskStartTime: "",
               taskEndTime: ""
             }
         ],

         . . . 
             . . .
         dayOfWeek: "Sunday",
         taskDetails: [
             {
               taskName: "",
               taskStartTime: "",
               taskEndTime: ""
             }
         ]
       }

iOS: Decouple HTTP Requests from view controller

I have feature in my app where the user will initiate a http request to an API from a view controller and quickly navigate between different view controllers. However the http request response is still valid and should be handled even when the user moves out from the view controller. So technically, the app is in foreground only but the user can initiate http requests and navigate between different screens. What is the best design pattern to solve this on iOS. I know in Android we can use a combination of intent service and broadcast receivers to solve this problem.

How to keep a global state in memory of an object?

I'm trying to build an application that will receive a lot of messages that may be repeated in any order, how can i instantiate a class or keep the data in memory to avoid processing the same information more than once? example:

The messages:

{"product": {"name": "iphone", "active": True}}
{"price": {"amount": 100}}
{"product": {"name": "iphone", "active": True}}

When processing the messages I need to generate an error saying that the "product was already activated", I've tried to use the Singleton pattern but I don't think that it will work because I'm reading the message in a loop and i didn't figure out how to store the "product" information somewhere in a global state and check if the state is None and active = True.

The loop:

for message in messages:
    product = Product(message)  # serialize the dict into a class, this is the first message

    # On the second loop I should get an "string" saying that the product was already activated.

How can I store a information in a global state?

create list of organisms based on pattern matching of sequence to a genome

I have a dataframe with two columns, the first are names of organisms and the second is there sequence which is a string of letters. I am trying to create an algorithm to see if an organism's sequence is in a string of a larger genome also comprised of letters. If it is in the genome, I want to add the name of the organism to a list. So for example if flu is in the genome below I want flu to be added to a list.

dict_1={'organisms':['flu', 'cold', 'stomach bug'], 'seq_list':['HTIDIJEKODKDMRM', 
'AGGTTTEFGFGEERDDTER', 'EGHDGGEDCGRDSGRDCFD']}
df=pd.DataFrame(dict_1)

     organisms             seq_list
0          flu      HTIDIJEKODKDMRM
1         cold  AGGTTTEFGFGEERDDTER
2  stomach bug  EGHDGGEDCGRDSGRDCFD

genome='TLTPSRDMEDHTIDIJEKODKDMRM'

This first functions finds the index of the match if there is one where p is the organism and t is the genome. The second portion is the one I am having trouble with. I am trying to use a for loop to search each entry in the df, but if I get a match I am not sure how to reference the first column in the df to add the name to the empty list. Thank you for your help!

def naive(p, t):
occurences = []
for i in range(len(t) - len(p) + 1):
    match = True
    for j in range(len(p)):
        if t[i+j] != p[j]:
            match = False
            break
    if match:
        occurences.append(i)
return occurences


Organisms_that_matched = []
for x in df:
   matches=naive(genome, x)
   if len(matches) > 0:
      #add name of organism to Organisms_that_matched list

Try except clauses for importing multiple Python modules

Let's say I have many modules, that may or may not throw some kind of Exception. From each of these modules I'd like to retrieve one class(extending common superclass).

Question

How to neatly avoid writing try except clause which is the same for all of them?

Possible solutions

For example I could write a for loop based on strings representing modules and classes inside them, but this looks bad, e.g. because it loses IDE support.

Another possible solution is to move fail-checking to instance initialization. But failing at import is the first possible place that it can fail, so I guess that's delaying the inevitable.

It would be great if modules could append themselves to some list if they succeed at initializing, but I have no idea how to do that.

Code:

a.py

class A(CommonInterface):
   a = 1 / 0 # simulating bad configuration

b.py

class B(CommonInterface):
   b = 1 # good configuration

all.py

all_classes = []
try:
    from a import A
    all_classes.append(A)
except Exception as e:
    some_common_routine()
try:
    from b import B
    all_classes.append(B)
except Exception as e:
    some_common_routine()

# all_classes == [B]

Generic Messaging when concrete Messages are autogenerated C++ classes from XML

Background

I have auto generated concrete message types from a XML -> C++ generator.

GenMsg1, GenMsg2, ... , GenMsgN

All of these generated classes are from an XML schema. Technically I can edit their cpp and hpp files but I would prefer to not touch these as much as possible. They all have guaranteed functions that I would like to be able to call generically.

NOTE: I cannot get away from the above situation as this is a design limitation from another project. Also, I just used raw pointers in this simple example. I understand this is not best practice, its just for showing a general idea.

Goal

I am looking to process the above generated messages generically on my side.

Idea 1 and 2

My first idea was to just create and general "Message" class that was templated to hold one of the above types with a simple enum for identifying what type of message it is. The problem with this is I cannot just pass around a pointer to Message because it needs the template type parameter so this is obviously a no-go.

My next thought was to use the Curiously Recurring Template Pattern but that has the same issues as above.

Idea 3

After a lot of reading on messaging frameworks my next thought was that std::variant might be an option. I have the following example which works but it uses double pointers and templated functions to access. If the wrong datatype is used this will throw an exception at runtime (which makes it quite clear this is the issue) but I could see this being annoying down the line as far as tracking the source of the throw.

I keep trying to read up on the std::visit but it does not make a whole lot of sense to me. I do not really want to implement a separate visitor class with a bunch of functions by hand when all of the functions in the generated classes are autogenerated already(like foo in the example below) and are ready to be called when the type is known. Additionally, they are guaranteed to exist. So it would be kind of nice to be able to call a foo() in Message and have it dive into the internal Representation and call its foo.

I have a MsgType enum in there that I could use as well. When the internal representation is set, I could set that and use it for deducing type... But this seems like its just duplicating effort already done by the std::variant so I scrapped its use but kept it in the code blow in case someone here had a new idea where something like that could be useful.

Any ideas on design moving forward? This seems like the most promising route, but I am open to ideas.

Idea 3 Code

#include <iostream>
#include <variant>

enum class MsgType { NOTYPE = 0, GenMessage1 = 1, GenMessage2 = 2, GenMessage3 = 3 };

class GenMessage1
{
public:
    void foo() {std::cout << "Msg 1" << std::endl;}
};

class GenMessage2
{
public:
    void foo() { std::cout << "Msg 2" << std::endl; }
};

class GenMessage3
{
public:
    void foo() { std::cout << "Msg 3" << std::endl; }
};

class Message
{
private:
    MsgType msgType;
    std::string xmlStrRep;
    std::variant<GenMessage1*, GenMessage2*, GenMessage3*> internalRep;
public:

    Message()
    {
        this->msgType = MsgType::NOTYPE;
        this->xmlStrRep = "";
    }

    template <typename T>
    void setInternalRep(T* internalRep)
    {
        this->internalRep = internalRep;
    }

    template <typename T>
    void getInternalRep(T retrieved)
    {
        *retrieved = getInternalRepHelper(*retrieved);
    }

    template <typename T>
    T getInternalRepHelper(T retrieved)
    {
        return std::get<T>(this->internalRep);
    }

    void foo()
    {
        //call into interal representation and call its foo
    }
};

int main()
{
    Message* msg = new Message();
    GenMessage3* incomingMsg = new GenMessage3();
    GenMessage3* retrievedMsg;
    msg->setInternalRep(incomingMsg);
    msg->getInternalRep(&retrievedMsg);

    retrievedMsg->foo();

    return 0;
}

Outputs:

Msg 3

Is two way classes association bad?

I was developing one tool, and noticed what my classes use "two way association". Objects of class A have a pointer to B, and B have pointer to A. I tried to find out, is that a bad design architecrute, or it is ok, but didn't found anything.

class A {
    B field;
    
    public A(B field) {
      this.field = field;
    }
}

class B {
    A field;
    
    public B() {
      field = new A(this);
    }
}

So, how bad this is?