I have barcode pasted on each product so before generating invoice i to have enter batch number and expiry date. so batch number and expiry data only accept by scanning in the textbox.
Should not accept copy paste also.
I need JavaScript code
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
I have barcode pasted on each product so before generating invoice i to have enter batch number and expiry date. so batch number and expiry data only accept by scanning in the textbox.
Should not accept copy paste also.
I need JavaScript code
I already have the percentage for my data, I just need to append the % to each data value.
I’m very new to JS and programming in general, so please be nice.
const Votes1 = document.getElementById("Votes1");
new Chart(Votes1, {
  type: "bar",
  reverse: "true",
  data: {
    labels: [
      "African National Congress", "Other", "IFP", "National Party"
    ],
    datasets: [
      {
        label: "Voting results from 1994 South African election.",
        data: [62.25, 6.42, 10.54, 20.39],
        backgroundColor: ["#627b88ff"],
        borderWidth: 1,
      },
    ],
  },
  options: {
    indexAxis: "y",
    scales: {
      y: {
        beginAtZero: true,
        grid: {
          drawOnChartArea: false,
        },
      },
      x: {
        beginAtZero: true,
        grid: {
          drawOnChartArea: false,
        },
      },
    },
  },
});
I’ve tried using Youtube videos for help, as well as some documentation – but I’m struggling since those are meant to extract data and THEN add the %. I just need to be able to add special characters to my Chart.js Data
If it matters, I’m using a tachyons framework
i have a custom wordpress feature im working on where i have created 5 images with buttons beaneath each,i dont want anu user to upload any avatars just select from my 5 and i want the selected image to be set as the current users profile image on my account and admin page on wordpress help please
i have tried custom plugins but non seem to be working for this feature and i and php codes
// Update profile photo
add_action('wp_ajax_update_profile_photo', 'update_profile_photo');
add_action('wp_ajax_nopriv_update_profile_photo', 'update_profile_photo');
function update_profile_photo() {
    $avatar_id = $_POST['avatar_id']; // Get the selected avatar ID from the AJAX request
    $user_id = get_current_user_id(); // Get the ID of the current user
    // Update user's profile photo with the selected avatar
    update_user_meta($user_id, 'profile_image', $avatar_id);
    // Optionally, return a response indicating success or failure
    wp_send_json_success('Profile photo updated successfully');
}
I’m developing a Discord bot in TypeScript that uses the Google Cloud Speech API to transcribe speech to text in real-time. I use the @discordjs/voice libraries to handle voice connections in Discord and @google-cloud/speech for voice transcription. I aim to capture user audio in a voice channel and send it to the Google Cloud API for transcription.
Although the bot can detect when a user starts speaking (using speaking events), there seems to be an issue with how the audio is captured and transmitted to the Google Cloud Speech API. I get a timeout error from the API indicating that the audio is not received on time or as expected. The exact error is:
ApiError: Audio Timeout Error: Long duration elapsed without audio. Audio should be sent close to real-time.
Here is the main segment of the code that handles the voice connection and sending audio:
const connection = joinVoiceChannel({
    channelId: voiceChannel.id,
    guildId: voiceChannel.guild.id,
    adapterCreator: voiceChannel.guild.voiceAdapterCreator,
    selfDeaf: false,
    selfMute: false,
});
const audioPlayer = createAudioPlayer({
    behaviors: {
        noSubscriber: NoSubscriberBehavior.Pause,
    },
});
connection.subscribe(audioPlayer);
connection.receiver.speaking.on('start', (userId) => {
    const audioStream = connection.receiver.subscribe(userId, { mode: 'pcm' });
    const request = {
        config: {
            encoding: 'LINEAR16',
            sampleRateHertz: 48000,
            languageCode: 'es-ES',
        },
        interimResults: false,
    };
    const recognizeStream = client.streamingRecognize(request)
        .on('data', (data) => {
            const transcription = data.results[0].alternatives[0].transcript;
            console.log(`Transcripción: ${transcription}`);
        });
    audioStream.on('data', (chunk) => {
        recognizeStream.write(chunk);
    });
    audioStream.on('close', () => {
        recognizeStream.end();
    });
});
encoding and sampleRateHertz settings.speaking events are working as expected and that the audio streams are created and closed properly.How can I ensure that audio captured from Discord is effectively streamed in real time to the Google Cloud Speech API to avoid the timeout error? Are there any settings or best practices in stream handling or API configuration that I may be overlooking?
Any help or suggestions would be greatly appreciated. Thanks in advance.
Let’s assume you’re writing a script using javascript. This script will run on any and every webpage.
Assume the webpage contains the name, phone and email of multiple users. Without relying on any classnames or tags, how would you process the page in such a way that the resulting data is an item of grouped contact info of a person.
Input: Any HTML that contains contact information
Expected Output: [{ name:"John Doe", email:"[email protected]", phone:"+15555555555" }, ...so on]
When asked to ChatGPT, it suggested the idea of distance and typically such information would be closer to each other, so the closest phone number to an email is most likely related to it
I’ve gotten it to work with email and phone, by simply matching the first email with first phone number found, second email with second phone number found etc.
I have a node project using GraphQL(v16.7.0) and the @graphql-tools/utils library, attempting to setup a nonEmptyArray custom schema directive to throw an error whenever a mutation is called with an empty array for an input. It would be used like this:
input ExampleInput {
  ids: [String!]! @nonEmptyArray
}
The code I have so far is:
const getNonEmptyArrayDirective = (schema: GraphQLSchema): SchemaMapper => ({
  [MapperKind.INPUT_OBJECT_FIELD]: (
    fieldConfig: GraphQLInputFieldConfig,
    fieldName: string,
    typeName: string,
  ) => {
    const directive = getDirective(schema, fieldConfig, 'nonEmptyArray')?.[0];
    if (directive) {
      fieldConfig.extensions = {
        ...fieldConfig.extensions,
        validateInput: inputValue => {
          console.log({inputValue})
          if (Array.isArray(inputValue)) {
            if (inputValue.length === 0) {
              throw new EmptyArrayError(fieldName);
            }
          }
          return inputValue;
        },
      };
    }
    return fieldConfig;
  },
});
export default function applySchemaDirectives(
  schema: GraphQLSchema,
): GraphQLSchema {
  schema = mapSchema(schema, getNonEmptyArrayDirective(schema));
  return schema;
}
and declaring the directive:
directive @nonEmptyArray on FIELD_DEFINITION | INPUT_FIELD_DEFINITION
So far I can’t even get the console.log({inputValue}) to execute. I’ve experimented with adding other MapperKind values such as MapperKind.SCALAR_TYPES and those do log properly, implying it’s not a problem with the general setup of the custom directive. My impression is that the issue has something to do with the way GraphQL specifically handles list types.
const initial = [
  { name: "Alice", price: 30, occupation: "Writer" },
  { name: "Bob", price: 50, occupation: "Teacher"}
]
    
   
const extraFreelancers = [
    { name: "Dr. Slice", price: 25, occupation: "Gardener" },
    { name: "Dr. Pressure", price: 51, occupation: "Programmer" },
    { name: "Prof. Possibility", price: 43, occupation: "Teacher" },
    { name: "Prof. Prism", price: 81, occupation: "Teacher" },
    { name: "Dr. Impulse", price: 43, occupation: "Teacher" },
    { name: "Prof. Spark", price: 76, occupation: "Programmer" },
    { name: "Dr. Wire", price: 47, occupation: "Teacher" },
    { name: "Prof. Goose", price: 72, occupation: "Driver" },
  ]; 
const maxLancers = 5;
render();
const addFreelancerInterval = setInterval(addFreelancer, 5000);
function render() {
    const container = document.querySelector(".container")
    for(let i = 0; i < initial.length; i++){
    const usersBox = document.createElement("div")
    usersBox.className = "usersBox"
    
    const name = document.createElement("p")
    const price = document.createElement("p")
    const occ = document.createElement("p")
    
    name.innerText = `${initial[i].name}`
    price.innerText = `$${initial[i].price}`
    occ.innerText = `${initial[i].occupation}`
    
    usersBox.appendChild(name)
    usersBox.appendChild(price)
    usersBox.appendChild(occ)
    
    container.appendChild(usersBox)
  }
}
function addFreelancer() {
    const freelancer = extraFreelancers[Math.floor(Math.random() * extraFreelancers.length)];
    initial.push(freelancer);
    render();
    
    if (initial.length >= maxLancers) {
      clearInterval(addFreelancerInterval);
    }
    averageStartingPrice();
}
const avg = document.createElement("p")
avg.className = "avg"
avg.innerText = `${averageStartingPrice()}`;
function averageStartingPrice() {
  const totalStartingPrice = initial.reduce((acc, freelancer) => acc += freelancer.price, 0);
  return totalStartingPrice / initial.length;
}
html {
    background-color: white;
}
body {
    background-color: white;
    height: 100vh;
    width: 100%;
    margin: 0;
}
.usersBox{
    display: flex;
    border-bottom: 2px solid black;
    text-align: center;
    font-size: 30px;
    padding: 10px;
    height: 100px;
    justify-content: center;
    align-items: center;
    justify-content: space-between;
    width: 1000px;
  }
#box {
    margin: auto;
    display: flex;
    justify-content: center;
    position: relative;
    flex-direction: column;
    align-items: center;
    border: 5px solid black;
    margin:100px;
    padding: 0px;
}
p {
    text-align: center;
    margin: auto;
}
#title {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 30px;
    padding: 10px;
    height: 200px;
    width: 1000px;
    flex-direction: column;
}
h1 {
    margin: 10px;
}
h2 {
    margin: 10px;
    margin-bottom: 20px;
}
#lists{
    justify-content: space-between;
    display: flex;
}
h3 {
    margin: 110px;
    margin-top: 0px;
    margin-bottom: 0px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Freelancer Forum</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    
    <div id="box">
        <div id="title">
            <h1>Freelancer Forum</h1>
            <p class="avg">The average starting price is 
            </p>
            <h2>Available Freelancers: </h2> 
            <div id="lists">
                <h3>Name</h3>
                <h3>Price</h3>
                <h3>Occupation</h3>
            </div>
        </div>
        <div class="container">  
        </div>
    </div>
        <script src="script.js"></script>
</body>
</html>
I have created two functions to display an array of objects onto an HTML page.
function render() {
    const container = document.querySelector(".container")
    for(let i = 0; i < initial.length; i++){
    const usersBox = document.createElement("div")
    usersBox.className = "usersBox"
    
    const name = document.createElement("p")
    const price = document.createElement("p")
    const occ = document.createElement("p")
    
    name.innerText = `${initial[i].name}`
    price.innerText = `$${initial[i].price}`
    occ.innerText = `${initial[i].occupation}`
    
    usersBox.appendChild(name)
    usersBox.appendChild(price)
    usersBox.appendChild(occ)
    
    container.appendChild(usersBox)
  }
}
The above function to display the array onto HTML.
function addFreelancer() {
    const freelancer = extraFreelancers[Math.floor(Math.random() * extraFreelancers.length)];
    initial.push(freelancer);
    render();
    
    if (initial.length >= maxLancers) {
      clearInterval(addFreelancerInterval);
    }
    averageStartingPrice();
}
And this function to add objects from another array to the initial array.
For some reason, the output on the HTML page is iterating the same initial array over and over again instead of just adding the new objects to the list. Below is a screenshot of what the output looks like (note the repeated “Alice” and “Bob” objects, which are the initial array).
I really have no idea where the issue is. I am very new to JavaScript and HTML so I apologize if it is something simple that was overlooked. Any help is greatly appreciated!
(https://github.com/antjuh/Unit2.FreelancerForum.git) GitHub for anyone interested in further details.
EDIT: Apologies, I have added JavaScript, HTML, and CSS to the post for easy access.
        let chart;
        document.addEventListener('dataLoaded', (data) => {
            options.series[0].data = data.detail[0][1];
            chart = new ApexCharts(document.getElementById("column-chart"), options);
            chart.render();
            document.getElementById('svg').addEventListener('click', function(e) {
                e.preventDefault();
                chart.dataURI().then((uri) => {
                    var link = document.createElement('a');
                    link.download = "chart.svg";
                    link.href = uri.svg;
                    link.click();
                });
            });
            document.getElementById('png').addEventListener('click', function(e) {
                e.preventDefault();
                chart.dataURI().then((uri) => {
                    var link = document.createElement('a');
                    link.download = "chart.png";
                    link.href = uri.png;
                    link.click();
                });
            });
            document.getElementById('csv').addEventListener('click', function(e) {
                e.preventDefault();
                chart.dataURI({
                    type: 'csv',
                    filename: 'chart.csv'
                }).then((csv) => {
                    var blob = new Blob([csv], {
                        type: 'text/csv'
                    });
                    var link = document.createElement('a');
                    link.download = "chart.csv";
                    link.href = URL.createObjectURL(blob);
                    link.click();
                });
            });
        });
Does anyone know the error code above, why when downloading Apexchart the file isn’t available on site error occurs?
Does anyone know the error code above, why when downloading Apexchart the file isn’t available on site error occurs?
I am trying to write a unit test that will test a useEffect that calls an api (let’s call it fetchData) so that when the component containing the useEffect unmounts or re-renders from the dependencies updating, we can test the cancellation path.
Here’s a mockup version of my code here:
export function useCustomHook(props: { foo: string }) {
  const [state, setState] = useState<any>();
  useEffect(() => {
    let isCancelled = false;
    fetchData()
      .then((response) => {
        if (isCancelled) {
          console.error('Fetch api request cancelled');
          return;
        }
        setState(response);
      });
    .error( // like the .then(), setState(error) if not cancelled only )
    return () => { isCancelled = true; }
  }, [foo]);
  return state;
}
i’m trying to make a test with the @testing-library/react library so that we test the setState wasn’t called if the dependency foo gets updated before fetchData finishes.
To ensure I get this, I mocked fetchData so that it uses setTimeout for 5 seconds and then returns a successful response per normal.
This is my jest test so far:
it('should not update state if cancelled' , () => {
  // assume it's properly mocked
  const mockFetchData = jest.fn().mockImplementation(async () => {
    return new Promise((resolve) => {
        setTimeout(() => {
          resolve(mockData);
        }, 5000); // simulate a long request so we can cancel it
      });
  });
  const { rerender } = renderHook(() =>
    useCustomHook({ foo: 'bar' });
  });
  rerender({ foo: 'baz' });
  expect(console.error).toHaveBeenCalled(); // this line fails
});
What am I missing here? The console.error never executes after the rerender and i put temporary console.logs everywhere to verify this (the last thing that executes is the effect’s cleanup function). Is there a way to test this condition?
I’m using the react-pro-sidebar library for a React project and facing an issue with the SubMenu component. When the sidebar is collapsed, an automatic marker (a small dot) appears next to the SubMenu items. I’ve tried various CSS methods to hide this marker, but none have been successful. The usual suspects like setting list-style: none; or targeting pseudo-elements haven’t worked. Here’s a snippet of how I’m implementing the SubMenu:
jsxCopy code
<SubMenu title=”Data” icon={<img src={dataIcon} alt=”Data Icon” />} className=”my-submenu” > <MenuItem>Sub-item 1</MenuItem> <MenuItem>Sub-item 2</MenuItem> </SubMenu>
I’ve attempted to override styles using both class selectors and pseudo-elements but to no avail. It seems like the library might be injecting these markers dynamically or through scripts.
Does anyone know how to specifically target and remove these markers, or is there a recommended approach for customizing or disabling them in react-pro-sidebar?
Library version: react-pro-sidebar v0.6.0
Browser: Chrome 89
React version: 17.0.1
Any help or pointers would be greatly appreciated!
I am having a problem when performing a push to a nested array, I am trying to add one or more objects within the nested array “fieldList”, when I execute the push it tells me ok but when I check it it has not updated it.
{
_id: ObjectId(‘6628363d6ed5718acbd2af72’),
label: ‘Movimiento Vehicular IDAAN’,
folders: [
{
name: ‘Datos Generales’,
fieldList: [],
_id: ObjectId(‘6628367b6ed5718acbd2af9f’)
},
{
name: ‘Datos de Vehículo y Conductor’,
fieldList: [],
_id: ObjectId(‘6628555de630217d0abafcc5’)
}
],
createdAt: ISODate(‘2024-04-23T22:29:17.213Z’),
updatedAt: ISODate(‘2024-04-24T00:42:05.879Z’)
}
I am trying to add it with $push and the dot notation { $push: { “folders.fieldList”: newfield}} tells me that it was executed ok but it is not added. This is the code I am using:
Object to add:
{
  "name": "Dia",
  "label": "Dia",
  "order": 11,
  "type": "number",
  "requ": true,
  "par": "Datos Generales"
}
Update Script:
export const newfieldwithfolder = async (req: Request, res: Response) => {
  try {
    const { name, label, order, type, requ, par } = req.body;
    const query = { _id: req.params.id };
    const updateQuery = new Fields({
      name,
      label,
      order,
      type,
      requ,
      par,
    });
    const newfield = { $push: { "folders.fieldList": updateQuery } };
    const result = await Template.updateOne(query, newfield);
    console.log(result);
    res.status(201).json({ message: "Fields have been added successfully!" });
  } catch (error) {
    console.error(error);
    res.status(500).json({ success: false, error: "Something went Wrong!" });
  }
};
I have multiple geolocations stored in a Redis database (version 7.2.4) in the following format:
GEOADD locations -46.63803300 (longitude) -23.53523600 (latitude) "270353275" (ID)
In Node.js (v13.5.0), I want to search for which geolocations are contained inside a given polygon.
Input: Geolocations of the polygon vertices are provided in the following format:
"bounds": [ { "lat": -23.534717280387206, "lng": -46.602115631103516 }, { "lat": -23.548251460987665, "lng": -46.623573303222656 }, ... ]
Output: IDs of the geolocations that are inside this polygon.
I’m trying to use the ‘redis-redisearch’ (^1.0.1) library with the ‘ioredis’ (v4.28.5) library in the following way:
`const redis = await getRedis() //returns new Redis client
redisearch(redis)
const results = await redis.ft_search(
“announces”,
@location:{${polygon_query}},
“RETURN”,
“1”,
“@location”
)`
However, I’m receiving the error “redis.addCommand is not a function”. How can I implement this functionality?”
This plugin in WordPress have a feature such that we can add LaTeX equation in display mode and show the preview in the block editor. https://wordpress.org/plugins/katex/
Now, I want to customize it so there is also feature such that we can add LaTeX equation in inline mode and show the preview (like Notion) in the block editor.
I am a newbie, can you help me? Or what should I learn to make this feature?
How can I prevent the lens from jumping when it is on the first image and show the result of the zoom correctly on the div of the zoom result?
And how can I make the lens appear on the other images, not just on the first one as it is in the gif? If not, follow the cursor and the position of the other images, it seems that the result of the zoom with the position of the cursor is correct.
I am using grid to display in a grid or ruler the images to which the zoom effect is applied.
this is my css code:
.imagen__cont__zoom .grid_contenedores {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 20px;
}
.imagen__cont__zoom .cont__img {
    width: 100%;
    overflow: hidden;
}
.imagen__cont__zoom .cont__img img {
    width: 300px;
    height: 300px;
    /*object-fit: cover;*/
}
.img__zoom__lente {
    position: absolute;
    border: 1px solid #d4d4d4;
    width: 40px;
    height: 40px;
}
.img__zoom__resultado {
    border: 1px solid #d4d4d4;
    width: 300px;
    height: 300px;
}
In the html I am adding several images to which I am applying zoom
this is my html code:
<div class="imagen__cont__zoom">
<div class="grid_contenedores">
<div class="cont__img">
<img class="img__zoom" src="https://source.unsplash.com/random/?city,night" alt="Girl">
</div>
<div class="cont__img">
<img class="img__zoom" src="https://source.unsplash.com/random/?space,night" alt="Girl">
</div>
<div class="cont__img">
<img class="img__zoom" src="https://source.unsplash.com/random/?montain,night" alt="Girl">
</div>
<div class="cont__img">
<img class="img__zoom" src="https://source.unsplash.com/random/?night" alt="Girl">
</div>
<div class="cont__img">
<img class="img__zoom" src="https://source.unsplash.com/random/?beach" alt="Girl">
</div>
<div class="cont__img">
<img class="img__zoom" src="https://source.unsplash.com/random/?vector" alt="Girl">
</div>
<div class="cont__img">
<img class="img__zoom" src="https://source.unsplash.com/random/?winter" alt="Girl">
</div>
</div>
<div class="img__zoom__lente"></div>
<div class="img__zoom__resultado"></div>
</div>
I think that the way I do the calculations for the position of the lens is wrong, that is why it is not shown according to the image where the lens is positioned, that is, in the real position of the cursor.
this is my javascript code:
    var imgs, lens, result, cx, cy;
imgs = document.querySelectorAll('.img__zoom');
result = document.querySelector('.img__zoom__resultado');
lens = document.querySelector('.img__zoom__lente');
// Función para mover la lente
function moveLens(e) {
var pos, x, y, img;
// Calcula la posición de la lente
pos = getCursorPos(e);
x = pos.x - (lens.offsetWidth / 2);
y = pos.y - (lens.offsetHeight / 2);
img = e.target;
// Evita que la lente se salga de la imagen
if (x > img.width - lens.offsetWidth) {x = img.width - lens.offsetWidth;}
if (x < 0) {x = 0;}
if (y > img.height - lens.offsetHeight) {y = img.height - lens.offsetHeight;}
if (y < 0) {y = 0;}
// Establece la posición de la lente
lens.style.left = x + "px";
lens.style.top = y + "px";
// Calcula la relación entre el resultado y la lente
cx = result.offsetWidth / lens.offsetWidth;
cy = result.offsetHeight / lens.offsetHeight;
// Ajusta el tamaño del resultado
result.style.backgroundSize = (img.width * cx) + "px " + (img.height * cy) + "px";
// Muestra el resultado
result.style.backgroundImage = "url('" + img.src + "')";
result.style.backgroundPosition = "-" + (x * cx) + "px -" + (y * cy) + "px";
}
// Función para obtener la posición del cursor
function getCursorPos(e) {
var a, x = 0, y = 0;
e = e || window.event;
a = e.target.getBoundingClientRect();
x = e.pageX - a.left;
y = e.pageY - a.top;
x = x - window.pageXOffset;
y = y - window.pageYOffset;
return {x : x, y : y};
}
// Agrega el evento de movimiento del mouse a cada imagen y a la lente
imgs.forEach(function(img) {
img.addEventListener("mousemove", moveLens);
});
lens.addEventListener("mousemove", moveLens);
I’m aware that if I want to add an item to an array BehaviorSubject I need to assign a copy of the entire array plus the new item using next().
However, I would like to push items into this array without having to assign an entire copy, I also have to perform other operations in this array, which seems complicated using BehaviorSubject.
Is there a way to accomplish what I want, or an alternative to BehaviorSubject that could help me? And whether there is or isn’t an alternative, is there a good library that helps with this?
Example:
export class ArrayService {
  currentArray = new BehaviorSubject<[]>([]);
  addItem(){
    let newItem = 'newItem';
    currentArray.next([...this.currentArray.getValue(), newItem]);
  }
}