How to change information in a local db after calling a firebase query in angular?

I have a TS file that is called db-data.ts and it is acting as a local db for entries in my blog. However, I want to change the data in this after calling a querying a firebase db. I am querying firebase in a components ts file and my db-data.ts file is in the src folder. Please forgive me if I used some wrong terms here as I am inexperienced in this. Thanks.

How to append data into JSON using php? [duplicate]

i have a data.json file that looks like this:

{"price_usd":[
  ["June 3, 2022",886.754],
  ["June 5, 2022",899.644],
  ["June 6, 2022",891.014],
  ["June 7, 2022",13685.4],
  ["June 8, 2022",13411]
]
}

I want to add another date + price to this data.json file (inside the price_usd, after june 8), but i dont really know how to do this. Ive looked up different documentations, but all of them had different way to how they formed their JSON.
I cannot use another format, since its connected to a graph.

This is what i have (php), but it just wipes the data.json:

$file=fopen("data.json","w");

$array_data=array();
$extra = array("June 10, 2022", 455);
$array_data["price_usd"] = $extra;
$final_data = json_encode($array_data);
fclose($file);
return $final_data;

Trying to use sessionStorage in javascript

I’m trying to show a popup window only once per session. In order to achieve that I’m using sessionStorage function. however, the popup is showing up whenever I reload the web page. Can you please let me know where I’m making the mistake.

dialogue = new IMu.App.Dialogue();
dialogue.setHtmlMessage(IMu.string('dialogue-heading'));
dialogue.show({ showDetails: true });

window.sessionStorage.setItem('message','true');
var is_dialogue = window.sessionStorage.getItem('message');
if (is_dialogue != 'true')
{
    dialogue.show();
}

Below is the show function

show: function(options, callback)
{
   if (typeof(options) == 'function')
   {
       callback = options;
       options = undefined;
   }
   var test = jQuery('body').children('div.imu-dialogue');
   jQuery('body').children('div.imu-dialogue').remove();
   var owner = self.owner = jQuery('body').child('div', 'imu-dialogue');

    var box = owner.child('div', 'box');

    var message = box.child('div', 'message');
    if (this.message)
    {
        var value = this.message.value;
        var method = this.message.type;
        message[method](value);
    }
            
    if (self.details)
    {
        var details = box.child('div', 'details');
        for (var i in self.details)
        {
             if (! self.details.hasOwnProperty(i))
             continue;

             var detail = details.child('div', 'detail');

             var value = self.details[i].value;
             var method = self.details[i].type || 'text';

             detail[method](value);
          }

           var show = box.child('div', 'show-details');
           if (! options || options.showDetails !== true)
           {
                show.text('Details');
                details.hide();
           }
           else
           {
                details.show();
                show.text('I agree');
           }

           show.on('click', function()
           {
                 self.owner.remove();
           });
}

Property of function does not exist on type angular

Im trying to make a menu image execute a js function to change it’s properties by adding the active class to it. I am working with angular on stackblitz and I keep getting the Property 'openbtn' does not exist on type 'HeaderComponent' error. I am lost on what to do.

The js file is in angular.json like this: "scripts": ["src/app/header/assets/js/nav.js"]

The image which should execute the function:

<img
    src="https://myimage.png"
    width="32"
    alt="!"
    class="burger"
    id="burger"
    (click)="openbtn()"
  />

The function itself:

function openbtn() {
  document.getElementById('burger').onclick = function () {
    this.classList.toggle('active');
  };
}

header.component.ts file:

import { Component, OnInit } from '@angular/core';
declare function openbtn(): any;

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css'],
})
export class HeaderComponent implements OnInit {
  constructor() {}

  ngOnInit() {
    openbtn();
  }
}

Retrieve data from HTML form to server file

I am working on the Stripe payment API and I have a form to collect data that is written in HTML and would like to retrieve the collected data to another javascript file (server.js). I have tried changing the ${AMOUNT} to req.body.amount but seems that is not the case. Is it actually possible to retrieve the data via the form method? Or it is only be done in the fetch method?

HTML:

<form action="/create-checkout-session" method="POST" id="create-checkout-session">
  <div className="description">
    <span>Price:</span> 
    <input type="number" className="field" id="amount" name="amount" min="500"/>
    <button type="submit" id="checkout">
      Checkout
    </button>
  </div>
</form>

Javascript (server.js):

app.post('/create-checkout-session', async (req, res) => {
const session = await stripe.checkout.sessions.create({
line_items: [
  {
    price_data: {
      currency: 'hkd',
      product_data: {
        name: "Test",
      },
      unit_amount: ${AMOUNT},
    },
    quantity: 1,
  },
],
mode: 'payment',
success_url: `${YOUR_DOMAIN}?success=true`,
cancel_url: `${YOUR_DOMAIN}?canceled=true`,});
res.redirect(303, session.url);
});
app.listen(4242, () => console.log('Running on port 4242'));

Azure blob storage and Node.js

So i have been using Azure DB for a while, but i ran in problem that I can’t store in Azure large files and as a solution I found Storage Account.

To make queries I used tedious (JS). Can I save and recieve data via JS?

Why can’t I call a static method from the constructor? [duplicate]

I’m getting into ES6 and trying to turn a class that’s over 2700 lines long into a collection of small, easy-to-read files.

I’d like to move some initialization code from the constructor into their own methods. But I’m a bit stuck. Consider this code:

export default class Thingy {
  non_static_prop;

  initNonStaticStuff() {
  }

  constructor(args) {
    this.non_static_prop = 'some non-static prop set by the constructor'; // ok
    console.log(this.non_static_prop); // works as expected
    // now can we get a method to do the same thing?
    initNonStaticStuff(); // fails:
      /**
       * `Uncaught ReferenceError: initNonStaticStuff is not defined`
       */
    // So I guess we'll have to initialize everything here.
    // But then how am I supposed to make my code smaller and more modular?
  }
}

I’m confused. What options do I have to run code from the constructor?

I could, of course, call a static method instead, but then this wouldn’t let me access non-static properties.

Another option I see is to ask the page that creates the instance to then run initNonStaticStuff() (e.g. say by way of a start() method), but I’d rather skip such a step if possible.

What did I miss?

javascript save base64 image file to new file in directory

In this project my purpose is sending local image url to python or saving image to specific folder.

I am using bootstrap in this link: “https://codepen.io/aaronvanston/details/yNYOXR” for my project. I am uploading image.

https://i.stack.imgur.com/PtMxX.jpg

My javascript code in belong. How can ı take local image url or how can I save image to new file?

function readURL(input) {
    localStorage.setItem("./imgData.jpg", input.files[0]);
    if (input.files && input.files[0]) {
    var reader = new FileReader();
      
        reader.onload = function (e) {
      $('.image-upload-wrap').hide();

            $('.file-upload-image').attr('src', e.target.result);
            var fs;
            // string generated by canvas.toDataURL()
            var img = e.target.result;
            // strip off the data: url prefix to get just the base64-encoded bytes
            var data = img.replace(/^data:image/w+;base64,/, "");
            fs.writeFile('image.jpg', data);
      $('.file-upload-content').show();

      $('.image-title').html(input.files[0].name);
    };

        reader.readAsDataURL(input.files[0]);
       
        
  } else {
    removeUpload();
  }
}

strong text

Having trouble understanding why original object is affected after .map within example

I have been having trouble understanding why temp is being affected here. When looking at the console when running this code:

const objectsArray = [
    {'id': 1, 'name': 'Erik', 'yearsCompleted': 2, 'status': 'student'}, 
    {'id': 2, 'name': 'Carol', 'yearsCompleted': 1, 'status': 'student'}, 
    {'id': 3, 'name': 'Sarah', 'yearsCompleted': 4, 'status': 'student'}
];

temp = {
    actions: objectsArray.map(student => {
    if (student.yearsCompleted === 4) student.status = 'wow';
    return student
    })
}
console.log(temp)

temp2 = {
    actions: objectsArray.map(student => {
    if (student.yearsCompleted === 4) student.status = 'foo';
    return student
    })
}

console.log(temp)
console.log(temp2)

I end up getting the following result:

{ actions:
   [ { id: 1, name: 'Erik', yearsCompleted: 2, status: 'student' },
     { id: 2, name: 'Carol', yearsCompleted: 1, status: 'student' },
     { id: 3, name: 'Sarah', yearsCompleted: 4, status: 'wow' } ] }
{ actions:
   [ { id: 1, name: 'Erik', yearsCompleted: 2, status: 'student' },
     { id: 2, name: 'Carol', yearsCompleted: 1, status: 'student' },
     { id: 3, name: 'Sarah', yearsCompleted: 4, status: 'foo' } ] }
{ actions:
   [ { id: 1, name: 'Erik', yearsCompleted: 2, status: 'student' },
     { id: 2, name: 'Carol', yearsCompleted: 1, status: 'student' },
     { id: 3, name: 'Sarah', yearsCompleted: 4, status: 'foo' } ] }

Why is temp in this case being affected? Are we getting a reference to the objectsArray when setting the actions property of temp to the objectsArray.map function? I thought temp wouldn’t be affected in this case. Thank you.

Changing value of a specific TD using jQuery

I would really like your help.
Couldn’t find the solution on past posts.

I am trying to change the text of a specific td in a specific row.

So I got this code which I find the specific row:

$('#courses-table tr').each(function () {
                

                if (this.children[6].innerText == newAssignment[3]) { // check courses

                    if (this.children[5].textContent == newAssignment[5].split(' ').slice(1).join(' ')) { // check route

                        if (this.children[4].textContent == newAssignment[4].split(' ').slice(1).join(' ')) { // check semester

                            
                            
                            console.log(this.getElementsByTagName('td')[3].textContent)
                            this.getElementsByTagName('td')[0].innerHTML = "TEST";
                            
                                
                                
                                
                               
                        }
                    }
                }
            })

Now, after i find the row with the specific data, i want to change for example the td in position 5 to be something else.
But .innerHTML don’t work for me.

Do you guys have any suggestions for me?
10x

Nestjs multiple file upload with extra properties

I am unable to achieve multiple file upload with extra properties in array of objects.

The below picture shows the things I need to achieve. where I need to retrieve serviceDocument array field with documentFile and caption properties inside it.
enter image description here

Controller

@ApiConsumes('multipart/form-data')
@Post('create')
@UseInterceptors(FilesInterceptor('serviceDocument'))
create(@UploadedFiles() images: Array<Express.Multer.File>, @Body() dto: CreateServiceDto) {
  console.log(images, dto)
  return "hello world"
}

CreateServiceDto

class ServiceDocumentDto {
  @ApiProperty({
    type: 'string',
    format: 'binary'
  })
  @IsNotEmpty()
  documentFile: string

  @ApiProperty()
  @IsNotEmpty()
  caption: string
}

export class CreateServiceDto {
  @ApiProperty()
  @IsString()
  @IsNotEmpty()
  title: string

  @ApiProperty()
  @IsNumberString()
  @IsNotEmpty()
  price: number

  @ValidateNested()
  @ApiPropertyOptional({
    type: [ServiceDocumentDto]
  })
  serviceDocument: ServiceDocumentDto[]
}

How do i update all values of an object in an array?

How do i change all values of salary properties and increase them by the given percentage in this case it would be by 10 in JavaScript.

[
        { name: "Ali", salary: 3000 },
        { name: "Rob", salary: 2000 },
        { name: "Adam", salary: 4500 },
    ],
    10;

Should return

[
   { name: 'Ali', salary: 3300 },
   { name: 'Rob', salary: 2200 }, 
   { name: 'Adam', salary: 4950 }
]

Trying to connect RCON to minecraft server but getting connection timeout

I’m stuck with connecting to RCON, but I can’t. I tried some packages like rcon-client and modern-rcon, but none of them seems to work. I get exactly the same error, but I don’t know how could I fiz this on server side. I use node 18.2.0.
My code is this:

const Rcon = require("modern-rcon")

const rcon = new Rcon(<serverip>, <rconpassword>)

  await rcon
    .connect()
    .then(() => {
      return rcon.send("say hello world")
    })
    .then((res) => {
      console.log(res)
    })
    .then(() => {
      return rcon.disconnect()
    })

but while after running I’m getting error:

node:internal/process/promises:288
            triggerUncaughtException(err, true /* fromPromise */);
            ^

Error: connect ETIMEDOUT <serverip>:25575
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1195:16) {
  errno: -4039,
  code: 'ETIMEDOUT',
  syscall: 'connect',
  address: '<serverip>',
  port: 25575
}

How can I fix this?