typescript – RxJs – Flat nested swithMaps and pass variables on Http interceptor

How can the following method be flattened? I tried to pipe all the operators to the first pipe (from(this.fireAuth.currentUser)) but I lost access to the previous variables. It’s an Angular HTTP interceptor that adds a Bearer Token when the user has logged in, the chain should continue as usual when the user has not logged in yet.

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const isApiUrl = request.url.startsWith(apiCloudURL);
    return from(this.fireAuth.currentUser).pipe(
      switchMap(user => {
        if (!user) return next.handle(request);
        return from(user.getIdToken()).pipe(
          switchMap(token => {
            if (isApiUrl) request = this.addToken(request, token);
            return next.handle(request).pipe(
              catchError(error => {
                if ( isApiUrl && token && error instanceof HttpErrorResponse && error.status === 403) {
                  return this.handle403Error(request, next);
                }
                else{
                  return throwError(error); 
                }
              })
            );
          })
        )
      })
    );
  }

Piping to the first observable… I have no access to the token var in the catchError block 😥

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const isApiUrl = request.url.startsWith(apiCloudURL);
    return from(this.fireAuth.currentUser).pipe(
      switchMap(user => {
        if (!user) return next.handle(request);
        return from(user.getIdToken());
      }),
      filter<string>(x => typeof(x) === "string"), //x can be string to HttpEvent<any>
      switchMap(token => {
        if (isApiUrl) request = this.addToken(request, token);
        return next.handle(request)
      }),
      catchError(error => {
        if ( isApiUrl && error instanceof HttpErrorResponse && error.status === 403) {
          return this.handle403Error(request, next);
        }
        else{
          return throwError(error); 
        }
      })
    );
  }

I’m also wondering what’s happening in the scenario where user is falsy, does it mean the request will be canceled because it does not pass the filter?

Thanks.

postgresql – PostgrSQL Many to many relation double nested query

Recently I’ve started working on the backend for my app.
I’ve designed database model where I have representation of 3 tables connected with many to many relation.
They are connected via pivot tables.

So to illustrate I have tables like this below. Where <-> indicated many to many relation created thanks to pivot tables
[country] <-> [city] <-> [building]

What’s is the best way for me to query all countries by property filtering property under building. I.E. asbestos roof.

So I want to query all the countries which have cities containing buildings with roof made of asbestos.

I can figure out what query should be like. To make it most efficient, effective and, eliminate duplicate rows.
Tried something like this:

select r.* from country c, country_city cc, city t, city_building cb, building b
where b.roof = ‘asbestos’
and t.city_id = cb.city_id 
and cc.city_id = t.city_id 
and cc.country_id = c.country_id
group by c.country_id;

But this is not working. I don’t get it :/
Any explanation? Any help?

MongoDB – Robo3t: Failed to do query, no good nodes, Field ‘cursor’ must be a nested object

When viewing documents of a collection and trying to move between pages using “left” and “right” arrow buttons:

enter image description here

suddenly started to get the following error in Robo3T:

Failed to load documents.
Error:
Failed to do query, no good nodes in MyCluster-shard-0, last error: can’t query replica set node mycluster-shard-xx-xx.xxx.xxx.net:27017 :: caused by :: Field ‘cursor’ must be a nested object in: { conversationId: 7, done: false, payload: BinData(0, 723D424753514D4F432F494C776E73765A7263356774622F42564B695A62746F45523832456A5244475473346E30616B4B597938686352413D3D2C733D6F52614C316438586F…), ok: 1 }

Any idea of why is this happening?

All documents in a collection are of following structure:
enter image description here

Using Robo3T 1.4 on Ubuntu/Windows 10 – same thing on both OS.

Nested URL with categories, sub categories and pages in between

I’m a bit new to wordpress and would like to know how to achieve the following structure. Essentially I’m creating a website for a store that carries multiple products. For example:

site.com/brand/<brand1>/products/<product1>
site.com/brand/<brand1>/products/<product2>
site.com/brand/<brand2>/products/<product3>

also as part of the requirement:

site.com/brand loads a page that will display all available brands
site.com/brand/<brand1>/products loads a page that will display all available products for brand 1

Is there a way for me to achieve this without using any plugin? I prefer to create a custom code instead.

information architecture – How can I simplify this highly nested data structure?

Trying to layer multiple levels of tab controls can get messy, fast.

I would suggest you stick with something more simple such as a navigation menu. You could also make it an accordion menu if you don’t want all sub-categories to be visible at the same time.

Here is an example of a simple menu:

enter image description here

It isn’t clear what “medium” and “language” are in your question. So this idea works on the basis that they are field sets and fields. Therefore, you have the navigation menu for categories, and then a single (scrollable) view that will hold all the data for the selected sub-category.

postgresql – Find nested related users

From this SQL schemas, I want to find all users related by contest.id

enter image description here

I try this req :

SELECT u.id, u.firstname, u.lastname, u.avatar FROM contests c
LEFT JOIN trials AS t ON (t.contest_id = c.id)
LEFT JOIN trials_has_users AS tu ON (tu.trial_id = t.id)
LEFT JOIN users AS u ON (u.id = tu.trial_id)
WHERE c.id = '7a101d23-a1d5-457c-821e-14321ae3bb64'
GROUP BY u.id;

but it does not work, u.id, u.firstname, u.lastname, u.avatar is NULL, and I only have one result 😅

time complexity – Theta bound for runtime analysis of nested while loops

I am trying to fully analyze the running time of $texttt{nestedLoops}$ in terms of $n$ with a Theta bound.

The Java code I have is as follows:

public void nestedLoops(int n) {
     int i = 1;
     while (i < n) {
          int j = i;
          while (j > 1) {
               int k = 0;
               while (k < n) {
                    k += 2;
               }
               j = j // 2
          }
          i *= 2
     }
}

I know that the innermost while loop has an obvious runtime of $lceil frac{n}{2} rceil$.
But I get stuck on the next while loops. I think the middle while loop has a runtime of $lfloor
log_2texttt{i} rfloor$
, but that is very confusing for me.

Any help would be taken with much gratitude.

MVC architecture – communication between nested components

I’m working on a rich client desktop application. I’m trying to use MVC to decouple the model, view and controller responsabilities.
Problem is I can’t seem to find a clean solution for handling communication between nested components.

Most of the answers I’ve read online were either confusing or were dealing with “web MVC” architecture rather than real MVC.

I do not mind ending up using another MVC flavor (MVP, MVVM etc…) if it helps me creating a clean a maintainable architecture.

Scenario

The codebase is small and contains two classes: MainView, and MainController. So far the view and controller responsabilities are decoupled and the code is clean.

At some point the codebase grows and I need a SecondaryView with a button. When the button is clicked, the program needs to access the file system to perform operations.

Problem

How to handle the button click in a nested component (one level deep or more) without making a mess in my code?

What I tried so far

1 – One controller owning the nested view and a chain of observer/observables: unmaintainable code

MainController has a reference to MainView. MainView has a reference to SecondaryView.

When SecondaryViewButton is clicked, SecondaryView notifies its listener MainView which notifies its listener MainController which performs the file system operations.

This solution is even less maintainable when we nest components into components into components…

2 – Still one controller, but the main view now owns its nested views AND the controller

MainView has a reference to MainController and SecondaryView.

When SecondaryViewButton is clicked, SecondaryView notifies its listener MainView which directly calls performOperation() method on MainController.

This solution seems slightly better but it wouldn’t work if the clicked button is nested several levels deep.
Plus I suspect having a view reference BOTH controllers and other views is not a good idea?

3 – Multiple controllers, and each view has a reference to its controller

This solution seems better, but now all the controllers have to be able to access the file system (which is a common operation in this application) instead of a unique entry point when we just had MainController.
I’m not sure whether this would be a good idea in the long run.

The real problem however is I don’t have a clear understanding of how to nest components in a MVC architecture? Should I nest the views together and each view reference its own controller?

How would you solve the component nesting problem while maintaining a clean architecture?

rest – POSTing a nested object – returning the created nested object inside the parent

Suppose that we have a Post resource (this is just a dummy example):

GET /api/posts/1

{
  "id": 1,
  "header": null,
  "content": null
}

And now we’d like to create a Header inside the Post#1.

POST /api/posts/1/header

{
  "color": "blue",
  "title": "Some title"
}

Now, is it okay for the POST request above to return the following response?

{
  "id": 1,
  "header": {
    "id": 1,
    "color": "blue",
    "title": "Some title"
  },
  "content": null
}

So, basically, a Header was created inside the Post and returned as part of the Post.

Also, if we need to GET the header for Post#1:

GET api/posts/1/header

 {
   "id": 1,
   "color": "blue",
   "title": "Some title"
}

So here only the Header is returned.

Best Practice: creating a nested associative array JSON in PHP

It’s been a while I have been on here and I hope I still understand the rules😊.
I have recently started learning PHP and WordPress for a Whatsapp Chatbot integration.
I have created a webhook on my WordPress site that returns a JSON, which is consumed by Google Dialogflow(Chatbot engine).

For example, my webhook returns something like this

{
  "fulfillmentMessages": (
    {
      "text": {
        "text": (
          "Text response from webhook"
        )
      }
    }
  )
}

To achieve this structure, I have written used this nested associative array

$innerarr= array();
$innerarr(0) = "Text response from webhook";
$newarr = array();
$newarr("fulfillmentMessages")= array();
$newarr("fulfillmentMessages")(0) = array("text"=>array("text"=>$innerarr));
echo json_encode($newarr);

It works but I’m also thinking, should I

  1. Use a class definition instead that manages the above?
  2. Use the stdClass object to dynamically create this structure?
  3. Is there a neater way to do this as the dynamic properties will grow depending on the request from the chatbot
  4. Am I overthinking?