Autoplay HTML video if url hash is present

I wrote some javascript to detect if a specific URL hash is present to automatically play a specific video when the page loads.

I am able to determine that the video play code is being activated via the togglevid() alert when the page loads. However, the video never starts playing.

Can you take a look at the code below and see what I am missing here?

if (window.location.hash) {
  // if "playvideo" hash is present, automatically start playing the video
  var runvid = document.getElementById(window.location.hash.slice(1)).getElementsByTagName('video').item(0);
  togglevid(runvid);
}

// Create listener for each video to play when clicked on
var vids = document.getElementsByTagName('video')
for (var i = 0; i < vids.length; i++) {
  var x = vids.item(i);
  vids.item(i).addEventListener("click", function() {
    togglevid(this);
  });
}

function togglevid(x) {
  alert("Video toggle triggered.  SRC: " + x.src);
  if (x.paused == true) x.play();
  else x.pause();
}
body {
  max-width: 800px;
}

video {
  max-width: 800px;
}
<h1>TEST</h1>
<p>Click on video to start playing if it hasn't already started.</p>
<div id="playvideo">
  <video src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"></video>
</div>

Is shapes.devs deprecated in jointjs v4.0.4?

I am currently trying to get familiar with a JS library – JointJS(to upgrade a project from version 3.7.7 to 4.0.4 because it is now dependency-free). Apparently I do not see documentation for the free version as much as for JointJS plus.

Is shapes.devs deprecated?
According to the code I still see shapes.devs but the changelog says it is removed?

https://github.com/clientIO/joint/blob/v4.0.4/packages/joint-core/types/joint.d.ts

https://changelog.jointjs.com/plus/4.0.0/changelog.html
(Also this seems to be for plus version could not find changelogs for open source)

Can someone also provide suggestions on how can I upgrade it efficiently while getting familiar to the new library and the way it’s built in the project I am working on(it is an Angular project).

How do i handle interpolated Animated and dot indicator gracefully while I have a copy of data list?

I want to create a bidirectional swiper my own, but I have a problem about to seek a way how do i handle the interpolated. here’s my swiper so far

Swiper.js

import React, {useCallback, useRef} from 'react';
import {Animated, View} from 'react-native';

const Swiper = ({
  RenderItem = () => null,
  data = [],
  RenderDotIndicator = false,
  containerWidth = 0,
}) => {
  const refAnimated = useRef(new Animated.Value(0)).current;
  // here I copy the data that I got from props
  // so if the data is [1,2] it would be [1,2,1,2]
  const [InternalData, setInternalData] = React.useState([...data, ...data]);

  // here I want to handle that interpolated only used 2 length instead of 4
  const interpolateFunct = (outputRange, index) =>
    refAnimated.interpolate({
      inputRange: [
        (index - 1) * width,
        index * width,
        (index + 1) * width,
      ],
      outputRange,
      extrapolate: 'clamp',
    });

  const WrappedRenderItem = useCallback(
    ({item, index}) => (
      <View style={{overflow: 'hidden', width: width}}>
        {RenderItem({item, index})}
      </View>
    ),
    [],
  );

  const WrappedRenderDotIndicator = useCallback(() => {
    const dotItem = data.map((item, index) => {
      return (
        <Animated.View
          key={'dot' + item + index.toString()}
          style={{
            width: 6,
            backgroundColor: '#D3D3D3',
            height: 6,
            borderRadius: 6 / 2,
            marginHorizontal: 5,
            transform: [{scale: interpolateFunct([1, 2, 1], index)}],
          }}
        />
      );
    });
    return (
      <View
        style={{
          flexDirection: 'row',
          alignSelf: 'center',
          position: 'absolute',
          bottom: 6,
        }}
      >
        {dotItem}
      </View>
    );
  }, [RenderDotIndicator]);

  return (
    <View>
      <Animated.FlatList
        ref={refAnimated}
        data={InternalData}
        renderItem={WrappedRenderItem}
        horizontal
        pagingEnabled
        onScroll={Animated.event(
          [{nativeEvent: {contentOffset: {x: refAnimated}}}],
          {useNativeDriver: true},
        )}
      />
      <WrappedRenderDotIndicator />
    </View>
  );
};

Swiper.displayName = 'Swiper';

export default Swiper;

currently, using the code above, I got this behaviour (notice the dot indicator when I sliding from 2nd to 3rd image, the dot is not reflecting the first one)

https://jmp.sh/JeFQ2CbF (or run snippet below)

<div style="position: relative; padding-bottom: 56.25%; height: 0;"><iframe src="https://jumpshare.com/embed/IFu1Zeev0hccyrbvqm9h" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></iframe></div>

How do I handle when sliding from 2nd to 3rd, the dot indicator reflecting the first one?

[ERR_HTTP_HEADERS_SENT]: Cannot append headers after they are sent to the client on middleware.js during authentication

I have a project where I do authentication checking on middleware.js file. It was doing fine locally and on development server, but when we deploy it to production it got:

[ERR_HTTP_HEADERS_SENT]: Cannot append headers after they are sent to the client
import { NextResponse } from 'next/server'
import { getBackendUrl } from './components/Constanta/Constanta'

// This function can be marked `async` if using `await` inside
export async function middleware(request) {
    const BE_URL = getBackendUrl('general')
    const token = request.cookies.get('token')
    if(token) {
        try {
            const response = await fetch(BE_URL+"check-auth/", {
                method: "GET",
                headers: {
                    'Authorization': `Bearer ${token.value}`,
                    "Content-Type": "application/json",
                },
            })
            if (!response.ok) {
                const resp = NextResponse.redirect(new URL('/login', request.url))
                resp.cookies.set("route", new URL(request.url).pathname);
                resp.cookies.set("token", null);
                resp.cookies.set("userID", null);
                resp.cookies.set("roleID", null);
                return resp
            } else {
                return NextResponse.next();
            }
        }
        catch (error) {
            console.log(error)
            const resp = NextResponse.redirect(new URL('/login', request.url));
            resp.cookies.set("route", new URL(request.url).pathname);
            return resp;    
        }
    } else {
        const resp = NextResponse.redirect(new URL('/login', request.url));
        resp.cookies.set("route", new URL(request.url).pathname);
        return resp;   
    }
}

 
// See "Matching Paths" below to learn more
export const config = {
    matcher: [
        '/',
        ...
    ],
}

Did I do something wrong? The production server should be mirroring the development server and I built it on Docker so I got confused here.

Create unique key/hash based on object

Say I have the following JavaScript objects:

const obj1 = {
 key1: 'str1',
 key2: 'str2'
}

const obj2 = {
 key2: 'str2',
 key1: 'str1'
}

const obj3 = {
 key1: 'something else',
 key2: 'str2'
}

const obj4 = {
 differentKey: 'str1',
 key2: 'str2'
}

I’d like to create a unique key based on a given object. This is so I can properly cache some data related to each object. In this scenario, obj1 and obj2 should have the same key, as the only difference is the ordering of properties. obj3 and obj4 should have different keys from each other. I tried using JSON.stringify() but this gives different results for obj1 and obj2 due to the ordering. Is there a way to get around this, ideally that can work with non-primitive types?

How to resolve that after searching request a property name has changed to a property id?

I am using a React Native Expo web app for the frontend and Django for the backend.

I have a search function that works fine. But the problem I am facing is that after a search term the property name of a specific animal has changed to a property id (number).

What I mean with this is that in the accordion the category name is shown. But after the search the category id is displayed.

In the frontend I have an accordion with some properties. The property for category looks:

export const AccordionItemsProvider = ({ children }) => {   
    const [categoryExpanded, setCategory] = useState(false);
    

    const accordionItems = (item) => {
        return (
            <>
            
                <List.Accordion
                    title="Familie"
                    expanded={categoryExpanded}
                    onPress={() => setCategory(!categoryExpanded)}>
                    <Text>{item.category}</Text>
                </List.Accordion>
                
            </>
        );
    };

    return (
        <AccordionItemsContext.Provider
            value={{
                accordionItems,
            }}>
            {children}
        </AccordionItemsContext.Provider>
    );
};

So the name of category will be displayed. But after the search the id of category will be displayd. And not the name.

The search context of animal looks:

/* eslint-disable prettier/prettier */

import React, { createContext, useEffect, useState } from "react";

import { fetchAnimalData } from "./animal/animal.service";
import useDebounce from "../hooks/use-debounce";

export const SearchAnimalContext = createContext();
export const SearchAnimalContextProvider = ({ children }) => {
    const [searchAnimal, setSearchAnimal] = useState([]);
    const [results, setResults] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [input, setInput] = useState("");
    const debounce = useDebounce(input, 500);

    useEffect(() => {
        if (debounce === "") {
            setResults([]);
            return;
        }
        fetchAnimalData(debounce)
            .then((response) => {
                setResults(response);
            })
            .catch((err) => {
                setError(err);
            });

        fetchAnimalData();
    }, [debounce]);

    const performSearch = async (text) => {
        if (text.trim() === "") {
            setResults([]);
        }
        setLoading(true);
        setError(null);
        setTimeout(() => {
            fetchAnimalData(text)
                .then((response2) => {
                    setResults(response2);
                    console.log(response2);

                    setLoading(false);
                })
                .catch((err) => {
                    setLoading(false);
                    setError(err);
                });
        }, 100);
    };
    return (
        <SearchAnimalContext.Provider
            value={{
                results,
                setResults,
                searchAnimal,
                setSearchAnimal,
                input,
                setInput,
                performSearch,
                loading,
                error,
            }}>
            {children}
        </SearchAnimalContext.Provider>
    );
};

And the output after a search request of the console.log looks:

category
: 
30
category_name
: 
"Katachtigen - Felidae"

So before the search category is displayed correctly: “Katachtigen – Felidae”. But after the search category is displayed as 30 – category_id: which is not correct.

And the seach function in the component looks:

import React, { useContext, useEffect, useState } from "react";
import { SafeArea } from "../../../components/utility/safe-area.component";
import { SearchAnimalContext } from "../../../services/search-animal.context";
import { fetchSubCategoryData } from "../../../services/category/category.service";

export const SubCategoryScreen = ({ route, navigation }) => {
    
    const [isLoading, setLoading] = useState(true);
    const { performSearch, results, setInput, input } = useContext(SearchAnimalContext);    
    const [isSearchbarFocused, setSearchbarFocused] = useState(false);  

    useEffect(() => {
        fetchSubCategoryData(route.params.subcategories).then((data) => {
            setSubCategoryList(data.animals.length > 0 ? data.animals : data.subcategories);
            setLoading(false);
        });
    }, [route]);

    const handleSearchChange = (text) => {
        setInput(text);
        if (text.length === 0) {
            performSearch(""); 
            navigation.navigate("dieren");
        } else {
            performSearch(text);
        }
    };



    return (
        <SafeArea>
            {isLoading && (
                <LoadingContainer>
                    <ActivityIndicator animating={true} color={MD2Colors.green200} />
                </LoadingContainer>
            )}
            <Searchbar
                placeholder="Search animals"
                value={input}
                onFocus={() => setSearchbarFocused(true)}
                onChangeText={handleSearchChange}
                onBlur={() => setSearchbarFocused(false)}
                style={styles.searchbar}
            />
            
        </SafeArea>
    );
};

And the model animal from the backend looks:

import sys
from io import BytesIO
from django.db import models

class Animal(models.Model):   
    name = models.CharField(max_length=100, verbose_name="Naam")
    sort = models.CharField(max_length=100, default='',  
    category = models.ForeignKey(
        Category, related_name='animals', on_delete=models.CASCADE, verbose_name="Familie")   

    def category_name(self):
        return self.category.name
   

    class Meta:
        verbose_name = "Dier"
        verbose_name_plural = "Dieren"
        # permissions = [("set_display_flag", "Check name is display or not",)]

   
        super(Animal, self).save()

    def __str__(self):
        return self.name

How to display the correct category name and not the category id after a search request?

In my Next js app some of the images are not loaded

In my next js app some of the images are not loaded. In inspect element it shows that image is loaded successfully but some of the images in the list are not appearing. When I shrink viewport or refresh the images appear(In most cases). you can view the bug website enter image description hereenter image description here

I tried updating next js version from 13.4.3 to 14. I use sanity as CDN

JS Event type change / keydown / beforeinput /

I have an input element of the type number and prefilled with a zero.
Now i want to trigger some JS everytime the value changes…but

  • It should not be triggered if the user presses backspace fort deleting the initial zero.
  • It should be triggered if the user uses the arrows awailable for number fields

So this is not working because its getting triggered on backspace:

on(document, "change keydown", ".mynumberfield", function (e) {
...

The offset of the data in the column

Help with the problem. There are filled cells A1:A3, there are also filled cells B1:B3. I am adding a value to cell A4 and I need the available data to be in the range B1:B3 shifted down, that is, cell B1 became empty And the values that were in cells B1:B3 moved to cells B2:B4#1 BEFORE

#2 AFTER

it is worth noting that the cells in the first column are filled with the IMPORTAGE function

I tried the following code, but it doesn’t work:

function onEdit(e) {
 if (e && e.source) {
 if (e.source.getSheetName() !== 'Calculation') return;
 }
 if (e) {
 if (e.range && e.range.columnStart == 1 && e.range.rowStart == 1 && e.value != '') {
 var row = e.range.rowStart + 2;
 var column = e.range.columnStart + 1;
 var nextRow = row + 1;
 var nextColumn = column;
 var range = e.range.offset(nextRow, 0);
 if (SpreadsheetApp.getSheetByName('Calculation').getRange(range).isBlank()) {
 // Если диапазон пуст, активируем его
 SpreadsheetApp.getSheetByName('Calculation').getRange(range).activate();
 } else {
 // Если диапазон не пуст, добавляем сообщение об ошибке
 SpreadsheetApp.getActiveSpreadsheet().toast("Ошибка: диапазон не пуст");
 }
 } else if (e.range && e.range.columnStart == 1 && e.range.rowStart >= 2 && e.range.rowStart <= 3) {
 var row = e.range.rowStart + 1;
 var column = e.range.columnStart + 1;
 var nextRow = row + 1;
 var nextColumn = column;
 var range = e.range.offset(nextRow, 0);
 if (SpreadsheetApp.getSheetByName('Calculation').getRange(range).isBlank()) {
 // Если диапазон пуст, активируем его
 SpreadsheetApp.getSheetByName('Calculation').getRange(range).activate();
 } else {
 // Если диапазон не пуст, добавляем сообщение об ошибке
 SpreadsheetApp.getActiveSpreadsheet().toast("Ошибка: диапазон не пуст");
 }
 }
 }
}

Not able to upload image in jpg or png format

I am trying to submit image in post api, but somehow I am not able to do it.

Currently I am using react-native-image-picker package.

On click of image selecting button, below function is being called. which is working fine.

    const handleImagePicker = async (item: string) => {
        const options: ImageLibraryOptions = {
          mediaType: 'photo',
        };
    
        try {
          const response = await launchImageLibrary(options);
    
          if (response.didCancel) {
            console.log('User cancelled image picker');
            return;
          }
    
          if (response.assets && response.assets.length > 0) {
            const {uri} = response.assets[0];
    
            if (item == 'Profile') {
              setSelectedProfileImage(uri);
              setProfilePictureEmpty(false);
            } else {
              setSelectedBannerImage(uri);
            }
          }
        } catch (error) {
          console.error('Error picking image:', error);
        }
      };

Then, On click of submit button below function is called.

 const addBusiness = async () => {
    const getUserId = async () => {
      try {
        const userId = await AsyncStorage.getItem('id');
        return userId;
      } catch (error) {
        return null;
      }
    };
    if (selectedProfileImage == '') {
      setProfilePictureEmpty(true);
      setErrMsg(string.enter_profile_picture);
    } else {
      var profileImg = {
        uri: selectedProfileImage,
      };
      var bannerImg = {
        uri: selectedBannerImage,
      };
      const userId = await getUserId();
      uploadImages(
        uploadImageAPI,
        businessDetails?.id,
        profileImg,
        bannerImg,
        (response: any) => {
          console.log(response)
          setSecondScreenEnabled(false);
        },
        (error: any) => {
          console.log('error', error);
        },
      );
    }
  };

here I am using custom API function. i.e., uploadImages.

Please find that function below:

export const uploadImages = async (
  url,
  Id,
  ProfilePicture,
  BannerPicture = null,
  onSuccess,
  onError,
) => {
  const formData = new FormData();
  instance.defaults.baseURL = Config.BASE_URL;

  const appendImage = (image, name) => {
    const { uri } = image;
    const fileType = uri.split('.').pop();
    formData.append(name, {
      uri: uri,
      type: `image/${fileType}`,
      name: `${name}.${fileType}`,
    });
  };

    formData.append('Id', Id);
 
  if (ProfilePicture) {
    appendImage(ProfilePicture, 'ProfilePicture');
  }

  if (BannerPicture) {
    appendImage(BannerPicture, 'BannerPicture');
  }

  try {
    const authToken = await getAuthToken();

    const config = {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    };

    if (authToken) {
      config.headers.Authorization = `Bearer ${authToken}`;
    }

    console.log('FormData:', formData);
    instance
        .put(url, formData, config)
        .then(function (response) {
          onSuccess(response.data);
        })
        .catch(function (error) {
          onError(error);
        });

    const response = await instance.put(url, formData, config);
    onSuccess(response.data);

  } catch (error) {
    if (error.response) {
      console.error('Response error:', error.response.data);
      console.error('Response status:', error.response.status);
      console.error('Response headers:', error.response.headers);
    } else if (error.request) {
      console.error('Request error:', error.request);
    } else {
      console.error('Error:', error.message);
    }
    onError(error);
  }
};

I am getting below error while submitting the image.

Request error: {"DONE": 4, "HEADERS_RECEIVED": 2, "LOADING": 3, "OPENED": 1, "UNSENT": 0, "_aborted": false, "_cachedResponse": undefined, "_hasError": true, "_headers": {"accept": "application/json", "authorization": "my_token"_responseType": "", "_sent": true, "_subscriptions": [], "_timedOut": false, "_trackingName": "unknown", "_url": "my_url", "readyState": 4, "responseHeaders": undefined, "status": 0, "timeout": 60000, "upload": {}, "withCredentials": true}

If anyone had face this thing and solved it then please help me out.

Thanks in advance 🙂

how to dynamically assign the head title in vue?

I wanted that when the openAddMenu method was called, the title in nuxt.config.js would be dynamically changed with the value “newTitle”.

Sidebar.vue

methods: {
         openAppMenu(itemIndex) {
              const newTitle = this.menuItems[itemIndex].title;
         },
}

nuxt.config.js

head: {
    title: 'XYZ', // this title
    meta: [
        {charset: 'utf-8'},
        {name: 'viewport', content: 'width=device-width, initial-scale=1'},
        {hid: 'description', name: 'description', content: pkg.description}
    ],
    link: [
        {rel: 'icon', type: 'image/x-icon', href: '/favicon.ico'}
    ]
},

Issue with positioning of spotlight in react-joyride, but only when using an automated testing tool

I’m encountering an issue where for certain steps, the spotlight will be positioned correctly when I run it manually as a user, but then when I try to run it in an automated end to end test, the positioning is off. This same issue occurs with either cypress or selenium. I’ve added wait/pause calls in both tools to ensure that it wasn’t an issue of speed. Note that it is only the spotlight that is off in these instances, the tooltip is positioned correctly.

Below is a screencast of the behavior in cypress. There are some other issues with lags in spotlight positioning in the intermediate steps that don’t occur when run manually but eventually the spotlight is placed correctly. However with the last spotlight, it remains in the incorrect position. This creates a functional issue for the test since only the spotlight area can receive a mouse click. As a workaround I’m think of expanding the padding of the spotlight (using the spotlightPadding step config value) for only when running in the automated tests, but my preference of course is to try to avoid automated test specific code in the application code.
https://d.pr/v/L6dlRh

Here’s a screencast of the behavior when run manually:
https://d.pr/v/mQFQ3d

Here’s how I have the step in question configured in react-joyride:

{
 target: '.hip-modal-study-settings .hip-version-1',
 content: 'Click on Version 1',
 disableBeacon: true,
 disableScrolling: true,
 spotlightClicks: true,
},

Here’s how the joyride component is being called:

 <Joyride
        debug={true}
        continuous={true}
        stepIndex={stepIndex}
        steps={startTour && tourId !== null ? getTourList()[tourId].steps : []}
        showProgress={false}
        disableOverlayClose={true}
        disableOverlay={false}
        callback={handleJoyrideCallback}
        scrollToFirstStep
        run={startTour}
        styles={{
          options: {
            zIndex: 20000,
          },
          tooltip: {
            width: '250px'
          },
          spotlight: {
            transition: 'opacity 0.2s',
          }
        }}

      />

This is with the latest versions of react-joyride, cypress and selenium.

Display title of file from AJAX on custom casette player [closed]

I am hoping someone can help me out.
OK, so I am creating a custom wordpress plugin which is based on this casette player demo from codrops: https://tympanus.net/codrops/2012/07/12/old-school-cassette-player-with-html5-audio/

I have so far created the metaboxes, custom post types etc, and added the required data to the WordPress REST API. For the actual audio tracks, the array from my AJAX request is working exactly as its supposed to, i.e. the player is working (nice!). The custom endpoint is here: https://dannysaber.dreamhosters.com/wp-json/wp/v2/songs and you can see the player working here: https://dannysaber.dreamhosters.com/tape-player-test/

What I would like to add here, is when a song is played, the title of the track is shown. I have managed to get the titles from the API, as an array, but I cannot figure out how to do this, my javascript is a bit rudimentary!

Another option I think that might work, is using something like this to get the ID3 tag of the actual tracks- https://github.com/aadsm/jsmediatags#browser (which also might support album art, if added). However, I think its best to get the data from the REST API. I am sure its possible, I just dont know how in this code to generate the song titles when a track is played. Am I doing the AJAX processing wrong? help is appreciated.

the code for the player is on this link (too long to copy here!) https://dannysaber.dreamhosters.com/wp-content/themes/dannysaber/js/jquery.cassette.js

Jquery barcode scanner

In my HTML file is use Jquery scannerDetection. My problem is that if i select an input field the scanner writes to that input (cardnameinput) instead of the dedicated one (cardidinput). If i deselect everything the scanner inputs in the right field.

<input type="text" id="cardnameinput" class="k-textbox" style="width: 100%;"/>
<input type="text" id="cardidinput" class="k-textbox k-state-disabled" style="width: 
    100%;"/>

$(function () {
     $(window).scannerDetection({
         timeBeforeScanTest: 100, // wait for the next character for upto 200ms
         startChar: [188], // prefix character to start listening
         endChar: ["?".charCodeAt(0)], // suffix character eg end of scanning. We can not get the character code for "?" reliably, hence the use of "charCodeAt"
         avgTimeByChar: 45, // it's not a barcode if a character takes longer than 40ms
         ignoreIfFocusOn: "input",
         minLength: 4,
     });

     $(window).bind("scannerDetectionComplete", function (e, data) {
         console.log("Card succesfully scanned " + data.string);
         $("#cardidinput").val(data.string);
     }).bind("scannerDetectionError", function (e, data) {
         console.log("Error reading card " + data.string);
     });

     $("#siteDropDown").change(function () {
         var departmentComboBox = $("#departmentComboBox").data("kendoComboBox");
         departmentComboBox.dataSource.read();
         departmentComboBox.value("");
     });

     $("#createGuestCardButton").on("click", function (e) {
         e.preventDefault();
         checkGuestCard();
     });
 });

Dialog page cannot be rendered successfully

I’m trying to navigate to page on my application on page load with this code below

apex.navigation.dialog(‘f?p=110:25’, {
title: “Interactive Report”,
modal: true,
width: 800,
height: 600
});

But I’m getting Application 110 Dialog page 25 cannot be rendered successfully. Ensure the page template in use on page 25 is of template type “Dialog page”, with appropriate JavaScript dialog initialization, dialog closure and dialog cancel code defined. what could be the possible solutions to it?