How can I make photopea.com offline?

Https://www.photopea.com
I have tried to download this website with httrack. Also used plugin in webstore. But I can’t run it properly in (offline) html viewer. So how can I download it and make it offline?

Already tried Httrack and Save all resources plugin.

Uncaught (in promise) FirebaseError: Missing or insufficient permissions when trying to update collection

i am createing a microblogging app using firebase firestore and im getting this error

`const handleNewPostSubmit = async (e) => {
e.preventDefault();

const createdAt = new Date().toISOString();

await firestore.collection('posts').add({
  text: newPostText,
  createdAt,
});`

this is the code i used but i get the error Uncaught (in promise) FirebaseError: Missing or insufficient permissions.

and im also getting the warning
[2023-02-24T03:48:58.451Z] @firebase/firestore: Firestore (9.17.1): Uncaught Error in snapshot listener: FirebaseError: [code=permission-denied]: Missing or insufficient permissions

i wanted this to create a collections posts and add the new post to it

Line break in react text area being treated as space wrongly and can be removed with trim()

I have a text area like below which I try to remove the leading and trailing spaces of the string but I want to include the number of new line charactor in the string.

const [textValue, setTextValue] = useState('')

const onChangeValue= ({target: {value}}) => {
    console.log(value.length);
    console.log(value.trim().length);
    setTextValue(value);
};

<textarea
     onChange={onChangeValue}
     noAutoResize
     width={'100%'}
     height={'15em'}
     value={textValue}
     maxLength={maxLength}
/>

If I keep pressing the enter button on the textArea to add line breaks, the value.length keep increasing but value.trim().length always remains in 0.

According to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim, the trim() method removes whitespace only

Why it it also remove my line break? Is there any way to achieve such requirement?

unexpected behaviors on classes when testing with jest

I’m working on some tests on my project, and have run in to some weird behaviors.

My code looks something like this:

export class Variable {
  b;

  constructor() {
    this.b = 'B';
  }

  changeValue = () => {
    this.b = 'changed B';
  };
}

export class DerivedVariable {
  v;

  constructor(v: Variable[]) {
    this.v = v;
  }
}

export class Store {
  a;

  v;

  initialize = () => {
    this.a = new Variable();
  };

  get computedValue() {
    return [this.a];
  }

  get computedInstances() {
    return new DerivedVariable(this.computedValue);
  }
}

and my test code:

test('test', () => {
    const { a, computedValue, computedInstances, initialize } = new Store();

    initialize();

    expect(computedValue[0].b).toBe('B');

    computedValue[0].changeValue();

    expect(a.b).toBe('changed B');

    expect(computedInstances.v[0].b).toBe('changed B');
  });

I figured running the initialize function would populate the class variable, which would allow the test to pass.

However, the results of the test returns something like:

 TypeError: Cannot read properties of undefined (reading 'b')

      24 |     initialize();
      25 |
    > 26 |     expect(computedValue[0].b).toBe('B');

Does jest have an asynchronous behavior when it comes to creating class instances?

Thanks in advance.

  • On a side note, I’ve run into a similar issue when testing with class variables after calling a function that mutates it, I assume the two issues are related.

Load images using webs urls with js

First of all I would like to inform that I’m very very new to JavaScript, I’ve been working on a super simple generator, basically all I want is to load an image from a random website on my html page using a form structure, using just vanilla JavaScript… I thought it was going to be easy but I cant seem to figure it out… This the code I’ve been working on:

document.getElementById(“byForm”).addEventListener(‘submit’, function(event) {

event.preventDefault();

let imageUrl = document.getElementById("imageLink").value;

let img = new Image();

img.src = imageUrl;

img.onload = function() {
    document.getElementById("imageContainer").appendChild(img);
};

})

The code above is the climax of several attempts that I’ve been trying on for the past few hours, created a div below the form application where the images are supposed to load in but nothing is happening. also the “imageLink” is the type=url id that i gave it. Can someone explain to me the correct way of doing this or if I’m missing something? Thanks!

javascript could not find the tr element

I visited a private website, and I want to retrieve the content of a tr element. However, document.querySelector("tr") cannot obtain the content even though I cached the page and confirmed that the tr element exists by opening the text file. Furthermore, even when I opened the cached page in the browser, I still couldn’t get the result. Why is this?

[webpack.cache.PackFileCacheStrategy] Caching failed for pack: TypeError: Cannot read properties of undefined (reading ‘length’)

We develop apps in Next.js and Node.js.
During the development phase, I get this error on the client side.
Is there a solution?

** [webpack.cache.PackFileCacheStrategy] Caching failed for pack: TypeError: Cannot read properties of undefined (reading ‘length’)
**

enter image description here
I think I got this error around the time I touched the JSX CSS, but I don’t actually know if it’s related because this error appears even after removing JSX.

I am not using the length variable from where I worked again. So why does it say this is unreadable?
enter image description here

I have commented out or deleted the area I worked on, but nothing has changed. I have a feeling it is something else.

GET http://localhost:9000/model/data.json 404 (Not Found)

That is my diretory path

I’m running npm server on http://localhost:9000/ to use cytoscape module. But my server can’t find my json file. What’s wrong with my code?

my index.js file source code.

import './favicon.ico';
import '../model/data.json';



fetch('../model/data.json', { mode: 'no-cors' })
    .then(function (res) {
        return res.json();
    })
    .then(function (data) {
        console.log(data);
});

my webpack.config.js file source code.

const path = require("path");
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");


module.exports = {
  entry: "./src/index.js",
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname + "/build")
  },
  devServer: {
    static: {
      directory: path.join(__dirname, 'public'),
    },
    compress: true,
    port: 9000,
  },
  mode: "none",
  module: {
    rules: [
      {
        test: /.(js|jsx)$/,
        exclude: "/node_modules",
        use: ['babel-loader'],
      },
      {
        test: /.html$/,
        use: [
          {
            loader: "html-loader",
            options: { minimize: true }
          }
        ]
      },
      {
        test: /.css$/,
        use: [MiniCssExtractPlugin.loader,'css-loader']
      }
    ]
  },
  plugins: [
    new HtmlWebPackPlugin({
      template: './public/index.html',
      filename: 'index.html'
    }),
    new MiniCssExtractPlugin({
      filename: 'style.css'
    }),
    new CleanWebpackPlugin()
  ]
};

I want my server to find data.json file…

Trouble with php on express js

I am trying to get php working on my express js website using the php-express module. Unfortunatly, from what I’ve gathered and tried from what I could find online, I get the following error:

Error: Command failed: php mysitedirnode_modulesphp-expresslibPHPExpress/../../page_runner.php mysitedirStorage mysitedirStorageget_video_info.php
‘php’ is not recognized as an internal or external command,
operable program or batch file.

Here are some snippets from my express.js file:

var phpExpress = require('php-express')({
    binPath: 'php'
});
app.engine('php', phpExpress.engine);
app.all(/.+.php$/, phpExpress.router);

And then in my route for /get_video_info.php:

app.route("/")
    .all(async (req, res) => {
        console.log("weee");
        return await res.render(path.resolve('Storage','get_video_info.php'));
});

I need help changing the resquest to the Open AI API from singular to stream

I’m having a problem that most of the resquest I do are taking gateway timeout. I found that one way to avoid this is by using the ‘stream: true’ when making the request.
But that’s the only part I know. I’m saving the messages on firebase so I would have to make a big change to the code to be able to make this all work, can someone help me with some way for me to follow at least?

My codes:

import admin from 'firebase-admin'
import query from '../../lib/queryApi'
import { adminDb } from '../api/db/firebase-admin'
import type { NextApiRequest, NextApiResponse } from 'next'

type Data = {
    answer: string
}

export default async function handler(
    req: NextApiRequest,
    res: NextApiResponse<Data>
){
    const {prompt, id, user} = req.body

    // ChatGPT

    const response = await query(prompt, id, user)

    const message: Message = {
        text: response || "error",
        createdAt: admin.firestore.Timestamp.now(),
        user: {
            _id: "bot",
            name: "bot",
            avatar: 'any'
        },
    }


    await adminDb
        .collection("conversations")
        .doc(user.email)
        .collection("chats")
        .doc(id)
        .collection("messages")
        .add(message)

    res.status(200).json({ answer: message.text })
}
const query = async (prompt, _id, _user) => {
    const res = await openai.createCompletion({
        model: 'text-davinci-003',
        prompt,
        temperature: 0.3,
        max_tokens: 1000,
        frequency_penalty: 0.5,
        presence_penalty: 0,
        stream: true,
    })
    .then(res => res.data.choices[0].text)
    .catch(
        (err) => 
        `Something happened(Error: ${err.message})`
    )

    return res
}

export default query

My codes to display messages

'use client'
import Message from "./Message"
import { useEffect, useRef } from "react" 
import { ArrowSquareDown } from "phosphor-react"
import { db } from "../../pages/api/db/firebase-config"
import { useUserContext } from "../../app/context/userContext"
import { useCollection } from "react-firebase-hooks/firestore"
import { collection, orderBy, query } from "firebase/firestore"

function Chat({ id }) {
    const { user } = useUserContext()
    
    const [messages] = useCollection(
        user && query(
            collection(db, "conversations", user.email, "chats", id, "messages"),
            orderBy("createdAt", 'asc')
        )
    )

    const messagesEndRef = useRef(null);

    useEffect(() => {
        messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }, [messages]);

    return (
        <div className="flex-1 overflow-y-auto overflow-x-hidden" >
            {messages?.empty && (
                <>
                    <p className="mt-96 text-center text-white font-mont" >
                        Escreva uma pergunta para começar!
                    </p>
                    <ArrowSquareDown className="h-10 w-10 mx-auto mt-5 text-white" />
                </>
            )}
            {messages?.docs.map((message, index) => (
                <Message key={message.id} message={message.data()} isLastMessage={index === messages.docs.length - 1}/>
            ))}
            <div ref={messagesEndRef} />
        </div>
    )
}

export default Chat
import { DocumentData } from "firebase/firestore"

type Props = {
    message: DocumentData
    isLastMessage: boolean
}

function Message({ message}: Props) {
    const isChatGPT = message.user.name === "bot"
    const formattedText = new String(message.text).trimStart().replace(/n/g, '<br>');
    
    return (
        <div className={`py-5 text-white ${isChatGPT && "bg-[#434654]"}`} >
            <div className="flex space-x-5 max-w-2xl mx-auto" >
                <img src={message.user.avatar} alt="" className="h-8 w-8 rounded" />
                <p className='pt-1 text-sm font-mont' dangerouslySetInnerHTML={{__html: formattedText}} />
            </div>
        </div>
    )
}

export default Message

Use Quokka with Vite and NodeJS 19?

I am trying to use the Quokka VSCode extension in a vite app and I keep getting the following error.

​​​​​Quokka PRO ‘App.jsx’ (node: v19.6.0)​​​​   Only URLs with a
scheme in: file and data are supported by the default ESM loader. On
Windows, absolute paths must be valid file:// URLs. Received protocol
‘d:’

I am running Quokkajs start on current file on my app.jsx file but no luck. It works on .js files and it works in create-react-app.

I am not really sure what is going on. On Quokka’s website it says to use with vite you need to install the node-vite package so I did. But no luck. Does anyone know what is going on here?

async nodemailer sendmail Promise

how can I get a ‘then’, or asynchronously return an API response?
I use fastify, but it doesn’t wait for a response if you make a callback inside.
I tried that, but the error: TypeError: a.then is not a function

         const a = await transporter.sendMail(mainOptions);
            a.then((error, result) => {
                if (error) return error
                reply.send({
                  messageId: result.messageId
                })
            })

Tablesorter JS Math widget Ignore empty cells

We have table sorter JS running and it works great, however the count function is counting all cells in the column not just those with data.

Is there a way to configure the count function to ignore empty cells?

The 3rd column should be 0 not 24

$(".sortableTable-totalsRow").tablesorter({
    theme: "bootstrap",
    widgets: ['filter', 'math'],
    widgetOptions: {
        math_data: 'math', // data-math attribute
        math_ignore: [0, 1, ''],
        math_textAttr: '',
        math_none: 'N/A', // no matching math elements found (text added to cell)
        math_complete: function ($cell, wo, result, value, array)
        {
            var textClass = $cell.attr('data-math-textAttr');
            if (textClass == undefined)
            {
                textClass = "align-right";
            }
            var txt = '<span class="' + textClass + '" >' +
                (value === wo.math_none ? '' : ' ') +
                result + '</span>';
            if ($cell.attr('data-math') === 'all-sum') {
                // when the "all-sum" is processed, add a count to the end
                return txt + ' (Sum of ' + array.length + ' cells)';
            }
            return txt;
        },
        math_completed: function (c) {
            // called after all math calculations have completed
        },
        // cell data-attribute containing the math value to use (added v2.31.1)
        // see "Mask Examples" section
        math_mask: '##0.00',
        math_prefix: '', // custom string added before the math_mask value (usually HTML)
        math_suffix: '', // custom string added after the math_mask value
        // event triggered on the table which makes the math widget update all data-math cells (default shown)
        math_event: 'recalculate',
        // math calculation priorities (default shown)... rows are first, then column above/below,
        // then entire column, and lastly "all" which is not included because it should always be last
        math_priority: ['above', 'below', 'col', 'row'],
        // set row filter to limit which table rows are included in the calculation (v2.25.0)
        // e.g. math_rowFilter : ':visible:not(.filtered)' (default behavior when math_rowFilter isn't set)
        // or math_rowFilter : ':visible'; default is an empty string
        math_rowFilter: ''
    }
});



<tfoot class="sticky-bottom">
    <tr style="border-top: double">
        @for (int i = 0; i < (Model.Heading.Count() - 2); i++)
        {
            <th class="text-center" data-math="col-count" data-math-mask="#,###.00">col-count</th>
            <th class="text-right" data-math="col-sum" data-math-mask="#,##0.00">col-sum</th>
        }

    </tr>
</tfoot>

enter image description here

Why is a class field not updated when its function is called by another class? [duplicate]

I’m not sure why this code is not working. The Receiver class instance does not return any messages.

const runExample = (messages) => {
  class Emitter {
    constructor(messages = []) {
      this.messages = messages;
      this.event = () => {};
    }

    setEvent(fn) {
      this.event = fn;
    }

    trigger() {
      this.messages.forEach((message) => this.event(message));
    }
  }

  class Receiver {
    constructor() {
      this.messages = [];
    }

    ping(message) {
      this.messages.push(message);
    }
  }

  const myEmitter = new Emitter(messages);
  const myReceiver = new Receiver();

  myEmitter.setEvent(myReceiver.ping);
  myEmitter.trigger();

  return myReceiver.messages;
};

One simple way to fix this is to pass the Receiver instance to the Emitter constructor, and call the ping() method directly. But I feel like there should be a way to call that function without passing the class.

How to count unaccented English letters in Javascript? [duplicate]

I’m trying to count the number of characters that are unaccented English letters in a string. For example, I would want the count to be 1 for the string “né!”.

I thought I would be able to check if each character is in the range ‘a’-‘z’ or ‘A’-‘Z’, but that would include 'é':

'é' >= 'a' && 'e' <= 'z';
true

Both accented and unaccented letters seem to have the same code point:

"eé".codePointAt(0);
101
"eé".codePointAt(1);
101

I tried using regular expressions, but the string "né!" was treated like the 4-character string "ne'!":

    for (let i = 0; i < len; i++) {
        var c = str.charAt(i);
        if (re.test(c)) {
            console.log("Is a letter: " + c);
            numLetters++;
        } else {
           console.log("Is not a letter: " + c);
        }
    }

Output:

Is a letter: n
Is a letter: e
Is not a letter: ́
Is not a letter: !

How can I find the number of characters that are unaccented English letters?