How to download a file using pure javascript?

I’m trying to make a code in pure javascript (an extension for browser) who be capable to download a file to the source code folder.

Using NPM, the code must be like that:

var http = require('http'),                                                
    Stream = require('stream').Transform,                                  
    fs = require('fs');                                                    

var url = 'http://www.google.com/images/srpr/logo11w.png';                    

http.request(url, function(response) {                                        
  var data = new Stream();                                                    

  response.on('data', function(chunk) {                                       
    data.push(chunk);                                                         
  });                                                                         

  response.on('end', function() {                                             
    fs.writeFileSync('image.png', data.read());                               
  });                                                                         
}).end();

But I can´t use the npm in an extension, so, I need to use pure javascript to make that process, and I didn’t find anything on the web about this.

FadeInLeft effect when changing content

      window.addEventListener('scroll', () => {
    let scrollDistance = window.scrollY;

    if (window.innerWidth > 768) {
        document.querySelectorAll('.section1').forEach((el, i) => {
            if (el.offsetTop - document.querySelector('.nav').clientHeight <= scrollDistance) {
                document.querySelectorAll('.nav a').forEach((el) => {
                    if (el.classList.contains('active')) {
                        el.classList.remove('active');
                    }
                });

                document.querySelectorAll('.nav li')[i].querySelector('a').classList.add('active');
            }
        });
    }
});
body {
  background: gray;
  padding: 100px;
}

.block-2 {
  display: flex;
  flex-direction: row;
  background: white;
  width: 100%;
  padding: 50px;
  height: auto;
}

.section-left {
  position: sticky;
  top: 10px;
  height: 300px;
  /* background: gray; */
  width: 100%;
}

.section-right {
  background: blue;
  width: 100%;
}

.wrap {
  margin: 10px;
  background: red;
}

.content {
  height: 500px;
}

.footer {
  width: 100%;
  height: 700px;
  background: red;
}

.nav {
  position: relative;
  left: 0;
  top: 0;
  width: 100%;
  background-color: white;
  /*     padding: 20px;
*/
}

.nav ul {
  display: flex;
  list-style-type: none;
  flex-direction: column;
  padding: 0;
}

.nav a {
  display: flex !important;
  text-decoration: none;
  color: black !important;
  display: inline-block;
  /*     margin-right: 25px !important;
 */
}

@media screen and (max-width: 1024px) {}

.subtitle {

  opacity: 0;

}



.active {

  opacity: 1;

}

.content1 {
  position: absolute;
  background-color: red;
  /*opacity: 0;*/
  width: 100%;
  height: 300px;
}

.content2 {
  position: absolute;
  background-color: gray;
  /*opacity: 0;*/
  width: 100%;
  height: 300px;
}

.content3 {
  position: absolute;
  background-color: green;
  /*opacity: 0;*/
  width: 100%;
  height: 300px;
}

.content4 {
  position: absolute;
  background-color: blue;
  /*opacity: 0;*/
  width: 100%;
  height: 300px;
}
<body>


  <div class="block-2">
    <div class="section-left">
      <nav class="nav">
        <ul>

          <li><a href="" class="active subtitle">
              <div class="content1">
                <h1>O1</h1>
              </div>
            </a></li>

          <li><a href="" class="subtitle">
              <div class="content2">
                <h1>O2</h1>
              </div>
            </a></li>

          <li><a href="" class="subtitle">
              <div class="content3">
                <h1>O3</h1>
              </div>
            </a></li>

          <li><a href="" class="subtitle">
              <div class="content4">
                <h1>O4</h1>
              </div>
            </a></li>



        </ul>
      </nav>
    </div>
    <div class="section-right">
      <div class="section1 wrap">
        <div class="content">asdf</div>
      </div>
      <div class="wrap section1 ">
        <div class="content">asdf</div>
      </div>
      <div class="wrap section1">
        <div class="content">asdf</div>
      </div>
      <div class="wrap section1">
        <div class="content">asdf</div>
      </div>
    </div>
  </div>
  <div class="footer"></div>
</body>

How can I get the FadeInLeft effect when changing content from .opacity=0 to .opasity=1 in the left side.
I tried to solve this problem with the given script, but it did not work for me.
I am not a cool js expert and I will be glad for your help.
P.S. See this layout in fullscreen.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Thanks

Getting Error – Failed to load resource: the server responded with a status of 403 () for server side rendering of angular app through aws lambda

I have implemented SSR for an angular app with Angular universal and Aws lambda.
The HTML content is loaded but the static files are not rendering.

When i try to indvidually access the js file i get {message:forbidden}

Serverless.yml

service: ngx-serverless-starter
plugins:
  - serverless-offline
provider:
  name: aws
  runtime: nodejs12.x
  lambdaHashingVersion: 20201221
  memorySize: 192
  timeout: 10
package:
  patterns:
    - "!/**"
    - "node_modules/@vendia/serverless-express/**"
    - "dist/**"
    - "lambda.js"
functions:
  api:
    handler: lambda.handler
    events:
      - http: GET /
      - http: GET /{proxy+}

React fine uploader not displaying thumbnails and progress?

I have trouble setting react-fine-uploader to work properly. I’m using react-fine-uploader low level components, and after I choose images thumbnails won’t show although I’ve done everything that docs say.

Here are versions I’m using

"fine-uploader": "^5.16.2",
"fine-uploader-wrappers": "^1.0.1",
"react-fine-uploader": "^1.1.1",

Here is my uploader setup:

const uploader = new FineUploaderTraditional({
options: {
  chunking: {
    enabled: isChunkedUpload,
  },
  request: {
    method: 'POST',
    endpoint: `${process.env.REACT_APP_API_URL}/api/images`,
    customHeaders: { Authorization: `Bearer ${accessToken}` },
    filenameParam: 'name',
    uuidName: 'id',
    totalFileSizeName: 'size',
    inputName: 'image',
  },
  multiple: true,
  callbacks: {
    onComplete: (id: number, name: string, response: object) => {
      console.log(id, name, response);
    },
    onSubmitted: (id: number, name: string) => {
      const newSubmitedFiles = submitedfiles;

      newSubmitedFiles.push(id);
      setSubmittedFiles(newSubmitedFiles);
    },
    onError: (id: number, name: string, errorReason: string, xhr: any) => {
      console.log(id, errorReason, xhr);
    },
  },
},
});

And here are components that I’m using:

     <Dropzone
        className="dropzone"
        style={{ backgroundColor: isDragOver ? 'red' : '' }}
        uploader={uploader}
        multiple
        onDropError={(errorCode: string, errorData: string) => console.log(errorCode, 
        errorData)}
      >
        <span className="dz-message">
          Drop Files Here
        </span>

        {submitedfiles.length ? submitedfiles.map((id) => (
          <div className="dz-preview" key={id}>
            <Thumbnail
              className="dz-image"
              id={id}
              fromServer={false}
              uploader={uploader}
            />
            <CancelButton id={id} uploader={uploader} />
          </div>
        )) : null}
      </Dropzone>

Is it possible to execute a python script through react native expo?

I’m working on a project in react native expo, And i want to Execute a python script inside my react native expo project to run a script, where it will then find a JSON file in my project and use that information to create an excel sheet and email it to the user, that is all it needs to do, I don’t need information to come back to me I just need the file to be executed within my project.

Creating Connection of an existing Mongo DB Database in an existing Docker Container

I want to create a connection from an existing Mongo DB collection to an existing Docker container. Can anybody see it out.

I tried out several syntaxes and approaches but It always give me error.
Thanks in advance!

player-cloud_1  | error  { MongoError: failed to connect to server [cluster0.bgso9.mongodb.net:27017] on first connect [MongoError: getaddrinfo ENOTFOUND cluster0.bgso9.mongodb.net cluster0.bgso9.mongodb.net:27017]
player-cloud_1  |     at Pool.<anonymous> (/app/node_modules/mongodb-core/lib/topologies/server.js:336:35)
player-cloud_1  |     at Pool.emit (events.js:182:13)
player-cloud_1  |     at Pool.EventEmitter.emit (domain.js:442:20)
player-cloud_1  |     at Connection.<anonymous> (/app/node_modules/mongodb-core/lib/connection/pool.js:280:12)
player-cloud_1  |     at Object.onceWrapper (events.js:273:13)
player-cloud_1  |     at Connection.emit (events.js:182:13)
player-cloud_1  |     at Connection.EventEmitter.emit (domain.js:442:20)
player-cloud_1  |     at Socket.<anonymous> (/app/node_modules/mongodb-core/lib/connection/connection.js:189:49)
player-cloud_1  |     at Object.onceWrapper (events.js:273:13)
player-cloud_1  |     at Socket.emit (events.js:182:13)
player-cloud_1  |     at Socket.EventEmitter.emit (domain.js:442:20)
player-cloud_1  |     at emitErrorNT (internal/streams/destroy.js:82:8)
player-cloud_1  |     at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
player-cloud_1  |     at process._tickCallback (internal/process/next_tick.js:63:19)
player-cloud_1  |   name: 'MongoError',
player-cloud_1  |   message:
player-cloud_1  |    'failed to connect to server [cluster0.bgso9.mongodb.net:27017] on first connect [MongoError: getaddrinfo ENOTFOUND cluster0.bgso9.mongodb.net cluster0.bgso9.mongodb.net:27017]' }
player-cloud_1  | error connecting to the database

Using new collections for each user

I am building an Expense Tracking app using Node.js where all the Income and Costs should get saved in a database.

My idea is to create a new collection for each registered user and save all their income/cost actions in that collection.

The things i would like to consider before writing it are:

  • how do i name the collections
  • Efficiency of this method
  • is it even secure
  • how do i save their data when they login from an another device
  • can two users have the same collection name causing them to save their actions in one collection
  • are there any better ways to do this

What i came up with to solve it was to make a model which takes the given company/user name to create a collection.

const mongoose = require('mongoose');
const bcrypt = require ('bcrypt');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
    userName: {
        type: String,
        required: true,
        unique: true
    },
    userPass: {
        type: String,
        required: true
    },
    userEmail: {
        type: String,
        required: true,
        unique: true
    }
}, { timestamps: true });

UserSchema.pre('save', async function (next) {
    try {
        const hashed = await bcrypt.hash(this.userPass, 10)
        console.log('saved user with hashed password.')
        this.userPass = hashed
        next();
    } catch {
        next(error)
    }
})

const User = mongoose.model(userName, UserSchema);

module.exports = User;

And that collection can only be accessed by the one who has the password for that unique name.

So what i would like to ask is: Are there any better ways to do this?

How to modify children to wrap them inside another key

I have the following form.

const MyForm = ({
  myFormRef,
}) => (
  <form id="myForm" ref={myFormRef} method="POST">
    <input name="test_token" type="hidden" />
    <input name="id" type="hidden" />
    <input name="versionId" type="hidden" />
    <input name="additionalId" type="hidden" />
  </form>
);

export default MyForm;

Information from above form is captured here within another component.

[...myFormRef.current.children].forEach((child) => {
    // child.name is 'test_token'
    // child.value is 'some_token'
});

Thus children here is the above data.

children is

{
    test_token: 'some_token',
    id: 'some_id',
    versionId: 'some_version',
    additionalId: 'some_additional_id'
}

I want to modify children to become

{
    token,
    overallData: {
        id,
        versionId,
        additionalId
    }
}

Is it possible to do that?

Closest I found was appendChild() but that is to append a node.

Modify objects in array when combining two arrays into one

I have two arrays of objects that I must combine in one array. If an object is present in both arrays, it should be only once in the final array. If an object is not present in an array, I need to add it with a modified attribute.

Here’s the situation:

const Array1 = [
{value: "id1", name: "Element1", boolean: false}, 
{value: "id2", name: "Element2", boolean: false}, 
{value: "id3", name: "Element3", boolean: false}
]

const Array2 = [
{value: "id1", name: "Element1", boolean: false}, 
{value: "id2", name: "Element2", boolean: false}, 
{value: "id4", name: "Element4", boolean: false}
]

Expected output:

const result = [
{value: "id1", name: "Element1", boolean: false}, 
{value: "id2", name: "Element2", boolean: false}, 
{value: "id3", name: "Element3", boolean: true}, 
{value: "id4", name: "Element4", boolean: true}
]

Test passing locally but failing in gitlab pipeling

I wrote some tests, which pass locally, but fail in the pipeline.

Here’s the test:

async displaysMachineTypeWhenOtherMachineIsSelected () {
      const { asFragment } = render(
        FunctionsFactory.componentFactory({ fetchedState: { machine: mockedMachineState } }),
  );

  // Functions is an object. It's used in other tests and they all pass
  await Functions.selectMachineState1();

  Functions.clickEditText();

  await Functions.clickOnSelect(DetailsNames.Category);

  screen.getByText('Other machine').click();

  await waitFor(() => {
    expect(screen.getByText(DetailsLabels.MachineType)).toBeInTheDocument();
  });

  expect(Array.from(document.querySelectorAll('input')).length).toEqual(10);

  expect(asFragment()).toMatchSnapshot();
}

it(
  'should display machine type dropdown when other machine is selected',
  displaysMachineTypeWhenOtherMachineIsSelected,
);

And as I said, it passes locally, but fails in the gitlab pipeline.

Error from gitlab:

  ● States › Testing machine view › Testing behavior › should display machine type dropdown when other machine is selected
    thrown: "Exceeded timeout of 5000 ms for a test.
    Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."
      64 |         machineBehavior(sharedArgs);
      65 |
    > 66 |       it(
         |       ^
      67 |         'should display machine type dropdown when other machine is selected',
      68 |         displaysMachineTypeWhenOtherMachineIsSelected,
      69 |       );
      at components/pages/states/tests/States.test.tsx:66:7
      at components/pages/states/tests/States.test.tsx:62:5
      at components/pages/states/tests/States.test.tsx:49:3
      at Object.<anonymous> (components/pages/states/tests/States.test.tsx:25:1)
  ● States › Testing machine view › Testing behavior › should return to machine view on Cancel click
    expect(received).toMatchSnapshot()
    Snapshot name: `States Testing machine view Testing behavior should return to machine view on Cancel click 1`
    - Snapshot  - 1
    + Received  + 0
    @@ -782,11 +782,10 @@
                            Layers
                          </div>
                        </div>
                        <div
                          class="ant-tabs-ink-bar ant-tabs-ink-bar-animated"
    -                     style="left: 0px; width: 0px;"
                        />
                      </div>
                    </div>
                    <div
                      class="ant-tabs-nav-operations ant-tabs-nav-operations-hidden"
      85 |
      86 |       Functions.checkIfLabelsArePresent(machineLabels);
    > 87 |       expect(asFragment()).toMatchSnapshot();
         |                            ^
      88 |     },
      89 |   };
      90 | };
      at Object.returnsToMachineViewOnCancelClick (components/pages/states/tests/testFunctions/machine-view/machineView.ts:87:28)
 › 1 snapshot failed.

dependencies from package.json:

"jest": "^27.0.5",
"babel-jest": "^27.0.5",
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^12.0.0",
"jest-cli": "^27.0.5",

Any idea what I’m doing wrong here?

Buefy autocomplete deselect and input issue

I have a Buefy autocomplete field in my project.

<b-field>
    <b-autocomplete
        v-model="client"
        :data="agencyClients"
        field="name"
        @input="setClient"
        :clearable="true"
        open-on-focus
        size="is-small"
    >
    </b-autocomplete>
</b-field>

The v-model property should be the object in form

{id: 10, name: 'AAA'} 

Therefore I use field property in the input which is set to name. This basic set up works well. But if I trigger @input event which looks like

async setClient(clientName) {
    if( clientName ) {
        const client = this.agencyClients.find((item) => item && item.name === clientName);
        if( client ) {
            await this.$store.dispatch(`${this.storeName}/updateClientId`, {clientId: client.id});
            this.client = client;  // Set client as object. 
        }
    }
},

I get and [object] as value in input field. Autocomplete is not able to show client.name value as onload. Why is it so?

The second issue is that with deselect function. It does not trigger @input event. It does not make sence. If I clear the value input event is not triggered? Why?

Can somebody explain me what am I doing wrong? Thanks a lot.

Updating array of objects with recursing function (Mapping replies to comments dynamiclly)

I am receiving a list of comments from a graphql backend in the following format:

[
        {
            "__typename": "Comment",
            "id": "1",
            "userId": "1",
            "postId": "1",
            "parentCommentId": null,
            "content": "test 1"
        },
        {
            "__typename": "Comment",
            "id": "2",
            "userId": "1",
            "postId": "1",
            "parentCommentId": null,
            "content": "this is a comment"
        },
        {
            "__typename": "Comment",
            "id": "34",
            "userId": "1",
            "postId": "1",
            "parentCommentId": "1",
            "content": "reply to test1"
        },
        {
            "__typename": "Comment",
            "id": "35",
            "userId": "1",
            "postId": "1",
            "parentCommentId": "34",
            "content": "nested reply to "reply to test1"nn"
        },
        {
            "__typename": "Comment",
            "id": "36",
            "userId": "1",
            "postId": "1",
            "parentCommentId": "34",
            "content": "test?"
        }
    ]

The comments with parentCommentId === null are the highest level comments, while comments where parentCommentId !== null are replies to a comment where id === parentCommentId

I would like to transform this data structure to something like:

[{
    "__typename": "Comment",
    "id": "1",
    "userId": "1",
    "postId": "1",
    "parentCommentId": null,
    "content": "test1",
    "replies": [{
      "__typename": "Comment",
      "id": "34",
      "userId": "1",
      "postId": "1",
      "parentCommentId": "1",
      "content": "reply to test1",
      "replies": [{
        "__typename": "Comment",
        "id": "35",
        "userId": "1",
        "postId": "1",
        "parentCommentId": "34",
        "content": "reply to test1"
      }]
    }]
  },
  {
    "__typename": "Comment",
    "id": "2",
    "userId": "1",
    "postId": "1",
    "parentCommentId": null,
    "content": "this is a comment",
    "replies": []
  }
]

I have the following function to do the data transformation:

function formatData(comments: Array < IComment > ) {
  let commentList = Array < IComment > ();

  // add comments without `parentCommentId` to the list.
  // these are top level comments.
  for (let i = 0; i < comments.length; i++) {
    if (!comments[i].parentCommentId) {
      commentList.push({ ...comments[i],
        replies: []
      });
    }
  }

  for (let i = 0; i < comments.length; i++) {
    if (comments[i].parentCommentId) {
      const reply = comments[i];
      mapReplyToComment(commentList, reply);
    }
  }


  return commentList;

  function mapReplyToComment(
    commentList: Array < IComment > ,
    reply: IComment
  ): any {
    return commentList.map((comment) => {
      if (!comment.replies) {
        comment = { ...comment,
          replies: []
        };
      }
      if (comment.id === reply.parentCommentId) {
        comment.replies.push(reply);

        return comment;
      } else {
        return mapReplyToComment(comment.replies, reply);
      }
    });
  }
}

However this only works for one level deep into the object tree. so I am getting the replies of a main comment, but replies to replies are not added to the object.

this is what I am getting now:

[{
    "__typename": "Comment",
    "id": "1",
    "userId": "1",
    "postId": "1",
    "parentCommentId": null,
    "content": "test1",
    "replies": [{
      "__typename": "Comment",
      "id": "34",
      "userId": "1",
      "postId": "1",
      "parentCommentId": "1",
      "content": "reply to test1"
      // -- I should have here another node of "replies"
    }]
  },
  {
    "__typename": "Comment",
    "id": "2",
    "userId": "1",
    "postId": "1",
    "parentCommentId": null,
    "content": "this is a comment",
    "replies": []
  }
]

Could you please point out what am I doing wrong and provide some explanation?
Thanks in advance