sh: tailwind: command not found [closed]

enter image description here

I am developing a project of a blog system, and while being in the early stages of that, while setting up the project, while setting up tailwind, I got this error.

this terminal screenshot shows all the errors and I am not able to run script: npx tailwindcss init -p and it shows the error sh: tailwind: command not found

Terminal showing error

Issues with Render.js: Problems with Puppeteer and Parallel Rendering

I’m having trouble with a Node.js script (render.js) that uses Puppeteer for rendering videos and images in parallel. The script creates a renderer that generates frames based on an HTML page and then combines them into either PNG files or video files using FFmpeg. The script uses multiple worker processes to handle rendering concurrently.

You can find the code for this project on GitHub here: https://github.com/dtinth/html5-animation-video-renderer

However, I’m encountering an issue where the rendering process is not functioning as expected. Here’s an overview of the problem:

Error:
When I run the command:

node render --url="file:///D:/Desktop/airports/New%20folder/Flourish%20template_%20Bar%20chart%20race.htm" --png="D:/Desktop/airports/New%20folder/PNG_output" --no-video

I get the following error output:

Spawn worker 1
Worker 1: getInfo
render

Renders a video

Options:
  --version      Show version number                                   [boolean]
  --help         Show help                                             [boolean]
  --url          The URL to render
                                [string] [default: "file://D:DesktopNew folder
                                 (5)PNG/examples/gsap-hello-world.html?render"]
  --video        The path to video file to render. Without `--alpha` this MUST
                 be .mp4, and with `--alpha` this MUST be .mov
                                                 [string] [default: "video.mp4"]
  --parallelism  How many headless Chrome processes to use to render in parallel
                                                           [number] [default: 8]
  --start        Frame number to start rendering           [number] [default: 0]
  --end          Frame number to end rendering (that frame number will not be
                 rendered)                                              [number]
  --png          Directory for PNG frame output                         [string]
  --alpha        Renders a image/video with alpha transparency. For video, the
                 file extension MUST be .mov                           [boolean]
  --scale        Device scale factor                       [number] [default: 1]

Error: Evaluation failed: ReferenceError: getInfo is not defined
    at __puppeteer_evaluation_script__:9:22
    at ExecutionContext._evaluateInternal (D:DesktopNew folder (5)PNGnode_modulespuppeteerlibcjspuppeteercommonExecutionContext.js:175:23)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async ExecutionContext.evaluate (D:DesktopNew folder (5)PNGnode_modulespuppeteerlibcjspuppeteercommonExecutionContext.js:110:16)
    at async D:DesktopNew folder (5)PNGrender.js:21:20
    at async Object.getInfo (D:DesktopNew folder (5)PNGrender.js:48:17)
    at async work (D:DesktopNew folder (5)PNGrender.js:128:24)
    at async Object.main [as handler] (D:DesktopNew folder (5)PNGrender.js:261:20)

The error suggests that there is an issue with getInfo not being defined. However, I’m not sure why it is failing or where I should define this function.

What I’ve tried:

  • Ensuring that the getInfo function is properly defined and
    accessible.
  • Verifying that the script is correctly passing information between
    workers and handling the necessary functions.
  • Adding more logging to track down the flow of execution, but the
    issue persists.

The goal:
I want the script to render frames from the provided URL and output PNGs to the specified directory without creating a video, but it’s failing with this getInfo is not defined error.
Has anyone worked with Puppeteer and parallel rendering in Node.js and encountered similar issues? Any suggestions on how to properly define or handle the getInfo function, or how to debug this further, would be greatly appreciated!

Thanks in advance for your help!

Data not rendering in Mantine’s Select Component

The cities data is coming from an Api cityOptions is being logged to
the console, but
when I try to show it in the UI in a dropdown, no data shows.

const cityOptions = cities?.map((city) => ({
    value: city.id.toString(),
    label: city.name,
  })) || [];
  console.log("cityoptions", cityOptions)

<Select
  name="city"
  placeholder="Cities"
  value={city || null}
  maw={200}
  size="md"
  data={isLoading ? []: cityOptions}
  disabled={isLoading}
  onChange={(value) => setCity(value as string)}
  icon={<IconSelector size={18} stroke={1.75} />}
  clearable
  style={{ marginBottom: 0 }}
/>

How can I redirect correctly after logging into Twitter?

When the user is logged in, the code works correctly, the user authorizes the app and redirects me correctly to –> api/x/callback, the problem is when I have a user who is not logged in to X, when I access –> api/auth/x/callback, it redirects me to X’s login, I log in correctly, but it does not redirect me correctly to the (Authorize App) page, but instead it redirects me to X’s profile, does anyone know a solution to this problem, I would greatly appreciate your help

this is –> api/auth/x/callback

import { NextResponse } from 'next/server'
import crypto from 'crypto'

const X_CLIENT_ID = process.env.X_CLIENT_ID as string
const REDIRECT_URI = `${process.env.NEXT_PUBLIC_URL}${process.env.NEXT_PUBLIC_X_REDIRECT_URI}`

export async function GET() {
  if (!X_CLIENT_ID) {
    return NextResponse.json(
      { error: 'X_CLIENT_ID is not defined' },
      { status: 500 }
    )
  }

  const codeVerifier = crypto.randomBytes(32).toString('hex')
  const codeChallenge = crypto
    .createHash('sha256')
    .update(codeVerifier)
    .digest('base64url')

  const response = NextResponse.redirect(
    `https://twitter.com/i/oauth2/authorize?${new URLSearchParams({
      response_type: 'code',
      client_id: X_CLIENT_ID,
      redirect_uri: REDIRECT_URI,
      scope: 'tweet.read tweet.write users.read offline.access',
      state: crypto.randomBytes(16).toString('hex'),
      code_challenge: codeChallenge,
      code_challenge_method: 'S256'
    })}`
  )

  response.cookies.set('code_twitter_verifier', codeVerifier, {
    httpOnly: true,
    secure: true,
    sameSite: 'lax',
    path: '/'
  })

  return response
}

this is –> api/x/callback

import { NextResponse } from 'next/server'
import { cookies } from 'next/headers'

const X_CLIENT_ID = process.env.X_CLIENT_ID as string
const X_CLIENT_SECRET = process.env.X_CLIENT_SECRET as string
const REDIRECT_URI = `${process.env.NEXT_PUBLIC_URL}${process.env.NEXT_PUBLIC_X_REDIRECT_URI}`

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url)
  const code = searchParams.get('code')

  if (!code) {
    const redirectUrl = new URL(
      '/admin/organizations',
      request.url
    )

    return NextResponse.redirect(redirectUrl)
  }

  const codeVerifier = cookies().get('code_twitter_verifier')?.value
  if (!codeVerifier) {
    return NextResponse.json(
      { error: 'code_verifier not found' },
      { status: 400 }
    )
  }

  const credentials = Buffer.from(`${X_CLIENT_ID}:${X_CLIENT_SECRET}`).toString(
    'base64'
  )

  const tokenResponse = await fetch('https://api.twitter.com/2/oauth2/token', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Authorization: `Basic ${credentials}`
    },
    body: new URLSearchParams({
      grant_type: 'authorization_code',
      code,
      redirect_uri: REDIRECT_URI,
      code_verifier: codeVerifier
    }).toString()
  })

  const tokenData = await tokenResponse.json()

  if (!tokenResponse.ok) {
    return NextResponse.json(
      { error: 'No se pudo obtener el token' },
      { status: 401 }
    )
  }

  const { access_token, refresh_token, expires_in } = tokenData

  const userResponse = await fetch('https://api.twitter.com/2/users/me', {
    headers: {
      Authorization: `Bearer ${access_token}`
    }
  })

  const userData = await userResponse.json()

  const { id, username } = userData.data

  if (!userResponse.ok) {
    return NextResponse.json({ error: 'User not found' }, { status: 401 })
  }

  const redirectUrl = new URL(
    '/admin/organizations/channels/twitter',
    request.url
  )
  redirectUrl.searchParams.append('accessToken', access_token)
  redirectUrl.searchParams.append('refreshToken', refresh_token)
  redirectUrl.searchParams.append('userId', id)
  redirectUrl.searchParams.append('screenName', username)
  redirectUrl.searchParams.append('expiresIn', expires_in)

  return NextResponse.redirect(redirectUrl)
}

Why does vite use dirname(fileURLToPath(import.meta.url))?

The vite build documentation gets the directory of vite.config.js like this:

const __dirname = dirname(fileURLToPath(import.meta.url))

And I was curious why it’s being done like this. According to this question we can get the __dirname directory via import.meta.dirname for more recent versions of node, so is const __dirname = dirname(fileURLToPath(import.meta.url)) just an older way of doing it?

parse: expected property name or ‘}’

error code

const exp = JSON.parse('<%= JSON.stringify(cafe.reviews || []) %>');

& # 3 9 ; causing issue. ans tried every thing around the internet but still having same error..

code:

<script>
    const exp = JSON.parse('<%= JSON.stringify(cafe.reviews || []) %>');

    function escapeHTML(str) {
        return str.replace(/[&<>"']/g, match => ({
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#39;'
        }[match]));
    }

    const experience = document.querySelector('.usersExperience');
    if (experience) {
        experience.innerHTML = exp.map(review => `
          <div>
            <h4>${escapeHTML(review.userId?.name || "N/A")}</h4>
            <h3>${escapeHTML(review.userId?.dietaryIdentity || "N/A")}</h3>
            <p>${escapeHTML(review.review || "N/A")}</p>
          </div>
        `).join("");
    }
  </script>

guys. What am i doing wrong

textRange.Words not found? Visual Studio js addin

I am making an addin using visual studio powerpoint web app addin template.
Below code Im attempting to set the first 3 words to bold. A breakpoint before this shows that the “words” member is not in the textRange object. I have tried to access .Words in various ways with and without the (). The error message either says “TypeError: shape.textFrame.textRange.Words is not a function” or “Words is undefined”. I have tried upper and lowercase as well. visual studio is 2022

 if (shape.textFrame.textRange.text && shape.textFrame.textRange.text.length > 0) {

         shape.textFrame.textRange.load("Words");
         await context.sync();

         let words = shape.textFrame.textRange.Words;
         console.log(words);
         shape.textFrame.textRange.Words(3).Font.Bold = true;

How to prevent innerHTML changes to cancel dragging of the element?

The code is visible at https://www.handsearseyes.fun/Ears/EarTrainer/EarTrainer.php?EDO=44&UpToTritave=&Sound=clarinet&Format=mp3&RatioBasedScale= -> press the ‘Play Interval’ Button and a Timer will appear which is driven through JavaScript. Here’s the JS driving the timer and Timer tag :

<script>
                    function StartTimer() {
                        TimerInterval = setInterval(function() {
                        var NewDate = new Date();
                        var Now = NewDate.getTime();
                        Elapsed = Math.round((Now - GameStartTime) / 1000);
                        var MinutesElapsed = 0;
                            while (60 <= Elapsed) {
                            Elapsed = Elapsed - 60;
                            MinutesElapsed++;
                            }
                        var SecondsElapsed = Elapsed;
                            if (SecondsElapsed < 10) {
                            SecondsElapsed = '0'+SecondsElapsed;
                            }
                        document.getElementById('Timer').innerHTML = MinutesElapsed+':'+SecondsElapsed;
                        },100);
                    }
</script>

[...]

<!-- Timer -->
<div id='Timer' draggable=true style='position:absolute; z-index:1; top:32px; width:125px; height:55px; text-align:center;
font-family:segoe ui variable display; color:#5D729F; cursor:grab' onDragStart="GrabElement(this,event,'EarTrainer.php');"
onDragEnd='ReleaseElement();' onMouseEnter='SwitchHooveredElementTo(this);' onMouseLeave='FalsifyHooveredElement();'></div>

All events on the tag drive the element’s resizing and moving functionalities, but when you try to grab the timer to displace it, you have to grab and move within the same second or your drag is lost. It seems resizing it up (SHIFT + MOUSE WHEEL UP while hoovering it) before trying to drag it cancels this negative effect, somehow (that impression may just be the fruit of luck on life’s rng and too few tests though).

Any idea of a work around?

MathJax’s Loader Option with TypeScript

I try to integrate xyjax-v3 into my VitePress project , but I failed . VitePress use markdown-it-mathjax to render math equations . It supports all extensions listed here except xyjax-v3 .

To make it possible to support xyjax-v3 , I git clone the entire markdown-it-mathjax . Here is part of the index.ts :

...
import { mathjax } from "mathjax-full/js/mathjax.js";
import { TeX } from "mathjax-full/js/input/tex.js";
import { SVG } from "mathjax-full/js/output/svg.js";
import { liteAdaptor } from "mathjax-full/js/adaptors/liteAdaptor.js";
import { RegisterHTMLHandler } from "mathjax-full/js/handlers/html.js";
import { AllPackages } from "mathjax-full/js/input/tex/AllPackages.js";
import { AssistiveMmlHandler } from "mathjax-full/js/a11y/assistive-mml.js";
...

interface DocumentOptions {
  InputJax: TeX<unknown, unknown, unknown>;
  OutputJax: SVG<unknown, unknown, unknown>;
}

...

Notice that it uses MathJax’s document options , which has 5 developer options . In our case it uses InputTeX and OutputTeX ; but where should I put the following things , according to the readme.md of XyJax-v3 ?

loader: {
  load: ['[custom]/xypic.js'],
  paths: {
    custom: 'https://cdn.jsdelivr.net/gh/sonoisa/[email protected]/build/',
  },
},
tex: {
  packages: { '[+]': ['xypic'] },
},

Firefox Service Worker import module giving TypeError

SW Registration failed with TypeError: ServiceWorker script at http://localhost/Vanilla/CacheManager.js for scope http://localhost/Vanilla/ threw an exception during script evaluation.

I’m getting the above TypeError when trying to register a ServiceWorker with FireFox (Works on Chrome, Wsdge, Opera) –

if ("serviceWorker" in navigator) {                 
    await navigator.serviceWorker.register('/Vanilla/CacheManager.js', { scope: '/Vanilla/', type: 'module' })
        .then(reg => {
                console.log('SW Registered');
            })
        .catch(err => {
            console.log('SW Registration failed with ' + err)
        });

CacheManager.js (reduced to) –

*import config from "/Vanilla/config.js"* **// The problem**
console.log("Hello")
//const CACHE_NAME = config.cacheName   

Config.js

export const config = 
{
    "cacheName": "VanillaV1.1"
}

I have no idea what TypeError FireFox is complaining about. CONST?

How do I use Angular 19 Observer for HTTP Requests?

sorry if this was asked already, I couldn’t find a similar question that had a satisfactory answer or had an answer that wasn’t deprecated. I’m not really sure how to word what I am trying to do in any technical way, I am still very new to web development.

Essentially I am trying to assign data from a GET request to a variable. I understand that an HttpClient GET request returns an Observable that must be subscribed to. The following works, it prints the correct data (a Json object):

this.get("").subscribe(response => {console.log(response)});

However when I try to assign response to a variable:

let raw; //have also tried var as I thought it might be related to scope?
this.get("").subscribe(response => {raw = response});
console.log(raw) //returns undefined

let raw = this.get("").subscribe(response => response); //have also tried => response.data with same result
console.log(raw) //returns a weird object that I assume is the observer?

What is the best way to do this? Thanks in advance.

Span doesn’t show social name in PHP+Javascript

Hope you’re having a good week so far!
So, I have this screen to edit a user’s information. (The information here is fictional, not from a real person)
All of other fields (name, birth date, age, address, etc) works and shows just fine, but nt the social name.
The request also not shows on the network tab when hitting the F12 in browser. I have tried a couple of things, but none of them worked. Anyone have any tips or hints that might help me find the solution?enter image description here

Some of the related functions in jsonParser, the functions that should be responsible to load the social name is called loadNomeSocial, the request is inside the function:

var usuarioJson;

function jsonParseInfoPessoa(json) {
    let objJson = JSON.parse(json);
    usuarioJson = objJson;
    nome = objJson[0].nome;
    $('.nome').append(nome);
    let controleConta = $('#bloqConta');

    if (objJson[0].excluido == 1) {
        $('#nomeLabel').append(nome + "- Usuário Desativado");
        //adicionando botao de reativar
        controleConta.append('<a href="control/main.php?req=ativaConta&id=' + identificador + '" class="btn btn-primary">Reativar conta</a>');
    } else {
        //botao de desativar
        $('#nomeLabel').append(nome);
        controleConta.append('<a href="control/main.php?req=desativaConta&id=' + identificador + '" class="btn btn-danger">Desativar conta</a>');
    }

    //formatando data de nascimento objJson[0].data_nascimento
    let nascFormatada = objJson[0].data_nascimento.split('-');
    nascFormatada = nascFormatada[2] + ' / ' + nascFormatada[1] + ' / ' + nascFormatada[0];
    let idade = calculaIdade(objJson[0].data_nascimento);
    $('#nasc').append(nascFormatada+'<br>Idade: '+idade + ' Anos');
    if (objJson[0].menor_idade === "1") {
        loadMenor();
        $('#maiorIdade').attr('hidden',true);
    } else {
        loadContato(identificador);
        loadEnd(identificador);
        loadDocument();
        loadDepententes();
        loadLogin(identificador);
        loadNomeSocial(identificador);
    }
    if (objJson[0].ruralino === "1") {
        loadRuralino();
    } else {
        btnInsertRuralino();
    }
    if (objJson[0].excluido == '0') addBtnEdicaoPessoa();
}

function loadLogin(id) {
    $('#altSenha').removeAttr('hidden');
    ajaxLoadGET('control/main.php?req=selectLoginUser&id=' + id, parseLogin, '.carr');

    function parseLogin(resposta) {
        let objJson = JSON.parse(resposta);
        $('#login').empty().append(objJson[0].usuario);
    }

}

function loadMenor() {
    $('#menorIdade').removeAttr("hidden");
    ajaxLoadGET('control/main.php?req=selectResponsavelByMenorId&id=' + identificador, parseMenor, '.carr');

    function parseMenor(json, corpo) {
        var objJson = JSON.parse(json);
        $('#menorIdade').removeAttr("hidden");
        $('#respnome').append(objJson[0].nome);
        $('#respLink').attr('href','index.php?pag=Info.Pessoa&id='+objJson[0].responsavel_id);
        $('#parentesco').append(objJson[0].parentesco);

        loadContato(objJson[0].responsavel_id);
        loadEnd(objJson[0].responsavel_id);
    }
}

function loadRuralino() {
    //adicionamos o botão editar
    $('#ruraLabel').append('&nbsp; <button id="btnDeps" onclick="editaRuralino()" class="btn btn-primary"><span class='glyphicon glyphicon-pencil'></span></button>');
    $('#ruralinoConteudo').removeAttr("hidden");
    ajaxLoadGET('control/main.php?req=selectRuralinoByPessoaId&id=' + identificador, parseRuralino, '.carr');

    function parseRuralino(json, corpo) {
        var objJson = JSON.parse(json);
        $('#matricula').append(objJson[0].matricula);
        $('#curso').append(objJson[0].curso);
        $('#bolsista').append(isAtivo(objJson[0].bolsista));
    }
}

function btnInsertRuralino() {
    //adicionamos o botão Adicionar
    $('#ruraLabel').append('&nbsp; <button id="btnDeps" onclick="insertRuralino()" class="btn btn-primary"><span class='glyphicon glyphicon-pencil'></span></button>');
}

function insertRuralino() {
    let conteudo = $('#ruralinoConteudo');
    conteudo.empty();
    conteudo.removeAttr('hidden');
    conteudo.append(
        '<form action="control/main.php?req=insertRuralino&id=' + identificador + '" method="POST">' +
        '<p>Curso: <input type="text" name="curso" placeholder="Educação Física" required="required"></p>' +
        '<p>Matricula: <input type="number" name="matricula" placeholder="2018180188" ></p>' +
        '<div class="form-group">n' +
        '                <label class="control-label" >Bolsista do CAC?</label>n' +
        '                <div class="">n' +
        '                    <label class="radio-inline">n' +
        '                        <input type="radio" name="bolsista" value="1">SIMn' +
        '                    </label>n' +
        '                    <label class="radio-inline">n' +
        '                        <input type="radio" name="bolsista" value="0">NÃOn' +
        '                    </label>n' +
        '                </div>n' +
        '            </div>' +
        '<br/><input type="submit" class="btn btn-primary" value="Gravar"/>' +
        '</form>'
    );
}

function editaRuralino() {
    let curso = $('#curso').text();
    let matricula = $('#matricula').text();
    let conteudo = $('#ruralinoConteudo');
    conteudo.empty();
    conteudo.append(
        '<form action="control/main.php?req=updateRuralino&id=' + identificador + '" method="POST">' +
        '<p>Curso: <input type="text" name="curso" value="' + curso + '" required="required"></p>' +
        '<p>Matricula: <input type="number" name="matricula" value="' + matricula + '" ></p>' +
        '<div class="form-group">n' +
        '                <label class="control-label" >Bolsista do CAC?</label>n' +
        '                <div class="">n' +
        '                    <label class="radio-inline">n' +
        '                        <input type="radio" name="bolsista" value="1">SIMn' +
        '                    </label>n' +
        '                    <label class="radio-inline">n' +
        '                        <input type="radio" name="bolsista" value="0">NÃOn' +
        '                    </label>n' +
        '                </div>n' +
        '            </div>' +
        '<br/><input type="submit" class="btn btn-primary" value="Gravar"/>' +
        '</form>'
    );
}

function loadContato(id) {
    ajaxLoadGET('control/main.php?req=selectTelefoneByPessoaId&id=' + id, parseContato, '#tels');

    function parseContato(json, corpo) {
        jsonContato = json;
        let objJson = JSON.parse(json);
        for (i in objJson) {
            corpo.append('<p>Contato (' + getTelType(objJson[i].tipo) + '): ' + objJson[i].contato + '</p>');
        }
    }
}
    
function loadNomeSocial(id) {
    ajaxLoadGET('control/main.php?req=selectNomeSocialByPessoaId&id=' + id, parseNomeSocial, '#nome_social');
    
    function parseNomeSocial(json, corpo) {
    console.log("Resposta da requisição Nome Social:", json);
    let objJson = JSON.parse(json);
    if (objJson.length > 0) {
        $('#nome_social').append(objJson[0].nomesocial);
    } else {
        console.log("Nenhum nome social encontrado.");
    }
}
}

    function getTelType(num) {
        num = parseInt(num);
        switch (num) {
            case 1:
                return "celular";
            case 2:
                return "Whatsapp";
            case 3:
                return "Fixo";
            case 4:
                return "Recados";
            case 5:
                return "Email";
            default:
                return "...";
        }

    }
}

function loadEnd(id) {
    ajaxLoadGET('control/main.php?req=selectEndereco&id=' + id, parseEnd, '.carr');

    function parseEnd(json, corpo) {
        var objJson = JSON.parse(json);
        $('#rua').append(objJson[0].rua);
        $('#num').append(objJson[0].numero);
        $('#complemento').append(objJson[0].complemento);
        $('#bairro').append(objJson[0].bairro);
        $('#cidade').append(objJson[0].cidade);
        $('#estado').append(objJson[0].estado);

    }
}

function loadDocument() {
    ajaxLoadGET('control/main.php?req=selectDocumento&id=' + identificador, parseDocumento, '.carr');
    $('#documentos').removeAttr("hidden");

    function parseDocumento(resposta, corpo) {
        let json = JSON.parse(resposta);
        $('#tipoDoc').append(documenTipo(json[0].tipo_documento));
        $('#numDoc').append(json[0].numero_documento);
    }

    function documenTipo(num) {
        if (num === "2") return "Passaporte";
        if (num === "3") return "CPF";
        return "Registro Geral (RG)";
    }
}

function loadDependentes() {
    ajaxLoadGET('control/main.php?req=selectDependentes&id=' + identificador, parseDependentes, '#dep');
    $('#dependentes').removeAttr("hidden");

    function parseDependentes(resposta, corpo) {
        let json = JSON.parse(resposta);
        for (i in json) {
            corpo.append('<p>Nome: <span class="depNome"> ' + json[i].nome +
                '&nbsp; <a href="?pag=Meus-Dados&id=' + json[i].id_pessoa + '" class="btn btn-primary"><span class='glyphicon glyphicon-pencil'></span></a>' +
                '&nbsp; <a href="control/main.php?req=removeDependente&id=' + json[i].id_pessoa + '" class="btn btn-primary"><span class='glyphicon glyphicon-remove'></span></a>' +
                '</span></p>');
        }
    }
}

/*------------------------------------------------EDITA USUARIO--------------------------*/
function addBtnEdicaoPessoa() {
    $('#dadosBasicos').append('&nbsp; <button id="btNome" onclick="editUsuarioNome()" class="btn btn-primary"><span class='glyphicon glyphicon-pencil'></span></button>');
    $('#contato').append('&nbsp; <button id="btnCont" onclick="editUsuarioContato()" class="btn btn-primary"><span class='glyphicon glyphicon-pencil'></span></button>');
    $('#endereco').append('&nbsp; <button id="btnEnd" onclick="editUsuarioEndereco()" class="btn btn-primary"><span class='glyphicon glyphicon-pencil'></span></button>');
    $('#docLabel').append('&nbsp; <button id="btnDoc" onclick="editUsuarioDocumento()" class="btn btn-primary"><span class='glyphicon glyphicon-pencil'></span></button>');
    $('#dependentes h4').append('&nbsp; <button id="btnDeps" onclick="adicionaDependete()" class="btn btn-primary"><span class='glyphicon glyphicon-plus'></span></button>');
     $('#nomesocial h4').append('&nbsp; <button id="btnDeps" onclick="adicionaDependete()" class="btn btn-primary"><span class='glyphicon glyphicon-plus'></span></button>');
}

function addMenor() {
    var quantidade = $('#qtd_menor').val();
    var divContent = $('#menor_de_idade');

    quantidade++;

    $(function () {
        $('<div class="aluno">' +
            '<h4> Dependente #' + quantidade + ' </h4><hr>n' +
            '            <div class="form-group col-md-8 col-lg-push-2">n' +
            '                <label class="control-label" for="nome_menor' + quantidade + '">Nome</label>n' +
            '                <div class="">n' +
            '                    <input id="nome_menor' + quantidade + '" name="nome_menor' + quantidade + '" type="text" placeholder="Nome do menor ' + quantidade + '" class="form-control input-md" required="">n' +
            '                </div>n' +
            '            </div><br/>n' +
            'n' +
            '            <!-- Nascimento do menor ' + quantidade + ' -->n' +
            '            <div class="form-group col-md-8 col-lg-push-2">n' +
            '                <label class="control-label" for="nascimento_menor' + quantidade + '">Nascimento</label>n' +
            '                <div class="">n' +
            '                    <input id="nascimento_menor' + quantidade + '" name="nascimento_menor' + quantidade + '" type="date" placeholder="dd/mm/aaaa" class="form-control input-md" required="">n' +
            '                </div>n' +
            '            </div><br/>' +
            '</div>').appendTo(divContent);
        
        $('#qtd_menor').remove();
        $('<input type="hidden" name="qtd_menor" value="' + quantidade + '" id="qtd_menor">').appendTo(divContent);
    });
}


function editUsuarioNome() {
    $('#btNome').removeAttr("onclick");
    let dadosBasicos = $('#nomeNasc');
    
    ajaxLoadGET('control/main.php?req=selecUsuarioLogado', function(response) {
        let userData = typeof response === 'string' ? JSON.parse(response) : response;
        
        // Log do valor exato e seu tipo para diagnóstico
        console.log("Valor de nv_acesso:", userData.nv_acesso);
        console.log("Tipo de nv_acesso:", typeof userData.nv_acesso);
        console.log("Código de caracteres:", Array.from(userData.nv_acesso || "").map(c => c.charCodeAt(0)));
        
        // Normalização do valor para evitar problemas com acentos ou espaços
        let nivelNormalizado = "";
        if (userData.nv_acesso) {
            nivelNormalizado = userData.nv_acesso.trim().normalize("NFD").replace(/[u0300-u036f]/g, "");
        }
        console.log("Nível normalizado:", nivelNormalizado);
        
        let nasc = usuarioJson[0].data_nascimento;
        dadosBasicos.empty();

        let opcoesSelect = "";
        
        // Abordagem inversa - exibir Coordenação para todos EXCETO para níveis específicos
        let niveisComuns = ["Administrador", "Professor", "Aluno", "Visitante"];
        let isNivelComum = niveisComuns.some(nivel => 
            userData.nv_acesso === nivel || nivelNormalizado === nivel
        );
        
        // Se NÃO for um dos níveis comuns, assumimos que é Coordenação
        if (!isNivelComum) {
            opcoesSelect += `<option value=5>${CargoCoordenador}</option>`;
        }

        opcoesSelect += `
            <option value=4>Visitante</option>
            <option value=3>${CargoAluno}</option>
            <option value=2>${CargoProf}</option>
            <option value=1>${CargoAdm}</option>
        `;

        dadosBasicos.append(`
            <form action="control/main.php?req=updateDadosBasicos&id=${identificador}" method="POST">
                <p>Nível de Acesso: <select id="nv_acesso" name="nv_acesso">${opcoesSelect}</select></p>
                <p>Nome: <input type='text' name='nome' value="${nome}" required="required"></p>
                <p>Data nascimento: <input type="date" name="nascimento" value="${nasc}" required="required"></p>
                <p>Nome Social: <input type='text' name='nome_social' value="${nome_social}"></p>
                <br/>
                <input type="submit" class="btn btn-primary" value="Gravar"/>
            </form>
        `);
    }, '#nv_acesso');
}

// Função auxiliar para obter o valor numérico do nível de acesso
function getNivelAcessoValue(nivelAcesso) {
    switch(nivelAcesso) {
        case "Coordenação": return 5;
        case "Visitante": return 4;
        case "Aluno": return 3;
        case "Professor": return 2;
        case "Administrador": return 1;
        default: return 4; // Default para Visitante
    }
}

function editUsuarioContato() {
    $('#btnCont').removeAttr("onclick");
    let tels = $('#tels');
    let acm = '<form action="control/main.php?req=updateContato&id=' + identificador + '" method="POST">';
    let tipo = 0;
    tels.empty();
    if (jsonContato !== null) {
        jsonContato = JSON.parse(jsonContato);
            tipo = jsonContato[0].tipo;
            acm += `<p><input type="hidden" name="resp_tel_id" value="${jsonContato[0].id_contato}">Tel: <input type="number" name="resp_tel" value="${jsonContato[0].contato}" required="required">Tipo: <select id="resp_tel_type" name="resp_tel_type">
                        <option value="2" ${verTp(tipo, 2)}>Whatsapp</option>
                        <option value="1" ${verTp(tipo, 1)}>Celular</option>
                        <option value="3" ${verTp(tipo, 3)}>Fixo (residencial)</option>
                        <option value="4" ${verTp(tipo, 4)}>Recados</option>
                        <option value="5" ${verTp(tipo, 5)}>Email</option>
                    </select></p>`;
            if(jsonContato.length >1){
                acm += '<p><input type="hidden" name="resp_email_id" value="'+jsonContato[1].id_contato+'">' +
                    'Email: <input type="email" name="email" value="' + jsonContato[1].contato + '" required="required">' +
                '</p>';
            }
    }
    acm += '<br/><input type="submit" class="btn btn-primary" value="Gravar"/></form>';
    tels.append(acm);

    function verTp(tp, val) {
        if (parseInt(tp) === parseInt(val)) return 'selected';
        return '';
    }
}

function editUsuarioEndereco() {
    $('#btnEnd').removeAttr("onclick");
    let end = $('#end');
    //Obtendo dados atuais
    let rua = $('#rua').text();
    let numero = $('#num').text();
    let complemento = $('#complemento').text();
    let bairro = $('#bairro').text();
    let cidade = $('#cidade').text();
    let estado = $('#estado').text();
    end.empty();
    //Inserindo campos de edicao
    end.append(
        '<form action="control/main.php?req=updateEndereco&id=' + identificador + '" method="POST">' +
        '<p>Rua: <input type='text' name='rua' value="' + rua + '" required="required"></p>' +
        '<p>Numero: <input type="number" name="numero" value="' + numero + '" required="required"></p>' +
        '<p>Complemento: <input type="text" name="complemento" value="' + complemento + '" ></p>' +
        '<p>Bairro: <input type="text" name="bairro" value="' + bairro + '" required="required"></p>' +
        '<p>Cidade: <input type="text" name="cidade" value="' + cidade + '" required="required"></p>' +
        '<p>Estado: <input type="text" name="estado" value="' + estado + '" required="required"></p>' +
        '<br/><input type="submit" class="btn btn-primary" value="Gravar"/>' +
        '</form>');
}

function editUsuarioDocumento() {
    $('#btnDoc').removeAttr("onclick");
    let docs = $('#docs');
    //obtendo dados atuais
    let tipo = $('#tipoDoc').text();
    let numero = $('#numDoc').text();
    docs.empty();

    docs.append(
        '<form action="control/main.php?req=updateDoc&id=' + identificador + '" method="POST">' +
        '<p>Tipo: ' +
        '   <select id="doc_type" name="doc_type">n' +
        '       <option value="3">CPF</option>n' +
        '       <option value="2">Passaporte</option>n' +
        '   </select>' +
        '</p>' +
        '<p>Numero: <input type="number" name="doc_number" value="' + numero + '" required="required"></p>' +
        '<br/><input type="submit" class="btn btn-primary" value="Gravar"/>' +
        '</form>');
}

function adicionaDependete() {
    $('#gravaMenor').attr('type', 'submit');
    $('#label_parentesco').removeAttr('hidden');
    //requisitamos adicionar dependente no id do usuario atual
    $('#formDependentes').attr('action', 'control/main.php?req=addDependente&id=' + identificador);
    addMenor();
}

Here it is the div where the social name span is located:

    <div id="nomeNasc">
        <p>Nome: <span class="nome"> </span></span></p>
        <p>data nascimento: <span id="nasc"></span></p>
        <p>Nome Social: <span id="nome_social"></span></p>
    </div>

Here it is the jsonParser.min functions:

function loadNomeSocial(id){console.log("Chamando loadNomeSocial com ID:",id),ajaxLoadGET("control/main.php?req=selectNomeSocialByPessoaId&id="+id,parseNomeSocial,".carr");function parseNomeSocial(json,corpo){console.log("Resposta da requisição Nome Social:",json);let objJson=JSON.parse(json);objJson.length>0?$(".nome-social").append(objJson[0].nomesocial):console.log("Nenhum nome social encontrado.")}}

And:

function editUsuarioNome(){$('#btNome').removeAttr("onclick");let dadosBasicos=$('#nomeNasc');ajaxLoadGET('control/main.php?req=selecUsuarioLogado',function(response){let userData=typeof response==='string'?JSON.parse(response):response;console.log("Valor de nv_acesso:",userData.nv_acesso);console.log("Tipo de nv_acesso:",typeof userData.nv_acesso);console.log("Código de caracteres:",Array.from(userData.nv_acesso||"").map(c=>c.charCodeAt(0)));let nivelNormalizado="";if(userData.nv_acesso){nivelNormalizado=userData.nv_acesso.trim().normalize("NFD").replace(/[̀-ͯ]/g,"");}console.log("Nível normalizado:",nivelNormalizado);let nasc=usuarioJson[0].data_nascimento;let nome_social=usuarioJson[0].nome_social||"";dadosBasicos.empty();let opcoesSelect="";let niveisComuns=["Administrador","Professor","Aluno","Visitante"];let isNivelComum=niveisComuns.some(nivel=>userData.nv_acesso===nivel||nivelNormalizado===nivel);if(!isNivelComum){opcoesSelect+=`<option value=5>${CargoCoordenador}</option>`;}opcoesSelect+=`<option value=4>Visitante</option><option value=3>${CargoAluno}</option><option value=2>${CargoProf}</option><option value=1>${CargoAdm}</option>`;dadosBasicos.append(`<form action="control/main.php?req=updateDadosBasicos&id=${identificador}" method="POST"><p>Nível de Acesso: <select id="nv_acesso" name="nv_acesso">${opcoesSelect}</select></p><p>Nome: <input type='text' name='nome' value="${nome}" required="required"></p><p>Nome Social: <input type='text' name='nome_social' value="${nome_social}"></p><p>Data nascimento: <input type="date" name="nascimento" value="${nasc}" required="required"></p><br/><input type="submit" class="btn btn-primary" value="Gravar"/></form>`);},'#nv_acesso');}

The function editUsuarioNome() also loads the values when you click in the pencil icon to further editions and updates of them.

The nomesocial attribute is in nome_social (social name) table which has id_pessoa as the foreign key from the table pessoa (person)

Controlling tick marks and lines in chart.js time scatter plot

Concerning this jsfiddle which uses chartjs v3.9.1 and the date-fns adapter:

https://jsfiddle.net/0a6c1ty5/22/

  1. I’m trying to format the tick labels in the function tick_label but I’m only getting a string as input. Is there a way to get the full Date object so I can include the month and day-of-month in the tick label if I want?

  2. Is there a way to specify which times to use for tick lines along the time axis?

Here is the code from the fiddle:

var chart1

function tick_label(xvalue) {
    console.log("xvalue:", xvalue, "type:", typeof(xvalue))
    return xvalue
}

function doit() {
  let t0 = 1742662800*1000; // Sat Mar 22 12:00:00 CDT 2025
  let N = 31
  data = [...Array(N)].map((a,i) =>
               ({ 'x': new Date(i*3600000+t0),
                 'y': ~~(Math.random()*40)
               }))  
  config = {
    type: "scatter",
    data: { datasets: [{ label: "Random Values", data: data }] },
    options: {
      scales: {
        x: { type: 'time', ticks: { callback: tick_label, color: 'red' } }
      }
    }
  }
  chart1 = new Chart(document.getElementById('chart1'), config);
}
doit()