Use (hidden) URL query parameters to re-use the email and password in the signup page?

I have a NextJS app with a login page. If the user enters a email that is not linked to an existing account, I want to show a button to redirect the user to the signup page.

Ideally, I would like the email and password entered in the login page to be pre-filled in the signup page.

I currently show a link:

<Link
  href={{
    pathname: '/signup',
    query: {
      email,
      password
    },
  }}
  as={'/signup'}
  passHref
>
  Go to signup
</Link>

The entered email and password are in the query params, but thanks to the as='/signup' property, they don’t show in the browser address bar.

In my signup page I can fetch them using:

const {
  query: {
    email,
    password
  }
} = useRouter()

I’m wondering if this is safe and a good practice, or if there is a better way?

[EDIT] Would it be safe to temporarily use sessionstorage?

Javascript not loading while logged out from WordPress

I’m inserting this script into my wordpress site using Elementor:

<script src="https://www.fourvenues.com/assets/iframe/"></script>

It looks great while I’m logged-in but as soon as I log-out I got this error on the console:

Uncaught TypeError: Cannot read properties of null (reading ‘style’)
at createIframe (events:45:11)
at script.onload (events:36:7)

I thought it might be some DOM content not loaded but used a DOMContentLoaded script but no results.

How can I modify javascript native fetch function from an extension?

I was trying to intercept and modify browser network requests response. To be exact I need to modify responses based on request url. From searching the Internet I came up with a code which is working fine in browser console also with tampermonkey extension.

But when I tried to make it into an extension it is not working. There is no error, even the code is working but in the context of the extension. Like if i fetch something in the extension after this interceptor, that request and response are getting logged. But not working on the site’s context.

This is what I came up with the help of Internet:

const originalFetch = window.fetch;

window.fetch = function(url, options) {
  return originalFetch(url, options)
    .then(response => {
      console.log(`Request URL: ${url}`);

      if (response.headers.get('content-type').includes('application/json')) {
        return response.json().then(json => {
          json.modified = true;
          console.log('Modified JSON Response:', json);
          return new Response(JSON.stringify(json), response);
        });
      }

      console.log('Response:', response);
      return response;
    });
};

I am using manifest v3 for the extension.

Thanks in advance. Kindly let me know if this does not clarifies the problem enough.

Automatically importing a util module into every file in NodeJS

Is there a way to automatically import a module into every file without using a global variable? In Webpack, I can use ProvidePlugin which automatically injects import util from './util.js' into every file that references util.

E.g.

plugins: [
  new webpack.ProvidePlugin({
    'util': './util.js',
  })
],

My goal is to avoid the grief of having to add import definition lines for commonly used utility or configuration modules.

Thanks

dropdown error: Cannot read properties of undefined (reading ‘parentNode’)

I am in the process of adapting the selectpicker code which is in Jquery to Native JavaScript
i got this problem since 3 weeks, that I don’t know how to resolve it

dropdown default focus

focus blue background that I want to use
-normally the focus should be on the first element, but we must click on the ‘keydown’ button before the focus is on the first element,
-also I would like to use the focus with the blue background, not the default dropdown focus

in add, I get this error every time I do a keydown

dropdown.js:97 Uncaught TypeError: Cannot read properties of undefined (reading 'parentNode')
    at new hi (dropdown.js:97:34)
    at hi.getOrCreateInstance (base-component.js:65:41)
    at HTMLUListElement.dataApiKeydownHandler (dropdown.js:418:31)
    at HTMLDocument.n (event-handler.js:118:19)

this link of my code:
https://gist.github.com/ZoubaGate/f7bd2cba2f40643dce45863d135e04b0

How can I create a javascript animation that recognizes when it hits things, in other words a hit box?

I am currently building a piano with visualizer in React. The users can record their song and play it back. This recording records a list of notes + start/end timestamps. I currently have note visualizations that start from the top of the screen and expand their height for end timestamp – start timestamp. Then the note falls down from the top until it is offscreen and is deleted. Both of these are done using animations with fill forward.

My problem is: I need the note sound to play when the visualizations hit the keys, and currently, basing this off of a timeout is causing me issues. It would make a lot more sense to me to base this sound off of the animated visualization hitting the key div but I am not sure how to do this.

Additionally, storing the animations for being able to pause and resume is causing me a lot of issues and I was wondering if there was a more concrete method of doing this. Pausing and resuming the animations is really finicky. I do not want to save it as a video.

Piano

Animation

export const attribute_animation = (object, attribute, start, end, duration, easing) => {
    return object.animate(
        [{[attribute]: start}, { [attribute]: end}],
        {duration: duration, fill: 'forwards', easing: easing}
    )
}

I animate first expanding the height attr, then the top attr. How can I have a specific div with ref recognize if it is hitting another div? (visualization hitting key)

Piano Component

  let [playing, set_playing] = useState(null)
  let start_note_index = useRef(0)
  let end_note_index = useRef(0)
  let song_player = useRef(null)
  let sp_start_time = useRef(null)
  let sp_anim_frameid = useRef(null)
function song_playback() {
  
      function animate(timestamp) {
        if (!sp_start_time.current) {
          sp_start_time.current = timestamp
        }
        if (start_note_index.current < song.length && 
          song[start_note_index.current]['note']['start_timestamp'] <= timestamp - sp_start_time.current) {
          
          let pkey_index = pkey_to_pkeyind[song[start_note_index.current]['note']['note']]
          set_piano(prev_state => {
            const keys = [...prev_state]
            keys[pkey_index] = React.cloneElement(keys[pkey_index], { pb_visual_mode: 'expand_down' })
            return keys
          })
          start_note_index.current += 1
        }
        if (end_note_index.current < song.length && 
          song[end_note_index.current]['note']['end_timestamp'] <= timestamp - sp_start_time.current) {
          
          let pkey_index = pkey_to_pkeyind[song[end_note_index.current]['note']['note']]
          set_piano(prev_state => {
            const keys = [...prev_state]
            keys[pkey_index] = React.cloneElement(keys[pkey_index], { pb_visual_mode: 'move_down' })
            return keys
          })
          end_note_index.current += 1
          }
          if (start_note_index.current >= song.length && end_note_index.current >= song.length) {
            set_playing(null)
            cancelAnimationFrame(sp_anim_frameid.current)
          } else {
            if (playing === 'playing') {
              sp_anim_frameid.current = requestAnimationFrame(animate)
            }
          }
        
      }
    
      function pause() {
        cancelAnimationFrame(sp_anim_frameid.current)
        set_piano(prev_state => {
          const keys = [...prev_state]
          for (let i = 0; i < keys.length; i++) {
            keys[i] = React.cloneElement(keys[i], { pb_visual_mode: 'pause' })
          }
          return keys
        })
      }
    
      function resume() {
        requestAnimationFrame(animate)
        set_piano(prev_state => {
          const keys = [...prev_state]
          for (let i = 0; i < keys.length; i++) {
            keys[i] = React.cloneElement(keys[i], { pb_visual_mode: 'resume' })
          }
          return keys
        })
      }
    
      function reset() {
        sp_start_time.current = null
        start_note_index.current = 0
        end_note_index.current = 0
      }

      return { pause, resume, reset }
    }
    song_player.current = song_playback()
  }, [song, playing])

Piano Key Component

  let [playback_visuals, set_playback_visuals] = useState([])
  let pb_counter = useRef(0)
  let curr_pb_anim = useRef([[], true])
  let playback_visual_refs = useRef({})
  let timeouts = useRef({})
  let timeouts_counter = useRef(0)
useEffect(() => {
    if (playback_visuals[pb_counter.current] && curr_pb_anim.current[1]) {
      curr_pb_anim.current[0].push(attribute_animation(playback_visual_refs.current[pb_counter.current], 'height', '0', '300000px', 1000000))
      curr_pb_anim.current[1] = false
    }
    
  }, [playback_visuals])

  useEffect(() => {
    if (pb_visual_mode === 'expand_down') {

      let curr_counter = timeouts_counter.current
      const timeout_id = new Timer((curr_counter) => {
        audio.current.play()
        delete timeouts.current[curr_counter]
      }, 2000, curr_counter)

      timeouts.current[timeouts_counter.current] = timeout_id
      timeouts_counter.current += 1

      set_playback_visuals(prev_state => {
        curr_pb_anim.current[1] = true

        return ({...prev_state,
          [pb_counter.current]: (
          <div key={`${pb_counter.current}`} ref={ref => playback_visual_refs.current[pb_counter.current] = ref} className='pb-visualizer-instance'></div>
          )
        })
      })
    } else if (pb_visual_mode === 'move_down' && curr_pb_anim.current[0]) {

      console.log(curr_pb_anim.current, note)
      curr_pb_anim.current[0][curr_pb_anim.current[0].length-1].pause()
      
      curr_pb_anim.current[0][curr_pb_anim.current[0].length-1] = attribute_animation(playback_visual_refs.current[pb_counter.current], 'top', '0', '300000px', 1000000, 'linear')
      curr_pb_anim.current[1] = true


      let curr_t_counter = timeouts_counter.current
      let curr_pb_counter = pb_counter.current
      const timeout_id = new Timer((curr_t_counter, curr_pb_counter) => {
        delete timeouts.current[curr_t_counter]
        delete playback_visual_refs.current[curr_pb_counter]
        delete curr_pb_anim.current[curr_pb_counter]
        set_playback_visuals(prev_state => {
          const new_state = Object.keys(prev_state).filter(key => key !== curr_pb_counter).reduce((acc, key) => {
            acc[key] = prev_state[key]
            return acc
          }, {})
          return new_state
        })
      }, 3000, curr_t_counter, curr_pb_counter)

      timeouts.current[timeouts_counter.current] = timeout_id
      timeouts_counter.current += 1

      pb_counter.current += 1

    } else if (pb_visual_mode === 'pause') {
      
      for (let i = 0; i < curr_pb_anim.current[0].length; i++) {
        console.log("pause", curr_pb_anim.current, note)
        curr_pb_anim.current[0][i].pause()
      }
    
      for (let timer_key in timeouts.current) {
        timeouts.current[timer_key].pause()
      }

      
      
    } else if (pb_visual_mode == 'resume') {
      for (let i = 0; i < curr_pb_anim.current[0].length; i++) {
        console.log("resume", curr_pb_anim.current, note)
        curr_pb_anim.current[0][i].play()
      }

      for (let timer_key in timeouts.current) {
        timeouts.current[timer_key].resume()
      }
    }
  }, [pb_visual_mode])

Simplify complexity [closed]

I came across this questions which asks to create a function which will return true/false based on the passed array containing all the letters to make up the passed word. Each letter from array can only be used once.

Here’s my attempt:

const checkArray = (word, arr) => {
    let good = true
    word.split('').forEach(letter => {
        const letterIdx = arr.findIndex(arrLetter => arrLetter === letter)
        if (letterIdx === -1) good = false

        arr.splice(letterIdx, 1)
    })

    return good
}

const word = 'goal'
const arr1 = ['g', 'o','a','l','x','a','d'] // true
const arr1 = ['g', 'r','a','l','x','a','d'] // false

With my approach, a loop inside a loop is used. Whats a better (less complexity) way of solving this issue?

Azure Open AI Embedding Skillset – Error in skill ‘Azure OpenAI Embedding skill’: ‘uri’ parameter cannot be null or empty

I am working on integrating Azure OpenAI’s embedding skill into my skillset for Azure Cognitive Search, but I’m encountering a RestError when I try to create or update the skillset. The splitSkill works fine, but the embeddingSkill throws an error despite the resourceUri being correctly set.

Here’s the error message I receive:

Failed to create or update skillset: RestError: One or more skills are invalid. Details: Error in skill 'Azure OpenAI Embedding skill': 'uri' parameter cannot be null or empty 
 {
  "name": "RestError",
  "code": "",
  "statusCode": 400,
  "request": {
    "url": "https://ai-search-service-dev-basic.search.windows.net/skillsets('samplel-skillset')?api-version=2023-11-01",
    "headers": {
      "content-type": "application/json",
      "accept": "application/json;odata.metadata=minimal",
      "prefer": "REDACTED",
      "accept-encoding": "gzip,deflate",
      "user-agent": "azsdk-js-search-documents/12.0.0 core-rest-pipeline/1.12.2 Node/v21.6.2 OS/(arm64-Darwin-23.2.0)",
      "x-ms-client-request-id": "818afa6b-5ffe-44ba-bd1a-301fd95b9ce2",
      "api-key": "REDACTED",
      "content-length": "692"
    },
    "method": "PUT",
    "timeout": 0,
    "disableKeepAlive": false,
    "streamResponseStatusCodes": {},
    "withCredentials": false,
    "tracingOptions": {
      "tracingContext": {
        "_contextMap": {}
      }
    },
    "requestId": "818afa6b-5ffe-44ba-bd1a-301fd95b9ce2",
    "allowInsecureConnection": false,
    "enableBrowserStreams": false
  },
  "details": {
    "error": {
      "code": "",
      "message": "One or more skills are invalid. Details: Error in skill 'Azure OpenAI Embedding skill': 'uri' parameter cannot be null or empty"
    }
  },
  "message": "One or more skills are invalid. Details: Error in skill 'Azure OpenAI Embedding skill': 'uri' parameter cannot be null or empty"
}
Creating or updating indexer: samplel-indexer...
Failed to create or update indexer: RestError: This indexer refers to a skillset 'samplel-skillset' that doesn't exist 
 {
  "name": "RestError",
  "code": "",
  "statusCode": 400,
  "request": {
    "url": "https://ai-search-service-dev-basic.search.windows.net/indexers('samplel-indexer')?api-version=2023-11-01",
    "headers": {
      "content-type": "application/json",
      "accept": "application/json;odata.metadata=minimal",
      "prefer": "REDACTED",
      "accept-encoding": "gzip,deflate",
      "user-agent": "azsdk-js-search-documents/12.0.0 core-rest-pipeline/1.12.2 Node/v21.6.2 OS/(arm64-Darwin-23.2.0)",
      "x-ms-client-request-id": "f6a9e94b-7b39-4238-a387-bfd1b50ded41",
      "api-key": "REDACTED",
      "content-length": "275"
    },
    "method": "PUT",
    "timeout": 0,
    "disableKeepAlive": false,
    "streamResponseStatusCodes": {},
    "withCredentials": false,
    "tracingOptions": {
      "tracingContext": {
        "_contextMap": {}
      }
    },
    "requestId": "f6a9e94b-7b39-4238-a387-bfd1b50ded41",
    "allowInsecureConnection": false,
    "enableBrowserStreams": false
  },
  "details": {
    "error": {
      "code": "",
      "message": "This indexer refers to a skillset 'samplel-skillset' that doesn't exist"
    }
  },
  "message": "This indexer refers to a skillset 'samplel-skillset' that doesn't exist"
}

Below is the code snippet where I define my embeddingSkill:

// Creating Skillsets
async function createOrUpdateSkillset() {
    const endpoint = process.env.AZURE_SEARCH_ENDPOINT || "";
    const apiKey = process.env.AZURE_SEARCH_ADMIN_KEY || "";
    const indexName = process.env.AZURE_SEARCH_INDEX_NAME;
    const azureOpenaiEndpoint = process.env.AZURE_OPENAI_ENDPOINT;
    const azureOpenaiDeployment = process.env.AZURE_OPENAI_DEPLOYMENT_NAME;
    const azureOpenaiKey = process.env.AZURE_OPENAI_API_KEY;

    const indexerClient = new SearchIndexerClient(endpoint, new AzureKeyCredential(apiKey));
    const skillsetName = `${indexName}-skillset`;

    // Define the split skill
    const splitSkill = {
        name: "Split skill",
        description: "Split skill to chunk documents",
        odatatype: "#Microsoft.Skills.Text.SplitSkill",
        textSplitMode: "pages",
        context: "/document",
        maximumPageLength: 2000,
        pageOverlapLength: 500,
        inputs: [
            { name: "text", source: "/document/content" }
        ],
        outputs: [
            { name: "textItems", targetName: "pages" }
        ]
    };
    
    // Define the embedding skill
    const embeddingSkill = {
        odatatype: "#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill",  
        name: "Azure OpenAI Embedding skill",
        description: "Skill to generate embeddings via Azure OpenAI",
        context: "/document/pages/*",
        resourceUri: azureOpenaiEndpoint, // "https://<resource_name>.openai.azure.com/"
        apiKey: azureOpenaiKey,
        deploymentId: azureOpenaiDeployment,
        
        inputs: [
            { name: "text", source: "/document/pages/*" }
        ],
        outputs: [
            { name: "embedding", targetName: "vector" }
        ],
        authIdentity: null
    };
    
    // Define the skillset
    let skillset = {
        name: skillsetName,
        description: "Skillset to chunk documents and generating embeddings",
        skills: [splitSkill, embeddingSkill],
        indexProjections: {
          selectors: [
              {
                  targetIndexName: indexName,
                  parentKeyFieldName: "parent_id",
                  sourceContext: "/document/pages/*",
                  mappings: [
                      { name: "chunk", source: "/document/pages/*" },
                      { name: "vector", source: "/document/pages/*/vector" },
                      { name: "title", source: "/document/metadata_storage_name" }
                  ]
              }
          ],
          parameters: { projectionMode: "skipIndexingParentDocuments" }
      }
    };

    console.log(`Creating or updating skillset: ${skillsetName}...`);
    await indexerClient.createOrUpdateSkillset(skillset); // Make sure this method exists or find the equivalent
    console.log(`Skillset '${skillsetName}' created or updated successfully.`);
}

I have verified that the resourceUri is correctly set and points to my Azure OpenAI resource. The splitSkill related part of the process works as expected, and the issue only arises when adding the embeddingSkill.

Can someone help me identify what might be causing this uri parameter error with the Azure OpenAI Embedding skill?

I’m successfully using a random background image script but would also like to add an image specific background position as well

I’m currently using this successfully:

<script>
    var imgCount = 15;
        var dir = 'wp-content/themes/Stoq/home-images/';
        var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
        var images = new Array
                images[1] = "1.jpeg",
                images[2] = "2.jpeg",
        images[3] = "3.jpeg",
        images[4] = "4.jpeg",
        images[5] = "5.jpeg",
        images[6] = "6.jpeg",
        images[7] = "7.jpeg",
        images[8] = "8.jpeg",
        images[9] = "9.jpeg",
        images[10] = "10.jpeg",
        images[11] = "11.jpeg",
        images[12] = "12.jpeg",
        images[13] = "13.jpeg",
        images[14] = "14.jpeg",
        images[15] = "15.jpeg",
        document.getElementById("random-bkg-img").style.backgroundImage = "url(" + dir + images[randomCount] + ")";
   </script>

However, with each image I would like to be able to assign a background image position. So each image would have a url, plus either a class or inline css to give each random image an adjustable background-position.

Just not sure how to accomplish that so that these two values are associated with each image.

I’ve searched for a solution for a couple hours and couldn’t find anything like this. The expectation is that I can add the background position to each image.

Sem informaçoes [closed]

Tenho dificuldade em achar respostas para minhas perguntas estou começando agr
e nao me vejo sendo aquele programador que ja faz tudo mto rapido
e mesmo assim eu tbm nao consigo achar as respostas para minhas perguntas tipo eu quero criar um gerenciador de estoque ai eu mais ou menos crio a logica e vejo o que eu preciso para vou no google e escrevo
“como fazer para adicionar um elemento em uma lista ” e se nao for no chat gpt ou alguma ia eu sinto que nao tem o que eu realmente quero
alguem pode me passar uma visao do que fazer pq e uma area quew eu realmente quero insistir e me deixa animado meu problema e que eu nao achei uma fonte de informaçao ao certo

nao sei o que fazer akakakaka

How do I record that this ionic checkbox has been checked by the user?

I am trying to record that the user has checked the checkbox, and am not sure where to start. this is using the ionic framework with vanilla JS.

I have the tag for a checkbox:

<ion-list>
       <ion-checkbox id="Email-check">Email</ion-checkbox>
<ion-list>

A variable that is refering to the ID in the tag:

const emailCheckbox = this.querySelector('#Email-check');
And an empty function:

function storeemailCheck(){
        
    }

error when the parser reaches a newline token while using nearley.js

i am building a small programming language and i am using nearley.js for parsing i am defining the grammar and the grammar syntax is working fine except in one case which is the newline token

this is the grammar

statement -> var_assign {% id %}
            | fun_call {% id %}
            | function_def {% id %}
            | conditional {% id %}
            | loop {% id %}


statements
    -> statement %NL
        {% 
            (data) => {
                return [data[0]];
            }
        %}
    |  statements %NL statement %NL
        {%
            (data) => {
                return [...data[0], data[2]];
            }

this is the error
Error while parsing Error: invalid syntax at line 1 col 19:

1 @name = “mohammad”
^
2 call print(name)
Unexpected input (lexer error). I did not expect any more input. Here is the state of my parse table:

expression → %string ●
var_assign → %var_declaration %identifier _ "=" _ expression ●
statement → var_assign ●

IAM ONLY FACING THE ERROR IN CASE OF NEWLINE TOKEN EVERYTHIHNG ELSE IS WORKING FINE

I’m having problem with my combined chart with 2 data

I have a chart that displays for both water and smoke, it fetch from my firebase project. why is it when I add data for my water to be display in the graph, it waits for the smoke data to be displayed first before showing the water data in the graph?

    var database = firebase.database();
    var ctx = document.getElementById('combinedChart').getContext('2d');
    var combinedChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: 'Smoke Sensor Value',
                data: [],
                backgroundColor: 'rgba(255, 99, 132, 0.2)',
                borderColor: 'rgba(255, 99, 132, 1)',
                borderWidth: 1
            },
            {
                label: 'Water Sensor Value',
                data: [],
                backgroundColor: 'rgba(54, 162, 235, 0.2)',
                borderColor: 'rgba(54, 162, 235, 1)',
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: true
                    }
                }]
            }
        }
    });
    database.ref('smokeNumber').on('value', function(snapshot) {
        var smokeData = snapshot.val();
        var time = new Date().toLocaleTimeString();
        combinedChart.data.labels.push(time);
        combinedChart.data.datasets[0].data.push(smokeData);
        if (combinedChart.data.labels.length > 10) {
            combinedChart.data.labels.shift();
            combinedChart.data.datasets[0].data.shift();
        }
        combinedChart.update();
    });

    database.ref('waterNumber').on('value', function(snapshot) {
        var waterData = snapshot.val();
        var time = new Date().toLocaleTimeString();
        combinedChart.data.datasets[1].data.push(waterData);
        if (combinedChart.data.labels.length > 10) {
            combinedChart.data.datasets[1].data.shift();
        }
        combinedChart.update();
    });

I want to display both my data in the chart simultaneously not waiting one of the data to display first before showing the other data.