TypeError: (intermediate value) is not iterable Sequelize findOrCreate

I am facing some issues using findOrCreate together with sequelize. I tried to apply the code bellow in order to catch sequelize errors and make sure the user transaction works.

const { User } = require('../models/user');
const { ValidationError, Sequelize } = require('sequelize');
const { getSequelizeErrorObject } = require('../utils/functions');

const registerController = async (req, res) => {
  const queryCondition = {
    where: Sequelize.or(
      { username: req.body.username },
      { email: req.body.email },
    ),
    defaults: {
      username: req.body.username,
      email: req.body.email,
      password: req.body.password,
    },
  };

  const [user, userCreated] = await User.findOrCreate(queryCondition).catch(
    (err) => {
      if (err instanceof ValidationError) {
        const sequelizeError = getSequelizeErrorObject(err);
        return res.status(400).send(sequelizeError);
      }

      return res.status(500).send({
        message: 'Something went wrong when trying to process the request',
      });
    },
  );

  if (userCreated) {
    const { username, email, id } = user;
    return res.status(200).json({ username, email, id });
  }

  return res.status(400).send({
    message:
      'The email/username are already associated within the app, try to sign in instead',
  });
};

module.exports = registerController;

I am getting this error:



TypeError: (intermediate value) is not iterable
    at registerController (C:UsersfilipDesktopProjectselfmetterservercontrollersregisterController.js:18:31)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

It just happens if I send this kind of data (that hits the sequelize validation):

"email": "",
"password": "m",
"username": ""

Tried to also use the promise chain (.then, .catch) but would like to avoid that if possible.

also tried to add a try catch block around the whole thing, but the error was the following:

Error: Can’t set headers after they are sent to the client

Any help with this? (The docs are not very clear on how to handle things with sequelize)

Thanks a lot, appreciated!

How to change select option value while loading dropdown>?

I have long text for each item but I want to set substring the value for the text while loading the select dropdown.

I tried this but not working.

  <select class="form-control chosen-select" id="eventCode" name="eventCode" >
  @foreach (var item in ViewBag.Events)
  {
      <option value="getEventCode(@item)">@item</option>
  }

script

 <script type="text/javascript">
    
function getEventCode(eventCodeStr) {

    let eventCode = eventCodeStr.substring(0, eventCodeStr.indexOf("("));
    alet(eventCode);
    return eventCode;
}
</script>

text example is this 18AA10 (Smarter Well Integrity 5/7/2018) and I need to get value 18AA10. How to do this?

Dreamlandjs – Text on page not updating when stateful value changes

I am using dreamland.js to write a simple application. I expect the text in the “preview” section to update when I set the value in state, but it’s not updating despite the value clearly being changed. Code is below

import "dreamland/dev";

let state = stateful({
    currentText: ""
})

function Editor() {
  return (
    <div id="editor">
      <textarea
        value={state.currentText}
        on:input={(e: InputEvent) => {
          state.currentText = e.target!.value
          console.log(state.currentText)
        }}
        autofocus
      />
      <div id="preview">
        {state.currentText}
      </div>
    </div>
  )
}

function MainApp() {
  return (
    <div id="app">
      <Editor />
    </div>
  )
}

window.addEventListener('load', () => {
  document.body.appendChild(<MainApp />)
})

Get notified when a person sees your Instagram story [closed]

does anyone know a script preferably Tampermonkey script which check people who see your story and if a specific person sees it to sent you a notification? Is that even possible? I have tried to do this but for me with my lack of knowledge on js I couldn’t manage to even get if the person saw it and then to even get a notification.

I am using:

Opera One (version: 111.0.5138.0) (arm64)

Opera is up to date Update

Update stream: developer

System: macOS Version 14.5 (Build 23F5059e) 14.5.0 arm64

Chromium version: 124.0.6356.6

And Mac mini, Sonoma 14.5 Beta (23F5059e)

Here is the script I tried:

// ==UserScript==
// @name         Instagram Story Notifier
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Notify when a specific person views your Instagram story
// @author       You
// @match        https://www.instagram.com/*
// @grant        none
// ==/UserScript==

console.log('Instagram Story Notifier script loaded');

(function() {
  'use strict';
  const targetUsers = ['usr1', 'usr2', 'usr3']; // Add the usernames you want to monitor
  const notificationMessage = 'Someone viewed your story';

  const observer = new MutationObserver(() => {
    const storyViewsContainer = document.querySelector('div[role="dialog"] ul li');
    if (storyViewsContainer) {
      console.log('Story views container found!');
      checkStoryViews();
      observer.disconnect(); // stop observing
    }
  });

  observer.observe(document.body, {
    childList: true,
    subtree: true
  });

  function checkStoryViews() {
    console.log('Checking story views...');
    const viewers = Array.prototype.slice.call(storyViewsContainer.children);
    const viewerUsernames = viewers.map(viewer => viewer.querySelector('span').textContent);
    console.log('Viewers:', viewerUsernames);

    targetUsers.forEach(targetUser => {
      if (viewerUsernames.includes(targetUser)) {
        console.log(`Target user ${targetUser} found`);
        notify(targetUser);
      } else {
        console.log(`Target user ${targetUser} not found`);
      }
    });
  }

  function notify(username) {
    alert(`${username} viewed your story`);
  }
})();

TypeError: window.Razorpay is not a constructor

I’m trying to intergrate RazorPay to my react app but it is throwing below error:

Error screenshot

code:

import TshirtImg from "./tshirt.jpg";
// import Razorpay from 'razorpay';
function Product() {
  const amount = 500;
  const currency = "INR";
  const receiptId = "qwsaq1";

  const paymentHandler = async (e) => {
    const response = await fetch("http://localhost:5000/order", {
      method: "POST",
      body: JSON.stringify({
        amount,
        currency,
        receipt: receiptId,
      }),
      headers: {
        "Content-Type": "application/json",
      },
    });
    const order = await response.json();
    console.log(order);

    var options = {
      key: process.env.KEY_ID, // Enter the Key ID generated from the Dashboard
      amount, // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise
      currency,
      name: "Acme Corp", //your business name
      description: "Test Transaction",
      image: "https://example.com/your_logo",
      order_id: order.id, //This is a sample Order ID. Pass the `id` obtained in the response of Step 1
      handler: async function (response) {
        const body = {
          ...response,
        };

        const validateRes = await fetch(
          "http://localhost:5000/order/validate",
          {
            method: "POST",
            body: JSON.stringify(body),
            headers: {
              "Content-Type": "application/json",
            },
          }
        );
        const jsonRes = await validateRes.json();
        console.log(jsonRes);
      },
      prefill: {
        //We recommend using the prefill parameter to auto-fill customer's contact information, especially their phone number
        name: "Web Dev Matrix", //your customer's name
        email: "[email protected]",
        contact: "9000000000", //Provide the customer's phone number for better conversion rates
      },
      notes: {
        address: "Razorpay Corporate Office",
      },
      theme: {
        color: "#3399cc",
      },
    };
    var rzp1 = new window.Razorpay(options);
    rzp1.on("payment.failed", function (response) {
      alert(response.error.code);
      alert(response.error.description);
      alert(response.error.source);
      alert(response.error.step);
      alert(response.error.reason);
      alert(response.error.metadata.order_id);
      alert(response.error.metadata.payment_id);
    });
    rzp1.open();
    e.preventDefault();
  };

  return (
    <div className="product">
      <h2>Tshirt</h2>
      <p>Solid blue cotton Tshirt</p>
      <img src={TshirtImg} />
      <br />
      <button onClick={paymentHandler}>Pay</button>
    </div>
  );
}

export default Product;

When I tried importing razorpay module in above code then it is throwing below error:

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
– add a fallback ‘resolve.fallback: { “url”: require.resolve(“url/”) }’
– install ‘url’
If you don’t want to include a polyfill, you can use an empty module like this:
resolve.fallback: { “url”: false }

Razor pay error

How to overcome the findings from PageSpeed Insights provided by Google

How to overcome the findings from PageSpeed Insights provided by Google, regarding problems found but not yet resolved.

Browser errors were logged to the console
Errors logged to the console indicate unresolved problems. They can come from network request failures and other browser concerns. Learn more about this errors in console diagnostic audit

enter image description here

https://wwww.mscengineeringgre.com/

Is there a way to validate react dropzone files using zod schema react react hook form

am using shadcn Form that uses react hook form, zod for validation and react dropzone together to validate my input before i submit a form.

below is the schema am using and how am mounting the component:

in The Validations

import { z } from "zod";
export const myFormSchema = z.object({
   images: z
    .custom<File>(),
  title: z.string(),
});

and here is my dropzone component

import { FileWithPath, useDropzone } from "react-dropzone";
import { useState, useCallback } from "react";
import Image from "next/image";
import { Upload } from "lucide-react";

type FileUploaderProps = {
  fieldChange: (FILES: File[]) => void;
  mediaUrl: string[] | null;
};

const FileUploader = ({ fieldChange, mediaUrl }: FileUploaderProps) => {
  const [fileUrl, setFileUrl] = useState<string[] | null>(mediaUrl);

  const onDrop = useCallback(
    (acceptedFiles: FileWithPath[]) => {
      fieldChange(acceptedFiles);
      const urls = acceptedFiles.map((file) => URL.createObjectURL(file));
      setFileUrl(urls);
    },
    [fieldChange],
  );
  const { getRootProps, getInputProps } = useDropzone({
    onDrop,
    accept: {
      "image/*": [".png", ".jpeg", ".jpg", ".svg"],
    },
  });

  return (
    <div
      {...getRootProps()}
      className="flex-center bg-dark-3 flex cursor-pointer flex-col rounded-xl"
    >
      <input {...getInputProps()} className="cursor-pointer" />
      {fileUrl ? (
        <>
          <div className="grid grid-cols-3 gap-2">
            {fileUrl.map((image, index) => (
              <button key={index}>
                <Image
                  alt="Product image"
                  className="aspect-square w-full rounded-md object-cover"
                  height="84"
                  src={image}
                  width="84"
                />
              </button>
            ))}
          </div>
          <p className="mt-10 text-center">Click or drag photo to replace</p>
        </>
      ) : (
        <div className="mt-2 grid grid-cols-3 gap-2">
          <button className="flex aspect-square w-full items-center justify-center rounded-md border border-dashed shadow">
            <Upload className="h-4 w-4 text-muted-foreground" />
            <span className="sr-only">Upload</span>
          </button>
        </div>
      )}
    </div>
  );
};

export default FileUploader;

here is my Form Component that connects them all here am using shadcn ui form to validate that the dropzone is not empty and it must show error if user tries to submit it without selecting images but the validations are not working:

'use client';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { Button } from '@/components/ui/button';
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';

import FileUploader from '../shared/FileUploader';
import Link from 'next/link';

const InfoForm = () => {
  // 1. Form Validation
  const form = useForm<z.infer<typeof myFormSchema>>({
    resolver: zodResolver(myFormSchema),
    defaultValues: {},
  });

  // 2. Form Submission
  async function onSubmit(values: z.infer<typeof myFormSchema>) {
    // Do something with the form values.
    // ✅ This will be type-safe and validated.

    console.log('work submitted');
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
        <FormField
          control={form.control}
          name="title"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Title</FormLabel>
              <FormControl>
                <Input placeholder="" {...field} />
              </FormControl>
              <FormDescription>
                Mention the key features of your item (e.g. brand, model, age,
                type)
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="images"
          render={({ field }) => (
            <FormItem>
              <FormLabel>UPLOAD UP TO 20 PHOTOS</FormLabel>
              <FormControl>
                <FileUploader fieldChange={field.onChange} mediaUrl={null} />
                {/* <Input id="picture" type="file" {...field} /> */}
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <div className="flex justify-between">
          <Link href="/">
            <Button variant="outline">Cancel</Button>
          </Link>
          <Button>Post</Button>
        </div>
      </form>
    </Form>
  );
};

export default InfoForm;

am i doing something wrong here? also excuse me as i am new to using react, nextjs and coding in general.

dropdown select option value codeigniter 4

Good evening, I’m new to codeigniter 4 and I want to make an application.
I can’t make a dropdown select option value, can you help me?

I have the structure that I have been struggling with for several hours to understand how it works

appModulesTaskModelsClientModel.php

namespace AppModels;

class ClientModel extends BaseModel
{
    protected $table = 'client';
    protected $primaryKey = 'id_client';
    protected $allowedFields = [
        'cl_first_name',
        'cl_last_name',
        'cl_name_company',
        'cl_logo_img',
        'cl_addres',
        'cl_banck_name',
        'cl_banck_id_number',
        'cl_data_add',
        'cl_data_mdf'
    ];
    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
}

appModulesTaskControllersTask.php

namespace AppModulesTaskControllers;

use AppControllersBaseController;
use AppModulesTaskModelsTaskModel;
use AppModulesTaskModelsClientModel;

/**
 * Class Task
 */
class Task extends BaseController
{
    private $task_model;
    private $client_model;

    function __construct()
    {
        $this->task_model = new TaskModel();
        $this->client_model = new ClientModel();
    }

    public function index() {
        
        
        $data['client'] = $this->client_model->select('id_client,cl_first_name,cl_last_name,cl_name_company,cl_logo_img,cl_addres,cl_banck_name,cl_banck_id_number')->findAll();
    

appModulesTaskViewstaskform.php

<div class="col-md-12">
                                        <div class="form-group">
                                            <label for="client" class="text-dark">Client</label>
                                            <?php $id_select = (isset($obj)) ? $obj['id_client'] : set_value('cl_first_name');?>
                                                            <select name="client" id="client" class="form-control">
                                                                <?php foreach($client??[] as $item): ?>
                                                                    <?php if ($item['type'] == "backend") : ?>
                                                                        <option value="<?=$item['cl_first_name']?>" <?= $id_select == $item['cl_first_name'] ? 'selected' : '' ?>><?=$item['id_client']?></option>
                                                                    <?php endif; ?>
                                                                <?php endforeach; ?>
                                                            </select>

                                       </div>
                                    </div>
                                    

<!-- Form -->
<script>
    $(document).ready(function () {
        "use strict";
        $('#title').focus();
         $("#client").select2();
    });
</script>

Make oneClick electron app for updates but not for first installation do it from second install

I’m trying to update my electron app on windows with electron-updater.

It all works except when the updater is running, it first asks the users where does he want to install the software and if the install is meant to be per machine or per user.

I do want these questions to be asked when running the installer for the first time, so my electron-builder.json nsis field look like this:

"build": {
        "appId": "com.shuv.oniyama",
        "productName": "Oniyama",
        "directories": {
            "output": "dist"
        },
        "win": {
            "target": [
                "nsis"
            ],
            "icon": "./src/logo/logo.ico"
        },
        "nsis": {
            "oneClick": false,
            "allowToChangeInstallationDirectory": true,
            "installerIcon": "./src/logo/logo.ico",
            "uninstallerIcon": "./src/logo/logo.ico",
            "createDesktopShortcut": true,
            "createStartMenuShortcut": true,
            "shortcutName": "Oniyama"
        }
    }

But I definitely don’t want them when it’s about updating, the app should detect it has already been installed and not ask anything.

Is there any way to achieve this? (preferably other than having two separate installers, one for the updates and one for the installations)

autoUpdater.autoInstallOnAppQuit = true;

i want to use this and not just the quitAndInstall() method

Is it possible to have a multi-form in a Modal form?

I’m new at programming. I’ve been tasked to develop a website as a final requirements for my database management class. Now i wanna try doing this multi-step form in my website and yes it might be an unnecessary problem but its the one I’m going with. I already have a form however when i tried working on my modal, the form doesn’t get into the modal. I don’t know what to do and I’m stuck. I still don’t know how to put my codes in here tho. Thanks

Multi-step form inside a modal

Store Money and pay Users/Customer using Stripe using Node.js

My problem is:
I am creating something like the Twitch Donation System where Users buy Credits and pay other with the Credits. The Person who gets paid with the credits should be able to transfer the credits to Dollars and send them to the person’s bank account.

I searched though the Stripe API but I only found how the Owner can cash out the money that the users spend and not how the users can cash out the money. Please let me know how this works or if this is even legal or if I should use another API.

Unable to do 2 Firestore updates at once

Is it required to do a batch update? The “emails” collection will not update. If I do a console.log, it does know what the uid and email are. It also knows there is one record in the “emails” collection. It also updates the “users” collection.

I tried making a second db reference as db2, which did not work.

If I put the “users” update above the “emails” update, the “users” updates but “emails” does not. If I put “emails” above “users”, neither update because “emails” fails to update.

async function setupNewUserInFirestore2(uid, email) {
  try {  

    let date = new Date('2000-01-01T12:00:00');
    const timestamp = date.getTime();
    const unixTimestamp = timestamp / 1000;

    const usersRef = collection(db, "users");
    await setDoc(doc(usersRef, uid), {
      usernameLastUpdated: unixTimestamp, 
      xVerEmailSent: 1
    })        

    const emailsRef = collection(db, "emails");        
    await setDoc(doc(emailsRef, email), {
      uid: uid
    }) 

  } catch (e) {
    console.error("Error adding users document: ", e);
  }

Yesterday I asked if it was necessary to check for duplicate emails when using “verifyBeforeUpdateEmail” and someone commented saying the question wasn’t clear. It was very clear and the answer to that one is YES you do because Google won’t send the email if it’s a dupicate and they don’t bother to give you an error because of it. And that’s why I’m working on this today.

"emails" collection
"users" and "emails" are right there together in the db

How do I generate new text when clicking a button in html/javascript?

I am trying to create a button where every time you click, a new sentence generates from a list. What I have now is only generating a new sentence when I refresh the page and I’m not sure what to try. I only started learning yesterday so be nice to me please.

Here is what I have so far.

<div>
    <button onclick="button" id="myButton">Hit me.</button>
    <p id="randomQuote"> </p>
</div>

<script>

    var quote = ["S1","S2","S3","S4",  ];

    var randomQuote = Math.floor(Math.random() * quote.length);
    document.getElementById("randomQuote").innerHTML = quote[randomQuote];

</script>