invalid checksum when using multipart upload with FULL_OBJECT checksum in NodeJS

Problem

I am trying to upload a file into AWS (since I am testing I am using a dockerized minio).

  1. I am calculating the checksum of the file like this:
    const fileContent = await readFile(fileName, {
      encoding: "binary",
    });
    const checksum = checksums.crc32(fileContent);
    
  2. Then I create a multipart upload, this part of my code.
  3. I store the UploadId for future use here.
  4. Then I start uploading each chunk inside a for loop.
  5. I also store all the parts responses in an array (here).
  6. Finally I try to complete the whole file upload by sending a CompleteMultipartUploadCommand.

If I remove line 77 and 78:

ChecksumType: "FULL_OBJECT",
ChecksumCRC32: checksum.toString(),

It will upload the file but that is not what I want.

Desired Outcome

  1. I want send the calculated checksum of the enter file (from the first byte to the last byte) to AWS S3 when I am sending the CompleteMultipartUploadCommand.
  2. So that AWS S3 can check data integrity of the uploaded part when they are being assembled back.

Side Notes

Questions

First, thanks in advance for you’re answer.

  1. Please if possible add a link to a repo or share some example.

  2. Explain what I do not know about this holy grail of checksum & data integrity check.

  3. I am not exactly familiar with how AWS S3 is generating those CRC32 checksums since the ones I was able to generate are all numbers and nothing like things AWS S3 returns as your checksum. You can look at the logs of Parts, here is one of them:

    ChecksumCRC32: 'VG/A4w=='
    

    Whereas the one I generate from the entire file is 209188370, a number!

    So maybe someone out there know how in NodeJS I can generate the same CRC32 as AWS folks do since I feel like my code is broken somehow.

Global variables in Incisor

How can I define and access global variables in an Incisor project?

In a typical Incisor project, the code is split across multiple packages and files. There will be situations where it’s necessary to reference data that needs to be globally accessible. What is the best way to create and access global variables throughout the codebase?

Result of JavaScript await inside if/else not available outside if/else block [duplicate]

I have an async function with an if/else statement:

class ItemsService {
  async getItems(fetchAmounts = false) {
    if (fetchAmounts === true) {
      const {
        items = [],
      } = await this.getAmounts(userId);
    } else {
      const {
        items = [],
      } = await this.getCounts(userId);
    }

    console.log(`items: ${JSON.stringify(items)}`);
  }
}

getAmounts and getCounts are both async. The console.log fails because items is not defined after the if/else statement despite the await. Additionally, running eslint on the code results in:

5:13  error  'items' is assigned a value but never used  no-unused-vars
9:13  error  'items' is assigned a value but never used  no-unused-vars
13:13 error  'items' is not defined                      no-undef

If I remove the if/else and only have the if case code, then everything works and items is defined as expected.

class ItemsService {
  async getItems(fetchAmounts = false) {
    const {
      items = [],
    } = await this.getAmounts(userId);
  }

  console.log(`items: ${JSON.stringify(items)}`);
}

Why does having the await inside an if/else fail and result in items not being defined outside the if/else?

For Programmers, an API that gives all the movies and series, even if it is paid? [closed]

stack overflow users, this is a question, specially for programmers, i want to create a web app that hosts all the movies and series, but i cannot find one, now i know that there are a lot of streaming platforms that gives the movies and series for free, where do they get this data? can you recommend me any api? i am guessing that these will be pirated but nonetheless there exists? and if there are any paid ones lete me know.
one more thing, does web scrapping also helps in extracting the movies? if yes can i do it in real time so that i don’t have to store the data in my own storage?

I tried internet, youtube tutorials, deepseek search, the best i could find the api’s that provide the meta data only, and guess what that are also paid? only 1000 requests a month for free? i mean even meta data is not free? what so special about the meta data that it is also paid?

Increase the width of a Qualtrics slider label

I’ve created a Qualtrics Survey slider and included the four labels above the slider, but my labels have a larger text so the last label is getting thinner and taller as compared to other three labels. Is there a way to increase the width of the label text box?enter image description here

I am not very familiar to qualtrics so tried to do it on qualtrics but nothing is working. i tried some solutions from internet but no one was answering this specific problem.

Remove rows from HTML table when rows added by PHP do… while loop [closed]

I have an HTML table with twelve available rows which is filled using a do… while… PHP loop.

If there is only one line of data entered, there are still twelve rows, but if there are more rows added by the loop, a new row is added each time.

I need to remove a table row for each extra row the loops adds.

How do I achieve this?

I’ve looked at other solutions here and via Google, but they don’t include a do… while… loop, or use a button to remove a row.

Is it possible to pass a Comlink-proxied object to a proxied function?

This question relates to the Comlink WebWorker library and specifically to the usage of Comlink.proxy. Consider the following situation:

// worker.ts

import * as Comlink from 'comlink';

export class Foo { ... }

export class Bar {
    makeFoo () {
        return Comlink.proxy(new Foo);
    }
    useFoo (foo: Foo) { ... }
}

Comlink.expose(Bar);
// main.ts

import type { Foo, Bar } from './worker.ts';
import * as Comlink from 'comlink';

const worker = new Worker('./worker.ts');
const bar: Comlink.Remote<Bar> = await new Comlink.wrap(worker);
const foo: Comlink.Remote<Foo> = await bar.makeFoo();

await bar.useFoo(foo);

Up until the last line there, everything works as expected: foo and bar on the main thread are proxies to Foo and Bar instances that live on the worker, respectively. The last line (await bar.useFoo(foo)) is where issues arise; the intention is for the proxy to get automatically unwrapped and to receive the unproxied Foo instance back on the worker side, but as-written this instead results in an error (obj is undefined).

Is there a way to achieve this within the bounds of what Comlink offers?

The alternative would be to never expose a proxied Foo to the main thread at all and instead rely on a layer of indirection, by assigning and returning unique IDs/handles to individual Foo instances created via makeFoo and passing those to useFoo. The main disadvantage of such an approach is the obvious complexity increase, especially as Foo‘s public API grows:

// with a proxy:
await foo.method1(arg1, arg2);
await foo.method2(arg1);
// with a handle:
await bar.fooMethod1(fooHandle, arg1, arg2);
await bar.fooMethod2(fooHandle, arg1);

calling right away a JavaScript from the backend

I want to call a JavaScript as soon as I am finished in backend in ASP.NET Web Form

 <table>
  <tr>
      <td>
           <asp:UpdatePanel ID="UpdatePanelSpin" runat="server"  UpdateMode="Conditional">
               <ContentTemplate>
                   <div id="spin">
                   </div>
               </ContentTemplate>
           </asp:UpdatePanel>
      </td>
      <td style="width:5px"></td>
       <td>
            <asp:Button ID="btnExecute" runat="server" ValidationGroup="btnExecute" OnClick="btnExecute_Click"
                Text="Execute" OnClientClick="spinStart();" />
       </td>
  </tr>

The JavaScript code

function spinStart() {
  console.log("Starting message");
  var target = document.getElementById('spin');
  var spinner = new Spinner(opts).spin(target);
}

function spinStop() {
   console.log("Done With sucess");
// does some stuff
}

at the backend

protected void btnExecute_Click(object sender, EventArgs e){
  // Do something
   CallMethod();
}

private void CallMethod()
{
  ScriptManager.RegisterStartupScript(this, this.GetType(), "spinStop", "spinStop();", true);
                       
}

spinStop is never called and I don’t have any message “Done With sucess” in the console but spinStart is called and the “Starting message” appears on the console.

I have replaced with

 ScriptManager.RegisterStartupScript(UpdatePanelSpin, UpdatePanelSpin.GetType(), "spinStop", "spinStop();", true);
 UpdatePanelSpin.Update()

but no success.
Any idea is appreciated.

PDF generation not working in production – Next.js

I have an error where my code isn’t executing the pdf generation function in production, but it’s working perfectly in development.
This is the error on the console:

https://firebasestorage.googleapis.com/v0/b/bcs-public-portal.appspot.com/o/profile-images%2F173926094730.jpg?alt=media&token=1d03014e-bc31-4c6b-b768-cc75566de55c’ from origin ‘https://uabcsptask1.vercel.app’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

This is my cors.json file:

[
  {
    "origin": ["http://localhost:3000", "https://uabcsptask1.vercel.app"],
    "method": ["GET"],
    "maxAgeSeconds": 3600
  }
]

Underlined text into PDF form filled by Oracle Analytics

I implemented an Oracle Analytics instance on Oracle OCI.
I have to manage a PDF form with several fields. I use the PDF form template directly, not an RTF template, because the structure is complex.

One of these fields needs to be underlined, but there is no field property to achieve this.
I tried implementing JavaScript to underline the text, but it is not executed.

if (!event.value) {
    event.target.fillColor = color.transparent;
    event.target.lineWidth = 0;
} else {
    event.target.strokeColor = color.black;
    event.target.borderStyle  = border.u;
    event.target.lineWidth = 1;
}

Do you have any ideas on how to underline the text in the field?

Thank you for your help.

How To Make A Github Game Multiplayer/Online [closed]

I Have Got A Github Game But I am trying To Make It So It Is Online/Multiplayer

what i mean by this is so people can play with each other

i would like to do this for free if possible

another thing i would like is to implement google analytics thx in advance code below

https://github.com/Darkoknight2009/gatdamn.io/tree/main

I expect people to play online together but that does not work at them moment 🙂

edit: this is a friends game who gave up and sold to me his server he set up was shut down and i want to restart this great game my knowledge on this kinda stuff is limited (i bought the rights to the game) i have tried reading through the code must stuff probably has to go but i don’t 100% understand it so i just need help restarting it all the mechanics work e.g moving shooting graphics works but only the online part does not work

Why does TypeScript throw an error when accessing errorCode on t.error in Angular?

I’m using Angular with @ngneat/query and RxJS to handle API requests. In my code, I throw an object containing an errorCode, but TypeScript complains that errorCode does not exist on t.error.

I have the following HTML:

<div *ngIf="todos | async as todos">
  <div *ngIf="todos.error">error code: {{ todos.error.errorCode }}</div>
</div>

And in my TypeScript code:

this.todos.subscribe((t) => {
  const errorCode = t.error?.errorCode; // TypeScript error here
});

Error:

NG9: Property 'errorCode' does not exist on type 'Error'.

Code Example

Here’s the full reproducible example:
StackBlitz

import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { of, tap } from 'rxjs';
import { injectQuery } from '@ngneat/query';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-root',
  imports: [CommonModule],
  template: `
    <div *ngIf="todos | async as todos">
      <div *ngIf="todos.error">error code: {{ todos.error.errorCode }}</div>
    </div>
  `,
})
export class App {
  #query = injectQuery();

  todos = this.#query({
    queryKey: ['todos'],
    queryFn: () =>
      of({ data: { status: 500 } }).pipe(
        tap((response) => {
          if (response.data.status === 500) {
            throw { errorCode: response.data.status };
          }
        })
      ),
  }).result$;

  ngOnInit() {
    this.todos.subscribe((t) => {
      const errorCode = t.error?.errorCode; // TypeScript error here
    });
  }
}

bootstrapApplication(App);

What I’ve Tried

  • I verified that the error is indeed an object ({ errorCode: number }) when thrown.
  • TypeScript seems to assume t.error is of type Error, which doesn’t have errorCode.

Why is TypeScript treating t.error as Error, and how can I correctly type it so that errorCode is recognized?

Share mongoose connection between repositories in a TypeScript monorepo

My MonoRepo structure

A high level diagram of my monorepo

Intent: I want to bring out database from app1 and app2 level and put it to common’s database folder. So app1 and app2 or appN will pass on the connection string and the class from shared repo will establish the connection to DB.

Problem: If I bring out this db connecting to common it’s not loading models in app1 and app2. I can see the value of readyState: 1, which means mongo is connected but, I’m not sure why it’s not loading models.

I’m not using Lerna or NX. it’s simple TS project. Every project has tsConfig and package.json but all common codes/services are in common folder. This mono repo contains only backend code.

Now the simple way I’m connecting to DB from individual app level is like below,

const dbConnectionConfig = {
    url: MONGO_URI ?? '',
    options: {
        dbName: MASTER_DATABASE_NAME,
    },
};

export class Database {
    private static instance: Database;
    private isConnected: boolean = false;
    private constructor() {}
    public static async getInstance(): Promise<Database> {
        if (!Database.instance) {
            Database.instance = new Database();
            await Database.instance.establishConnection();
        }
        return Database.instance;
    }
    private async establishConnection(): Promise<void> {
        if (this.isConnected) return;
        try {
            if (NODE_ENV !== 'production') { set('debug', true) }
            await connect(dbConnectionConfig.url, dbConnectionConfig.options);
            this.isConnected = true;
        } catch (err) {
            throw err;
        }
    }
}

and in app.ts in app1 and app2 folder I’m doing like this

    public static getInstance({ routes = [] }: { routes?: IRoute[] } = {}): App {
        if (!App.instance) {
            App.instance = new App(routes);
            Database.getInstance().catch((err) => {
                logger.error('Database connection failed', err);
                process.exit(1);
            });
        }
        return App.instance;
    }

I’m following repository pattern, in common I’m keeping base repository and base models like below,

export class BaseRepository<T> implements IBaseRepository<T> {
    private model: Model<T>;
    constructor(model: Model<T>) { this.model = model }
    async findAll(query: any): Promise<T[]> { return this.model.find(query) };
}

and

export class BaseSchema<T extends { [key: string]: any } = any> extends Schema {
    constructor(schema: Record<string, any> = {}) {
        const baseFields = {
            isDeleted: { type: SchemaTypes.Boolean, required: true, default: false },
            createdBy: { type: SchemaTypes.String, required: false },
            updatedBy: { type: SchemaTypes.String, required: false },
        };
        const combinedSchema = { ...baseFields, ...schema };
        super(combinedSchema, { timestamps: true, discriminatorKey: 'kind' });
    }
}

this is how I’m extending these classes to app1, app2

interface XRepositoryInterface {}
export class XRepository extends BaseRepository<IX> implements XRepositoryInterface {
    constructor() {
        super(XModel);
    }
}

and

const XSchema = new BaseSchema<IX>({
    userId: { type: SchemaTypes.String, ref: 'user', required: true },
    version: { type: SchemaTypes.String, required: false },
});
export const XModel = model<IX>(COLLECTION_NAME.X, XSchema);

Can anyone please help me with this?

Slick slider with color swatches – multiple sliders?

I’m trying to mimmick the behaviour seen on this page: https://www.mvagusta.com/gb/en/product/rush/1000

I’m using Ken Wheeler’s Slick Slider, as the original page uses that.

A slider is used to view the motorbike at different angles. This is a standard slider. However you also have the option to choose the color theme of the motorbike using the dots beneath the slider. Selecting a different color seems to load an alternate slider with a different set of images, with the same angle of the bike still showing.

How would one achieve this using the Slick Slider?

Javascript/React – TypeError: Cannot read properties of undefined (reading ‘map’)

This is from a tutorial. I am not a very experienced developer in Javascript. Starting on React.

The app.js with the initialization and call to the component:

function App() {
  const [movies, setMovies] = useState([]);
  const [watchlist, setWatchlist] = useState([]);

  useEffect(() => {
    fetch("movies.json")
      .then((response) => response.json())
      .then((data) => setMovies(data));
  }, []);

  const toggleWatchlist = (movieId) => {
    setWatchlist((prev) =>
      prev.includes(movieId)
        ? prev.filter((id) => id !== movieId)
        : [...prev, movieId]
    );
  };

  return (
    <div className="App">
      <div className="container">
        <Header></Header>

        <Router>
          <nav>
            <ul>
              <li>
                <Link to="/">Home</Link>
              </li>
              <li>
                <Link to="/watchlist">Watchlist</Link>
              </li>
            </ul>
          </nav>
          <Routes>
            <Route
              path="/"
              element={
                <MoviesGrid
                  movies={movies}
                  watchlist={watchlist}
                  toggleWatchlist={toggleWatchlist}
                />
              }
            ></Route>
            <Route
              path="/watchlist"
              element={
                <WatchList
                  movies={movies}
                  watchlist={watchlist}
                  toggleWatchlist={toggleWatchlist}
                />
              }
            ></Route>
          </Routes>
        </Router>
      </div>

      <Footer></Footer>
    </div>
  );
}

export default App;

The component:

export default function WatchList(movies, watchlist, toggleWatchlist) {
  return (
    <div>
      <h1 className="title">Your Watchlist</h1>
      <div className="watchlist">
        {watchlist.map((id) => {
          const movie = movies.find((movie) => movie.id === id);
          return (
            <MovieCard
              key={id}
              movie={movie}
              toggleWatchlist={toggleWatchlist}
              isWatchlisted={true}
            ></MovieCard>
          );
        })}
      </div>
    </div>
  );
}

With ‘watchlist.map’ I get:

[![Output eror][1]]https://i.sstatic.net/9QDW85BK.png

With ‘watchlist?.map’ this is output of the DevTools:

[![Dev Tools output][2]]https://i.sstatic.net/2fQr0HpM.png

‘watchlist’ looks defined to me with 2 elements, but no movie cards are being displayed.

Based on my researched on this error:

  • Verified ‘useState’ initializes the array to an empty array.

What I tried:

  • Changed the watchlist parameter name.
  • Added ‘watchlist &&’ before the ‘watchlist.map’

Why is watchlist undefined?
[1]: https://i.sstatic.net/9QDW85BK.png
[2]: https://i.sstatic.net/2fQr0HpM.png