reverse recursive search on an object with javascript – like tree search

I implemented a tree search with JavaScript.

It has below basic rules.

  • It will search over an array of objects which has recursive(like fractal)
  • If it found a according data in a leaf(the final depth one), it will return its ancestors, but without its siblings.(Example is below)

So here is an example.

Original one like this:

[      {         "value":"apple",       "children":[            {               "value":"green-apple",             "children":[                ]          },          {               "value":"red-apple",             "children":[                  {                     "value":"asia-red-apple",                   "children":[                      ]                },                {                     "value":"europe-red-apple",                   "children":[                      ]                },                {                     "value":"africa-red-apple",                   "children":[                      ]                }             ]          }       ]    },    {         "value":"grape",       "children":[            {               "value":"green-grape",             "children":[                  {                     "value":"asia-europe-green-grape",                   "children":[                      ]                },                {                     "value":"asia-africa-green-grape",                   "children":[                      ]                },                {                     "value":"africa-europe-green-grape",                   "children":[                      ]                }             ]          },          {               "value":"red-grape",             "children":[                  {                     "value":"asia-red-grape",                   "children":[                      ]                },                {                     "value":"europe-red-grape",                   "children":[                      ]                },                {                     "value":"africa-red-grape",                   "children":[                      ]                }             ]          }       ]    } ] 

Like I said before, it has children array element recursively. It user searches africa for instance, the result should be like below:

[      {         "value":"apple",       "children":[            {               "value":"green-apple",             "children":[                ]          },          {               "value":"red-apple",             "children":[                  {                     "value":"asia-red-apple",                   "children":[                      ]                },                {                     "value":"europe-red-apple",                   "children":[                      ]                },                {                     "value":"africa-red-apple",                   "children":[                      ]                }             ]          }       ]    },    {         "value":"grape",       "children":[            {               "value":"green-grape",             "children":[                  {                     "value":"asia-europe-green-grape",                   "children":[                      ]                },                {                     "value":"asia-africa-green-grape",                   "children":[                      ]                },                {                     "value":"africa-europe-green-grape",                   "children":[                      ]                }             ]          },          {               "value":"red-grape",             "children":[                  {                     "value":"asia-red-grape",                   "children":[                      ]                },                {                     "value":"europe-red-grape",                   "children":[                      ]                },                {                     "value":"africa-red-grape",                   "children":[                      ]                }             ]          }       ]    } ] 

0 and other parents value may not contain the keyword africa, but those will be returned since the final depth one(leaf) contains the keyword. That is the reason why I wrote reverse, the standard of search is on the final level.

The main logic implemented like here:

function recursiveSearch (coll, str, level) {     if(!level) level = 0;     console.log('level', level, ' coll size before job', coll.length);     let removalValuesForThisLevel = [];     let temp = [].concat(coll);     temp.forEach(mem => {         if(mem.children && mem.children.length > 0) {             // recursive if has child             let subList = recursiveSearch(mem.children, str, level + 1);             mem.children = (subList) ? subList : null;         } else {             if((mem.value || '').indexOf(str) > -1) {                 // collect according values                 // console.log(mem.value,' is match for string :: ', str);             } else {                 // collect removal values                 // console.log(mem.value,' is not match for string :: ', str);                 removalValuesForThisLevel.push(mem.value);             }         }     });      temp = temp.filter(mem => {         return mem.children && (removalValuesForThisLevel.indexOf(mem.value) < 0);     });      console.log('level', level, ' coll size AFTER job', temp.length, JSON.stringify(temp))     return (temp.length > 0) ? temp : (level === 0) ? [] : null; } 

It might work fine (in my thought), but I am worried about some parts.

  • If it handles tones of data(like billions).
  • Too many loops maybe?
  • Too many copy operations like Array.filter, Object.assign

You can advise me about good coding habbits and logics for JavaScript.

Here is a working fiddle.

Identifying an object pointer by generating and using a unique ID

I have an image class and a table class. To each image a single table can be “attached”. Each <image, table> pair should be identified with an ID, which can later be used to get the pointer of image or table associated with that ID. Images in this “map” should be unique. Below is my solution, please let me know if it can be improved. Thanks.

browserInfo.h

#include <vector> #include <tuple>  class BrowserInfo { public:     // Returns a unique ID for the <image, table> pair     /*         @param  img The image file pointer         @param  tbl     The table view pointer         @return         A unique ID for the input pair     */     unsigned getId(image *img, table *tbl) const;      /// Returns a image pointer for the given ID     /*         @param  uId The ID of <image, table> pair         @return     A pointer to image file if ID exists, otherwise nullptr     */     image *getImage(unsigned uId) const;      /// Returns a table pointer for the given ID     /*         @param  uId The ID of <image, table> pair         @return     A pointer to table if ID exists, otherwise nullptr     */     table *getTable(unsigned uId) const;  private:     // alias for the type     using imageTableToId = std::tuple<image *, table *, unsigned>;      // This vector keeps track of all unique <image, table> pair IDs     mutable std::vector<imageTableToId> m_vecImageTableIds;      // The current ID     mutable unsigned m_iCurrentId = 0;  }; // class BrowserInfo 

browserInfo.cpp

unsigned BrowserInfo::getId(image *img, table *tbl) const {     // first, try to see if we have worked with the provided image before     for (auto &tuple : m_vecImageTableIds)     {         if (std::get<0>(tuple) == img)         {             // we support a single table view for each image.             // therefore, if we find that the image is already stored             // in our vector, we just need to update the corresponding             // table pointer and return a new unique ID for this pair             std::get<1>(tuple) = tbl;             std::get<2>(tuple) = ++m_iCurrentId;              return m_iCurrentId;         }     }      // if we got here it means the image pointer wasn't stored before     // so we can just insert a new tuple into the vector     m_vecImageTableIds.push_back(std::make_tuple(img, tbl, ++m_iCurrentId));     return m_iCurrentId; }  image *BrowserInfo::getImage(const unsigned uId) const {     for (const auto &tuple : m_vecImageTableIds)     {         if (std::get<2>(tuple) == uId)             return std::get<0>(tuple);     }      return nullptr; }  table *BrowserInfo::getTable(const unsigned uId) const {     for (const auto &tuple : m_vecImageTableIds)     {         if (std::get<2>(tuple) == uId)             return std::get<1>(tuple);     }      return nullptr; } 

Transfer a Response object to another process

I am trying to pass an Express’ Response object from child process A to child process B.

In a.js, I am doing the following process.send(process.pid, res.socket);

In b.js, I can get the response socket by using the following

process.on('message', (msg, handle) => {     var output = { msg: msg, socket: handle };     console.log(output);     handle.write('hello there client!'); } 

When I print the contents of output, I do get the msg: 4355 and socket is connected and contains the IP address and port of the connected client. But when I use the socket to write hello there client!, the client did not receive the response. Please help?

My client is Postman.

How to install and enable object cache for LEMP on ubuntu 18.04 [on hold]

I deployed my server on digital ocean with LEMP stack. I followed all the official article below to use my server:-

  1. https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-18-04

  2. https://www.digitalocean.com/community/tutorials/how-to-install-linux-nginx-mysql-php-lemp-stack-ubuntu-18-04

  3. https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-18-04

  4. https://www.digitalocean.com/community/tutorials/how-to-install-wordpress-with-lemp-on-ubuntu-18-04

  5. https://www.digitalocean.com/community/tutorials/how-to-set-up-nginx-with-http-2-support-on-ubuntu-18-04

  6. https://www.digitalocean.com/community/tutorials/how-to-add-the-gzip-module-to-nginx-on-ubuntu-16-04

Now, still, I am not happy with my server because I know it can be optimized more. There are many things I still need to set up on my server, e.g., Object caching (Memcached, Varnish, Radis, FastCGI Caching)

First please clear my some doubt:-

  1. Should I install Varnish, Memcached & Radis all or only one? I read some article, and they are saying to install all for optimal performance. Is that correct?

  2. What about Nginx fast-CGI cache? Is this ahead of Varnish, Radis & Memcached? Is this pre-configured with Nginx or I need to enable manually. If I need to allow this, then how can I manually set up this?

  3. Should I move to PHP 7.3 now? I am on PHP 7.2. Is this stable now?

  4. I am using Ubuntu 18.04; I think this is LTS version of Ubuntu, should I go with the latest Ubuntu version mentioned on DO?

  5. Best cache plugin compatible for Nginx on frontend WordPress level? I have used Wp-Rocket & Swift performance Pro but if there is any other, i will be happy to know about.

  6. Best Nginx WordPress plugin to manage server level object cache? I have used Nginx helper and Redis Object Cache WordPress plugin. But don’t know which one works best.

Please if you can help me, then please clear my doubt and give a tutorial to configure Object Caching on server lever according to my server setup. If I am missing anything, please let me know. Thanks in advance.

How to use window.getSelection on an object parameter (here: browser.menus.onClicked.addListener((info, tab) `

I am building a FF Add-on that has to ensure the following:

  1. User highlights text, e.g. the word “example” on a page
  2. User opens right-click custom browser menu
  3. User selects icon of add-on
  4. In consequence, user is being taken to a website that contains the hightlighted text between www. and .com, e.g.: www.example.com

Currently, the injection of the content taken through
“window.getSelection().toString();” into the “url: part” does not work.

Maybe it is a scope problem? Thx in advance.

I am an absolute beginner. I moved “let selObj = window.getSelection().toString();” directly under “browser.tabs.create({… – with no success.

‘use strict’;

const openLabelledId = "open-labelled";  browser.menus.create({ id: openLabelledId, title: "Open", contexts: ["selection"] 

});

let selObj = window.getSelection().toString();  browser.menus.onClicked.addListener((info, tab) => { if (info.menuItemId === openLabelledId) { browser.tabs.create({   url: "(`http://$  {selObj).com+`)" }); 

} });

Expected result: selObj defines which website will be opened, e.g. when highlighting “cnn”, www.cnn.com is being opened

Actual result: “File on moz-extension://562a42ef-c853-4689-8488-fafbfa753353/(http://$ {selObj).com) can’t be read.”

Refactoring a LINQ lambda expression to eliminate duplicate object creation code

the following code fetches data from a MySql database to generate a simple report on accrued work time on projects.

I’ve been away from Entity Framework for a while and looking at this code you can see that the creation of ListProject is basically repeated 3 times.

Is there any way to refactor this so I can reuse the duplicate parts?

I’ve thought about a factory method, but that won’t work because it can’t be translated to SQL by the expression interpreter.

    var project = entities.Tickets         .Where(p => p.ID == id)         .Select(p => new ListProject         {             Id = p.ID,             Name = p.ueberschrift,             AssignedEmployee = new ListEmployee             {                 Id = p.AssignedEmployee.ID,                 Name = p.AssignedEmployee.name             },             WorkUnits = p.WorkUnits                 .Select(wu => new ListProjectWorkUnit                 {                     Duration = wu.dauer,                     PauseDuration = wu.pauseDauer,                     Employee = new ListEmployee                     {                         Id = wu.AssignedEmployee.ID,                         Name = wu.AssignedEmployee.name                     }                 })                 .ToList()             })             .Single(); 
    project.Tickets = entities.Tickets         .Where(p => p.vonProjekt == id)         .Where(p => p.phaseID == 0)         .OrderBy(p => p.ueberschrift)         .Select(p => new ListProject         {             Id = p.ID,             Name = p.ueberschrift,             AssignedEmployee = new ListEmployee             {                 Id = p.AssignedEmployee.ID,                 Name = p.AssignedEmployee.name             },             WorkUnits = p.WorkUnits                 .Select(wu => new ListProjectWorkUnit                 {                     Duration = wu.dauer,                     PauseDuration = wu.pauseDauer,                     Employee = new ListEmployee                     {                         Id = wu.AssignedEmployee.ID,                         Name = wu.AssignedEmployee.name                     }                 })                 .ToList()             })             .Single(); 
    project.Phases = entities.projekt_phase         .Where(p => p.projektID == id)         .OrderBy(p => p.rang)         .Select(p => new ListProjectPhase         {             Id = p.ID,             Name = p.name,             Tickets = p.Tickets                 .OrderBy(t => t.ueberschrift)                 .Select(t => new ListProject                 {                     Name = t.ueberschrift,                     Id = t.ID,                     AssignedEmployee = new ListEmployee                     {                         Id = t.AssignedEmployee.ID,                         Name = t.AssignedEmployee.name                     },                     WorkUnits = t.WorkUnits                         .Select(wu => new ListProjectWorkUnit                         {                             Duration = wu.dauer,                             PauseDuration = wu.pauseDauer,                             Employee = new ListEmployee                             {                                 Id = wu.AssignedEmployee.ID,                                 Name = wu.AssignedEmployee.name                             }                         })                         .ToList()                 })                 .ToList()         })         .ToList(); 

OpenShift template “object already exists” error

I have developed an Openshift template which basically creates two objects (A cluster & a container operator).

I understand that templates run oc create under the hood. So, in case any of these two objects already exists then trying to create the objects through template would through an error. Is there any way to override this behaviour? I want my template to re-configure the object even if it exists.

Tensorflowsharp GPU: Different output of object detector on GPU and CPU

I have downloaded a model ssd_mobilenet_v1_coco from here. Testing of the model has schown different boxes result for the same code on GPU and CPU. May be someone know what causes such behaviour and how this problem may be solved.

I have installed:

CUDA–>10.0

cudnn–> 7.3

tensorflow-gpu–> 1.12.2

tensoeflowsharp –> 1.12.0

Whenever i call the index URL a model object is sent as a parameter?

I am trying to permit only certain parameters in my controller method . I am finding a empty model object being passed with every request .

For Example : I have a organizations controller and whenever I call the get request(routed to index method) I see a parameter : organizations{} passed to it .How to remove this