Finding All Instances Of A Specific Word Within A Multidimensional Array Using Javascript

I have here a nested array:

const roster = [["Ryu","RyuNormal"], ["Ryu as Ken","RyuKen"], ["Ryu as Akuma","RyuAkuma"], ["Chun-Li","ChunLi"],["Zangief"]]

And a for-loop that will produce options for a dropdown menu:

for ([char, link] of roster) {
    options += `n <OPTION class="show" data-toggle="${link ?? char}">${char}</OPTION>`;
}

Each bracket in the nested array consists of the character’s name before the comma, and a toggle link ref after the comma. If the bracket has only one entry and not two (see Zangief), it is to be assumed the character’s name doubles as a toggle link, hence the double question marks.

Suppose you are building a chart that compares special move functions between two characters. If you were on Chun-Li or Zangief’s respective web pages, the dropdown menu would gladly show you Ryu’s moves in addition to his Ken and Akuma forms (for those not in the know, in the first Marvel vs. Capcom game, Ryu had the ability to switch styles), so their OPTION tags would be included here. However, if you were on Ryu’s page, the only OPTION tags you would be able to see are Chun-Li’s and Zangief’s, which is the intended result.

console.log(result) // [["Chun-Li","ChunLi"],["Zangief"]] if on Ryu page
console.log(result) // [["Ryu","RyuNormal"], ["Ryu as Ken","RyuKen"], ["Ryu as Akuma","RyuAkuma"], ["Zangief"]] if on Chun-Li page

I have tried the findIndex and filter functions, but neither of them worked. When I tried the filter function, the console log kept bringing up the entire array no matter if I used the !== or the includes() parameter. The findIndex function kept giving me a -1 (no match) whenever I tried looking up all entries that had the word “Ryu.” As this was a nested array, using the brackets in my field of search somewhat alleviated the situation, but there were some mishaps, like removing Chun-Li and Zangief because they were unique results but only removing one instance of Ryu when it should have removed all three instances.

How do I revise the code so that the filter and/or findIndex function properly finds all instances of a word in the first half of any bracketed array? Array splicing is optional.

Cannot remove child at index 0 from parent viewGroup [370], only 2 children in parent. Warning ChildCount may incorrect

const data = [
  {id: 1, name: 'irfan'},
  {id: 2, name: 'dami'},
];

<FlatList
  data={data}
  renderItem={({item}) => <Text>{item.name}</Text>}
  keyExtractor={(item) => item.id.toString()}
/>

React Native and Dependencies:

react-native: 0.76.6,

react-native-gesture-handler: ^2.22.0,

react-native-screens: ^4.6.0

Error Details:
I get this error when the FlatList is rendered. The warning suggests there is an issue with child removal in the view hierarchy, but I’m not sure how to fix it.

I’ve verified that my keyExtractor is returning a string from the item’s id, and the data array is being passed correctly.

Steps I’ve already tried:

1.Ensured that keyExtractor returns a string.

2.Checked for any re-renders or conditional rendering issues with the FlatList.

3.Tried wrapping the FlatList in a View container to see if it resolves the issue.

Has anyone encountered this issue before? Any help on how to resolve this would be appreciated!

TipTap RichTextEditor with React Hook Form and Zod only shows Expected string, received null

I can only see the values in the console but value for RichTextEditor (TipTap) does not show with the FormData and shows this error:

Validation Errors: { _errors: [], description: { _errors: [
‘Expected string, received null’ ] } }

 const form = useForm<BookInferSchema>({
    resolver: zodResolver(BookSchema),
    defaultValues: {
      //rest of the fields
      description: "",
      bookImageUrl: "",
    },
  });

Input form:

<FormField
                  control={form.control}
                  name="description"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Description</FormLabel>
                      <FormControl>
                        <RichTextEditor
                          content={field.value}
                          onChange={(value) => field.onChange(value)}
                        />
                      </FormControl>
                      <FormMessage />
                      {state?.errors?.description && (
                        <FormDescription>
                          {state.errors.description}
                        </FormDescription>
                      )}
                    </FormItem>
                  )}
                />

RichTextEditor:

import { useEditor, EditorContent } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Underline from "@tiptap/extension-underline";
import TextEditorMenuBar from "./TextEditorMenu";
import TextAlign from "@tiptap/extension-text-align";
import Heading from "@tiptap/extension-heading";
import Text from "@tiptap/extension-text";
import { mergeAttributes } from "@tiptap/core";

type TextEditorProps = {
  onChange: (content: string) => void;
  content?: string; // Add this line
};

export default function RichTextEditor({ onChange, content }: TextEditorProps) {
  const editor = useEditor({
    extensions: [
      StarterKit,
      Underline,
      Text,
      TextAlign.configure({
        types: ["paragraph"],
        alignments: ["left", "center", "right", "justify"],
      }),
      Heading.extend({
        levels: [1, 2, 3, 4, 5, 6],
        renderHTML({ node, HTMLAttributes }) {
          const level = this.options.levels.includes(node.attrs.level)
            ? node.attrs.level
            : this.options.levels[0];
          const classes: { [index: number]: string } = {
            1: "text-2xl",
            2: "text-xl",
            3: "text-lg",
            4: "text-md",
            5: "text-sm",
            6: "text-xs",
          };
          return [
            `h${level}`,
            mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, {
              class: `${classes[level]}`,
            }),
            0,
          ];
        },
      }).configure({ levels: [1, 2] }),
    ],
    content: content,
    onUpdate: ({ editor }) => {
      console.log(editor.getHTML());
      onChange(editor.getHTML());
    },
    editorProps: {
      attributes: {
        class:
          "w-full min-h-[150px] cursor-text rounded-md border p-5 ring-offset-background focus:outline-none focus-within:outline-none focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2",
      },
    },

    immediatelyRender: false,
  });
  return (
    <div>
      <TextEditorMenuBar editor={editor} />
      <EditorContent editor={editor} />
    </div>
  );
}

I am trying to send the formData in my action.ts, the rest of the fields are fine.

export async function addBook(state: BookFormState, formData: FormData) {
  // Validate form fields
  // Log all form data to debug
  for (const pair of formData.entries()) {
    console.log(`${pair[0]}: ${pair[1]}`);
  }

  const validatedFields = BookSchema.safeParse({
    //rest of the fields
    description: formData.get("description"),
    
  });

   // Check if validation failed
   if (!validatedFields.success) {
    console.error("Validation Errors:", validatedFields.error.format()); // Log errors
    return {
      errors: validatedFields.error.flatten().fieldErrors,
    };
  }

Filtering a list of dictionaries with JSON [duplicate]

I have an object named “exercises” with 31 dictionaries in a list, that resembles the following. How would I go about filtering this by ‘lessonid’ and ‘sequence’, and returning the corresponding ‘exerciseModelData’?

This is taken from the console.log output of the object:

[{
    "exerciseid": 3,
    "sequence": 1,
    "level": 3,
    "exerciseType_id": 1,
    "lessonid": 1,
    "icon": "fas fa-marker",
    "shortform": "E.1",
    "done": false,
    "exerciseModelData": []
},
{
    "exerciseid": 4,
    "sequence": 2,
    "level": 3,
    "exerciseType_id": 2,
    "lessonid": 1,
    "icon": "fas fa-marker",
    "shortform": "E.2",
    "done": false,
    "exerciseModelData": []
},
{
    "exerciseid": 5,
    "sequence": 3,
    "level": 3,
    "exerciseType_id": 2,
    "lessonid": 1,
    "icon": "fas fa-marker",
    "shortform": "E.3",
    "done": false,
    "exerciseModelData": []
},]

Let’s say I wanted to filter the above shortened version (I cannot put the whole object here, it is thousands of lines), by lessonid = 1 and sequence = 2, and return back the corresponding exerciseModelData.

I also want to get the index of the result dictionary if that’s possible.

Javascript method getElementsByClassName or getElementByID returning null

This seems so simple, but I cannot seem to wrap my head around what it is that I am doing wrong.

I’m merely trying to create a system of tags by passing an array of objects into the html of a div within the dom using vanilla javascript.

I have some very simple html

<html lang="en">
  <head></head>
  <body>
    <div class="tagtype"></div>
    <script src="index.js"></script>
  </body>
</html>

And I have some simple javascript I am attempting to populate within the tagtype div.

const tags = ["One", "Two", "Three", "Four", "Five", "Six", "Seven"]
var varName = document.getElementsByClassName("tagtype");
function generateTags () {
    for(var i = 0; i < tags.length; i++) {
    var tagTypes = document.createElement("div");
        tagTypes.innerHTML = tags[i];
        tagTypes.classList.add(tags[i]);
        varName.append(tagTypes);
    }
}
generateTags();

In most cases I’ve found when digging into this, people explain that the code is run before the dom element exists, so I tried placing the script tags before closing the body. I have also tried passing the for loop from within and outside of a function ‘generateTags’. I have tried variations on the class as an ID by passing the ‘getElementById()’ method against a div with id ‘tagtype’. I have even come across a discussion suggesting I need to make the tagtype variable the first in its ‘array’. However despite these I cannot seem to grab the tagtype div within the dom and populate the tags inside of the element. I usually get some variation of ‘tagtype returns null’ or ‘undefined’ or ‘tagtype.append is not a function.’

Any advice?

How do I make my remove button and the arrow buttons work in my Program?


// Create variables
var countTracker = 0;
var imageLink = "";
var index = 0;
var dessertsList = getColumn("Dessert", "Name");
var pictures = getColumn("Dessert", "picture");
var dessertsListFiltered = [] ;

onEvent("addButton", "click", function( ) { var userInput = dessertsList.length; if (userInput != dessertsList.length) { countTracker = countTracker + 0; setText("countText", countTracker); } else { countTracker = countTracker + 1; setText("countText", countTracker); } updateScreen(); }); 

/// OnEvent button to remove images onEvent("removeButton", "click", function( ) { clearCanvas(); }); 

// OnEvent to scroll right onEvent("rightArrow", "click", function( ) { if (index > 0) { index = index - 1; updateScreen(); setImageURL("imageArea", pictures[index]); } }); 

// OnEvent to scroll left onEvent("leftArrow", "click", function( ) { if(index < dessertsList.length -1) { index = index + 1; updateScreen(); setImageURL("imageArea", pictures[index]); } });

Link to my code
https://studio.code.org/projects/applab/PyRGvxfwjv40QgbGSUEFkprt_1B0I2MK2HyqsgfpXgU

I am trying to make the left and right button work as well as the remove button.

I want the program to delete 1 image each time the Remove button is clicked. The image that is deleted is the image on the user’s interface when they click the Remove button not all of the images stored.

I also need to make sure that my left and right button work as well. The left and right button will be used to scroll through the images. the left button shouldn’t be able to scroll behind the first image that was added and the right button should stop scrolling forwards when the last image is added.

Whenever a picture is added by pressing the add button I want the countText ID to say 1 of 4, 2 of 4, 3 of 4, and 4 of 4 because I want them to only be able to add 4 things and only be able to add the things that are in the dataset I created. When a picture is removed I want the countText ID to say go back to the amount of pictures that were added before so for example if it was 4 of 4 when the Remove button is clicked the the countText ID should say 3 of 4.

Thank you.

When I press the Remove button it wont do what I ask it to but I am pretty sure I am using the wrong block of code for my remove button but I don’t know what to do.

the add button is able to go past for and when you click the add button it will say 1 not 1 of 4.

The left and right button doesn’t work either it just stays on the same page

React Form Submission Not Triggering: Debugging onSubmit Issue in a Client Component

I am using a client component to submit the data. It used to work, but suddenly, it stopped. Before that, I remember changing ISBN to isbn and authorId to author_id. Initially, I thought the issue was with my Supabase setup, but even a simple onSubmit function no longer logs to the console.

    "use client";

interface BookFormProps {
  authors: Author[];
}

const BookForm: React.FC<BookFormProps> = ({ authors }) => {
  const [state, action, pending] = useActionState(addBook, undefined);

  // React Hook Form with default values
  const form = useForm<BookInferSchema>({
    resolver: zodResolver(BookSchema),
    defaultValues: {
      isbn: "",
      author_id: "",
      //rest of the values
    },
  });

  //submitting the forms - THIS DOES NOT SHOW
  async function onSubmit(data: BookInferSchema) {
    try {
      console.log("inside the onSubmit function");
      console.log(data, "data");
    } catch (e) {
      console.log(e);
    }
  }


  return (
    <div className="container mx-auto p-4">
      {/* Testing */}
      <Form {...form}>
        <form
          className="space-y-8"
          onSubmit={(e) => {
            e.preventDefault();
            console.log("submitting"); <--- THIS SHOWS IN THE CONSOLE
            startTransition(() => {
              form.handleSubmit(onSubmit)(e);
            });
          }}
        >
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
         //the rest of the fields
    </div>
  );
};

export default BookForm;

There are no errors on my BookSchem as well:

import { z } from "zod";

export const BookSchema = z.object({
  isbn: z.string().min(10, "ISBN must be at least 10 characters").max(13, "ISBN must not exceed 13 characters"),
  length: z.number().positive("Length must be a positive number"),
  width: z.number().positive("Width must be a positive number"),
  height: z.number().positive("Height must be a positive number"),
  publisher: z.string().min(1, "Publisher is required"),
  publicationDate: z.date({
    required_error: "Please select a data",
    invalid_type_error: "That is not a date."
  }),
  pages: z.number().int().positive("Pages must be a positive integer"),
  genre: z.string().min(1, "Genre is required"),
  author_id: z.string(), // Reference the Author schema
  signed: z.boolean(),
  format: z.string().min(1, "Format is required"),
  edition: z.string().min(1, "Edition is required"),
  productLanguage: z.string().min(1, "Product language is required"),
  stocks: z.number().int().positive("Stocks must be a positive integer"),
  title: z.string().min(1, "Title is required"),
  price: z.number().int().positive("Price must be a positive number"),
  description: z.string().min(1, "Description about the book is required"),
  bookImageUrl: z.string().url("Invalid URL"),
});

// TypeScript Type for Book
export type BookInferSchema = z.infer<typeof BookSchema>;

//Form state for adding and editing books
export type BookFormState =
  | {
      errors?: {
        isbn?: string[];
        length?: string[];
        width?: string[];
        height?: string[];
        publisher?: string[];
        publicationDate?: string[];
        pages?: string[];
        genre?: string[];
        author_id?: string[];
        signed?: string[];
        format?: string[];
        edition?: string[];
        productLanguage?: string[];
        stocks?: string[];
        title?: string[];
        price?: string[];
        description?:string[];
        bookImageUrl?: string[];
      };
      message?: string;
    }
  | undefined;

Why is it necessary to set the prototype of an extended object of a built in class in javascript/typescript to its own prototype?

I’m taking an online course in which the instructor writes out this code:

import { ValidationError } from 'express-validator';

export class RequestValidationError extends Error {
    constructor(private errors: ValidationError[]) {
        super();
        
        // Only because we are extending a built in class
        Object.setPrototypeOf(this, RequestValidationError.prototype);
    }
}

The line Object.setPrototypeOf(this, RequestValidationError.prototype) seems strange to me. It’s as if it is setting the prototype of this (the RequestValidationError) to its own prototype. What is it actually doing?

WordPress – Making Parent Menu Clickable

I know for a fact most WordPress themes don’t have the option to customise the behaviour of the submenus, so the only thing you can do is to hover the parent menu to access the submenus. However, I was wondering if there’s some way to make the parent menu clickable. Currently, I’m using the Kadence theme (http://www.antdogs.com/thewemdb)

I know there’s this option where you can put the “#” in the custom link field to make the parent menu not clickable but accessing the submenu that are clickable but that’s not exactly what I want to do.

I have heard this might be possible with JavaScript (which I have zero knowledge) but it depends on the code of the theme as far as I’m concerned.

If that’s not possible, then I can understand.

Best regards.

Detect when Child Reaches Bottom of Parent on Scroll

I’m trying to make a 2 column post template (images on the left, content on the right) and I want the content part to scroll with you as you scroll down the page, but stop when it gets to the bottom of its’ container.

I thought “parent.offset().top + parent.outerHeight()” was the proper way to detect when it has reached the bottom, but my code isn’t working quite right and I can’t figure out proper the sequence. I have the content start on scroll the way I intended it too, but it won’t stop once it reaches the bottom of the container.

Here is the code on CodePen

HTML

<div class="content-block"> 
  <div class="grid-column-group">
    <div class="grid-column grid-image">
      <div class="image-wrapper">
        <div class="image-prepped">
          <div class="image-set"></div>
        </div>
        <div class="image-prepped">
          <div class="image-set"></div>
        </div>
      </div>
    </div>
    <div class="grid-column grid-content">
      <div class="column-wrapper">
        <div class="wrapper-inner">
          <div class="column-headline">
            <h1>Lorem Ipsum Dolor</hi>
          </div>
          <div class="column-content">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
          </div>
        </div>
      </div>
      <div class="placeholder"></div>
    </div>
  </div>
</div>

JQUERY

function stickyBlock( $ ) {
    
    var position = $( window );
    var element = $( '.column-wrapper' );
    var parent = $( '.grid-content' );
    var isoffset = parent.offset().top;
    var isbottom = parent.offset().top + parent.outerHeight();
    var placeholder = $( '.placeholder' );

    position.scroll( function() {
      
      var issticky = $( this ).scrollTop();

      if( issticky >= isoffset ) {

        element.addClass( 'is-sticky' );
        element.css({ 'position': 'fixed', 'top': '0px', 'width': element.width() });
        placeholder.css({ 'display': 'block', 'position': 'static', 'width': element.width(), 'height': parent.height() });

      } else if( issticky >= isbottom ) {

        element.removeClass( 'is-sticky' );
        element.css({ 'position': 'absolute', 'top': 'auto', 'bottom': '100%', 'width': element.width() });
        placeholder.css({ 'display': 'block', 'position': 'static', 'width': element.width(), 'height': parent.height() });

      } else {

        element.removeClass( 'is-sticky' );
        element.css({ 'position': '', 'top': '', 'bottom': '', 'width': '' });
        placeholder.css({ 'display': '', 'position': '', 'width': '', 'height': '' });

      }

    });
  
  }

I don’t know how to approach this problem. Can anyone help me with this please? [closed]

I want to create an expression and also would like to edit it in the future if needed.
I am trying to write this code in React + Typescript.
Let me put the expressions in certain number of possible scenarios.
Scenario 1 (default) – when the page loads it should display like this in the UI

( Select )

*Select here stands for a dropdown which has 2 options, Symbol and App Name

Scenario 2 – If we select Symbol from the drop-down the UI should look like this

(( Select ))

And if we select AppName

( AppNameList / DataNameList )

*AppNameList is a drop-down which will have a list of options, upon selecting a option from the list, DataNameList options get populated.
Note – / should always be present after AppNameList and before DataNameList.

Scenario 3 – Now if we select an option from DataNameList, the UI should look like this

( AppNameList / DataNameList AND Select )

*AND is a default value from the drop-down which has two options, AND & OR
Select is the same drop-down which is by default and it works the same way as it was earlier

Scenario 4 – If we select Symbol from the Select drop-down, the UI will look

( AppNameList / DataNameList AND ( Select ))

I hope you understand the logic and can guess the possible scenarios.
I also want a delete icon at every option, not on all but maybe on the current item which I am going to select.

Please help me.

I have tried from my end but I was not able to create a logic for it. I got stuck on one or the other logic.

Questions about tg bot inline keyboard

Recently when I was found that some tg bots inline keyboards can share when i long press the button,Some bots to long presses have no response and it can only enter mini apps, I want to ask how to do long press can not share the link can only open the mini app, the following is my code and the info below:

var Options = {
    method: "post",
    contentType: "application/json",
    payload: JSON.stringify({
      chat_id: chatId,
      photo: photoUrl,
      caption: caption,
      reply_markup: {
        inline_keyboard: [
          [{ text: "Open App", url: "https://t.me/XXX_bot/start"}],
          [{ text: "Follow IG", url: "https://www.instagram.com/" }],
          [{ text: "Play with friends", url: "https://t.me/share/url?url=" + encodeURIComponent(shareMessage) }]
        ]
      }
    })
  };

enter image description here

I tried to modify the url: of [{ text: “Open App”, url: “https://t.me/XXX_bot/start”}], but my bot stopped responding after I changed it. I want to ask how to change it so that I can’t share my link but can only access my mini-apps?

I’m having difficulty uploading a video into the static folder of my flask app 413 request entity too large nginx error

I’m using the basic port 5000 development server. I’m trying to make a training portal for a cafe for my final project in cs50. The cafe wanted the ability to upload and delete training by management within the portal so that training can remain up to date. I’ve hit a wall as far as uploading videos

I configured the flask app to accept up to 1.8GB and made the route to handle any number of questions, answers, and options related to the video being uploaded

app=Flask(__name__)

# Set the maximum allowed request size to 1.8 GB
app.config["MAX_CONTENT_LENGTH"] = 1.8 * 1024 * 1024 * 1024 # 1.8 GB in bytes


@app.route("/trainingupload", methods=["GET", "POST"])
@login_required
def trainingupload():
    """upload training"""
    """only for management"""
    if request.method == 'POST':
        file = request.files['video']
        questions=request.form.getlist("question[]")
        answers=request.form.getlist("answer[]")
        secondary_options=request.form.getlist("option2[]")
        tertiary_options=request.form.getlist("option3[]")
        quarternary_options=request.form.getlist("option4[]")
        n=len(quarternary_options)
        if not(len(questions)==n and len(answers)==n and len(secondary_options)==n and len(tertiary_options)==n):
            return error("missing one or more fields", language=language)
        elif not (file and allowed_videos(file.filename)):
            return error("incorrect video format", language=language )
        elif not request.form.get("position"):
            return error("no position added", language=language)
        elif file and allowed_videos(file.filename):
            filename = secure_filename(file.filename)
            # Save the file path in a variable
            video_path = os.path.join(VIDEO_FOLDER, filename)
            # Save the file to the specified path
            file.save(video_path)
            position=request.form.get("position")
            db.execute("insert into training_key (video_path, require) values(?, ?)", video_path, position)
            training_id=db.execute("select training_id from training_key where require=? and video_path=?", position, video_path)[0]["training_id"]
            flash(f"Video uploaded successfully: {filename}")
            for i in range(n):
                db.execute("insert into quiz (training_id, question, answer, option2, option3, option4) values(?, ?, ?, ?, ?, ?)",
                    training_id, questions[i], answers[i], secondary_options[i], tertiary_options[i], quarternary_options[i]
                )
            return render_template('training_upload.html')    
    else:
        return render_template('training_upload.html')

I managed to upload a four second video without issue but then I tried a fourteen second video and it gave the error.

<label for="video">Choose a Video File to Upload 'mp4', 'mkv', or 'avi' only: </label>
        <input style="background-color: #fdfdfd;" type="file" name="video" id="video" accept="video/*" required>

I need to be able to upload a nine minute video at 30fps in 1080p which I researched to be 1.8GB max. Any help leading to a resolution of this error would be greatly appreciated.