The value disappears but still save in database

I have a registration form for a Python/Django project that uses Vue.js. I save the form correctly, but when trying to edit, I can see that the value is loaded properly, but it disappears very quickly, as if Vue.js/JavaScript is erasing it. When inspecting the field, I can see that its value receives the correct value from the registration, but the field becomes blank.

<script>
function capitalizeWords(string) {
    if (!string) return string;
    const words = string.split(' ');
    const capitalizedWords = words.map((word) => {
        if (word.length > 1) {
            return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
        } else {
            return word.toUpperCase();
        }
    });

    return capitalizedWords.join(' ');
}

var app = new Vue({
    el: '#app',
    delimiters: ['[[', ']]'],
    data: {
        street: '',
        district: '',
        city: '',
        state: '',
        country: '',
        cnpj: '',
        name: '',
        trade_name: '',
        cnae: '',
        opening_date: '',
        selectedBank: '',
        bank: '',
        bank_code: '',
        nameInBankAccount: '',
        cnpjInBankAccount: '',  
        postal_code: '',
        isLoading: false,
        isPostalCodeFound: true,
        isCNPJFound: true,
        display_form_address: false,
        display_form_bank: false,
        hasError: '{{ error }}'
    },
    beforeMount: function () {
        this.street = this.$el.querySelector('#id_address-0-street').value
        this.district = this.$el.querySelector('#id_address-0-district').value
        this.city = this.$el.querySelector('#id_address-0-city').value
        this.state = this.$el.querySelector('#id_address-0-state').value
        this.country = this.$el.querySelector('#id_address-0-country').value
        this.cnpj = this.$el.querySelector('#id_company-cnpj').value
        this.name = this.$el.querySelector('#id_company-name').value
        this.trade_name = this.$el.querySelector('#id_company-trade_name').value
        this.cnae = this.$el.querySelector('#id_company-cnae').value
        this.opening_date = this.$el.querySelector('#id_company-opening_date').value
        this.getError();
    },
    watch: {
        cnpj: function(newValue) {
            this.cnpjInBankAccount = newValue;
        },
        name: function(newValue) {
            this.nameInBankAccount = newValue;
        }
    },
    computed: {
        isBankDisabled: function() {
            return this.selectedBank !== '';
        }
    },
    methods: {
        onPostalCodeChange() {
            if (this.postal_code.length >= 8) {
                this.fetchPostalCodeData()
            } else {
                this.postal_code = ''
                this.street = ''
                this.district = ''
                this.city = ''
                this.state = ''
                this.isPostalCodeFound = true
            }
        },
        onCNPJChange() {
            if (this.cnpj.length === 14) {
                this.fetchCNPJData()
            } else {
                this.name = ''
                this.trade_name = ''
                this.cnae = ''
                this.opening_date = ''
                this.isCNPJFound = true
            }
        },
        showAddress: function () {
            this.display_form_address = !this.display_form_address;
        },
        showBank: function () {
            this.display_form_bank = !this.display_form_bank;
        },
        getError: function () {
            if (this.hasError === "True"){
                this.showBank();
                this.showAddress();
            }
        },
        async fetchPostalCodeData() {
            try {
                this.isLoading = true
                const response = await fetch(
                    `https://viacep.com.br/ws/${this.postal_code}/json/`, {
                        method: 'GET',
                    })
                const data = await response.json()
                if (data.erro == true || data.erro == 'true'){
                    this.isPostalCodeFound = false
                } else {
                    console.log(data)
                    this.street = data.logradouro
                    this.district = data.bairro
                    this.city = data.localidade
                    this.state = data.uf
                }
            } catch (error) {
                console.error(error)
            } finally {
                this.isLoading = false
            }
        },
        async fetchCNPJData() {
            try {
                this.isLoading = true
                const response = await fetch(
                    `link da api`, {
                        method: 'GET',
                    })
                const data = await response.json()
                console.log(data)
                console.log(response.status)
                if (response.status === 404) {
                    this.isCNPJFound = false
                } else {
                    this.name = capitalizeWords(data.name)
                    this.trade_name = capitalizeWords(data.trading_name)
                    this.opening_date = data.fundation_date
                    this.cnae = data.cnae_code
                }

            } catch (error) {
                console.error(error)
            } finally {
                this.isLoading = false
            }
        },

    }
})

The fields that are being cleared are:
bank
bank_code
I can’t understand the reason for these values being cleared; I believe it might be related to the loading of JS/Vue.js, but I can’t assert that with clarity. Nonetheless, the values are correctly saved in the database.

The form is:

class BuyerLegalPersonBankAccountForm(forms.ModelForm):
select_bank = MajorBankList(
    label='Banco',
    required=False,
    )
class Meta:
    model = CompanyBankAccount
    fields = (
        'name',
        'cpf',
        'cnpj',
        'select_bank',
        'bank',
        'bank_code',
        'agency',
        'account',
        'account_type',
    )
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields['bank'].required = False
    self.fields['bank_code'].required = False
    self.fields['bank'].widget.attrs.update(
        {
            'v-model': 'bank',
            ':disabled': 'isBankDisabled',
        }
    )
    self.fields['bank_code'].widget.attrs.update(
        {
            'v-model': 'bank_code',
            ':disabled': 'isBankDisabled',
        }
    )
    self.fields['select_bank'].widget.attrs.update(
        {
            'v-model': 'selectedBank',
        }
    )
    self.fields['name'].widget.attrs.update(
        {
            'v-model': 'nameInBankAccount',
        }
    )
    self.fields['cnpj'].widget.attrs.update(
        {
            'v-model': 'cnpjInBankAccount',
        }
    )

How would I create a Nested Default Dictionary in Javascript?

I’m trying to create an Apps Script, and I’ve been trying to implement a Default Dictionary. So far, I’ve been able to yoink a couple of things that didn’t end up working, the first one was this:

class DefaultDict {
  constructor(defaultInit) {
    return new Proxy({}, {
      get: (target, name) => name in target ?
        target[name] :
        (target[name] = typeof defaultInit === 'function' ?
          new defaultInit().valueOf() :
          defaultInit)
    })
  }
}

And while this works well enough for a flat Default Dictionary with say let locationDict = new DefaultDict(Array), or maybe new DefaultDict(Number), it kind of breaks with new DefaultDict(DefaultDict(DefaultDict(Array))).

Specifically, the error I get is TypeError: Class constructor DefaultDict cannot be invoked without 'new'… and I’m not sure what that means… I was hoping that the new keyword that’s inside of the class constructor definition would take care of invocations of class constructors…

So I managed to find a workaround to fix it that seemed to make things rosy by turning it into a function instead of a class:

function DefaultDict (defaultInit) {
  const handler = {
    get: (target, name) => name in target ?
      target[name] :
      (target[name] = typeof defaultInit === 'function' ?
        new defaultInit().valueOf() :
        defaultInit)
  }
  return new Proxy({}, handler)
}

and I had thought it was working dandy with the new DefaultDict(DefaultDict(DefaultDict(Array))) (because there weren’t any errors) until I actually ran it with some data. Without going too nitty gritty, let me see if I can simplify the use case:

   const data = [["Welcome to El Mirage Sign", "El Mirage", "Arizona", "United States"],
                 ["Indian Roller Bird", "Austin", "Texas", "United States"],
                 ["Greenbrier Park Half-Court", "Austin", "Texas", "United States"],
                 ["Pink Dinosaur Playscape", "Austin", "Texas", "United States"]]
  const caption = 0
  const subregion = 1
  const region = 2
  const country = 3
  
  let locationDict = new DefaultDict(DefaultDict(DefaultDict(Array)))
  for (let i = 0; i < data.length; i++)
  {
    const caption = data[i][0]
    const subregion = data[i][1]
    const region = data[i][2]
    const country = data[i][3]
    locationDict[country][region][subregion].push(caption)
  }

  console.log(locationDict)

So here, I got this console value verbatim:

{ 'United States': 
   { Arizona: { 'El Mirage': [Object], Austin: [Object], inspect: [] },
     Texas: { 'El Mirage': [Object], Austin: [Object], inspect: [] },
     inspect: { 'El Mirage': [Object], Austin: [Object], inspect: [] } },
  inspect: 
   { Arizona: { 'El Mirage': [Object], Austin: [Object], inspect: [] },
     Texas: { 'El Mirage': [Object], Austin: [Object], inspect: [] },
     inspect: { 'El Mirage': [Object], Austin: [Object], inspect: [] } } }

and I imagined a lot of stuff was just header stuff, in the debugger I can actually inspect the Array objects as well, and the arrays were actually correct, but the problem lies in the cities, or the “subregions” as I called them. It seems that Arizona and Texas both share the same value object.

I expected something more like this:

{
  'United States': 
  {
    Arizona:
    {
      'El Mirage': ["Welcome to El Mirage Sign"]
    },
    Texas:
    {
      Austin: ["Indian Roller Bird", "Greenbrier Park Half-Court", "Pink Dinosaur Playscape"]
    }
}

And so this is where I’m not sure where to go from here… Any help would be appreciated. Thanks!

Add additional type to object after running through a transformer function

So I have this object that will have many entries and it is defined in the following manner:

/* All Items are a class of their own */
class Item {}

const Items = {
  Item1: new Item(),
  Item2: new Item(),
  Item3: new Item(),
  Item4: new Item(),
  Item5: new Item(),
  Item6: new Item(),
  Item7: new Item(),
  Item8: new Item(),
  Item9: new Item(),
  Item10: new Item(),
};

Now I want to run this object through a transformer function and return the following typescript types without creating a separate typescript type for just that transformer function (similar to the ResultType I had created below).

/* 
  This is just a dummy transformer function. 
  In reality I don't have control on the return type of this function. 
*/
type TransformedReturnType<T> = {
  newFunctionmethod: () => T
}


type ResultType = {
  Item1: TransformedReturnType<Item>
  Item2: TransformedReturnType<Item>
  Item3: TransformedReturnType<Item>
  Item4: TransformedReturnType<Item>
  Item5: TransformedReturnType<Item>
  Item6: TransformedReturnType<Item>
  Item7: TransformedReturnType<Item>
  Item8: TransformedReturnType<Item>
  Item9: TransformedReturnType<Item>
  Item10: TransformedReturnType<Item>
}

function TransformerFn(item: Item): TransformedReturnType<Item> {
  return {
    newFunctionmethod: () => {
      return item
    }
  }
}

const result = Object.keys(Items).reduce((acc, item) => {
  acc[item] = TransformerFn(Items[item])
  return acc
}, {} as ResultType)

I want to save the input as a link every time, but nothing happens

I am a beginner and if possible I could use some help. I want to save the input as a link every time, but when I try to put

` li.append(anchor)` 

nothing happens.

This is what I’ve tried so far

`const renderLeads = () => {
  let myLeads = [];
  let listItem;
  for (let i = 0; i < myLeads.length; i++) {
    listItem = myLeads[i];
  }
  let anchor = document.createElement('a');
  let li = document.createElement('li');
  anchor.setAttribute('href', listItem);
  li.append(anchor);
  li.textContent = listItem;
  ulEl.append(li);
};`
 

If I don’t find the answer, it’s ok if I modify everything with innerHTML?

can’t read css path cause mime type

iam learning a node js form jonas coruse and iam in pug section so when i write the link of css in base.pug i get this error “Refused to apply style from ‘http://127.0.0.1:3000/css/style.css’ because its MIME type (‘text/html’) is not a supported stylesheet MIME type, and strict MIME checking is enabled. ” and i try many soluations and i don’t get the expexted result.

doctype html
html
head

    link(rel='stylesheet' href='css/style.css')
    link(rel='shortcut icon' type='image/png' href='img/favicon.png')
    

i tried alot of soluations but i can’t get the soluation .

Function that usesEveryNumber [duplicate]

write a function called usesEveryNumber which takes an input string and returns true if every number 0-9 all appear (0,1,2,3,4,5,6,7,8,9). The function should return false otherwise.

function usesEveryNumber(str) {
    if (str = ['0'||'1' || '2' || '3' || '4' || '5' || '6' || '7' || '8' || '9']) {
    return false;
    }
    return true;
}

I tried this function and I was expecting the function to pass all test cases. However there was a unique case where there were periods in the strings separating the numbers and returned false instead of true even though all numbers 0-9 were present in the string.

Getting the first true/truthy value in Javascript/NextJS to use in setting a property?

In my NextJS project using Javascript, I would like to set the property on a local object.

const localItem = 
{
  name: <<here is the value I need to set>>
};

However, the data that I am using to set the ^ property may not be reliably complete.
And, if possible, I’d rather not do a bunch of if/else if or switch/case statements since this might be needed for a bunch of properties and I’d like to keep the code compact if possible.

So for the sake of this question/example, let’s say that the data that I would like to use is:

person.nickname: '', //first choice - if it doesn't exist go to firstName
person.firstName: 'Sammy', //second choice - if it doesn't exist go to 'a default string'
'Mr. Bond' // a default string I presume - use if both of the above are missing

Tabulator – addColumn() returned promise

I have a Tabulator table that has a number of ‘standard’ columns, which are defined at the time of defining the table.
I also have a number of ‘custom’ columns, which are programmatically added to the table after it is built, using table.addColumn() method.
After each ‘custom’ column is added, I want to iterate through its cells, so that I can do some formatting based on some data in one of the ‘standard’ columns.
The .addColumn() method returns a promise, so I’m using .then() to do that formatting after the custom column is added.

The code below shows how I do this, and the example below works as expected. However, when I implement this algorithm in my own app, I get the following error:

ComponentFunctionBinder.js:27 The row component does not have a getIndex function, have you checked that you have the correct Tabulator module installed?

Here is my algorithm:

myTableData = [
    {'myID':'id1', 'column1':'col1data1', 'colum2':'col2data1', 'customField1':'customField1Data1', 'customField2':'customField2Data1', },
    {'myID':'id2', 'column1':'col1data2', 'colum2':'col2data2', 'customField1':'customField1Data2', 'customField2':'customField2Data2', },
]

myCustomFields = [
    {'field_id':'customField1', 'field_name':'Custom Field 1'},
    {'field_id':'customField2', 'field_name':'Custom Field 2'},
]

myTable = new Tabulator("#assetsTable", {
    height: "600px",
    data: myTableData,
    columnDefaults:{tooltip:true, hozAlign:'center', headerHozAlign:'center', headerFilter:'input', sorter:'alphanum', sorterParams:{alignEmptyValues:"bottom"}},
    index:"myID",
    columns:[
        {title:"my ID", field:"myID"},
        {title:"Standard Column 1", field:"column1"},
        {title:"Standard Column 2", field:"column2"},
    ]
});

myTable.on('tableBuilt', function(){
    for (let myCustomField of myCustomFields){

        myTable.addColumn({
            title:myCustomField.field_name,
            field:myCustomField.field_id,
        }).then(function(column){
            let cells = column.getCells();
            for (let cell of cells){
                let rowData = cell.getData()  // does not return all the data that I'm expecting.
                console.log('row index is', cell.getRow().getIndex());  //triggers Tabulator error.
                //do some formatting stuff based on other 'standard' fields in the row.
            }
        })
    }

});

Any suggestions on how to achieve what I’m trying to do? Note, the ‘custom’ columns are being added programmatically because the field_id and field_title are based on other data entered by the user.

Fields are not adding to the schema, Fields are not showing in POSTMAN even after defining in the req body

My MongoDB schema has fields, and i am defining those fields, but in postman body when pass the field value it doesn’t show up in response:-

[This is the response i am getting // image of the response] (https://i.stack.imgur.com/QzPRc.png)`

I have defined fields in the Schema but when i try to add fields afterwards in the schema it doesn’t get attached and doesn’t shows in POSTMAN response, but when I set its default value, then shows in the POSTMAN.

for ex- I added passwordChangedAt field, and on the sign up url in POSTMAN, i set its value in the req.body, but it doesn’t show in POSTMAN response.

similarly i added role field and set its value to admin, but it doesn’t show up in the POSTMAN response.

I am new to MongoDB and Mongoose, and working on a project, and i have tried everything but not able figure out thee problem.


userModel JS

const mongoose = require('mongoose');
const validator = require('validator');
const bcrypt = require('bcryptjs');
// name, email, photo, password, passwordConfirm

// const validateEmail = function(email) {
//   // eslint-disable-next-line no-useless-escape
//   const re = /^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/;
//   return re.test(email);
// };

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'A user must have a name'],
    trim: true,
    maxlength: [40, 'A user name must have less or equal than 40 characters'],
    minlrngth: [1, 'A user name must have more than 1 characters']
  },
  email: {
    type: String,
    required: [true, 'A user must enter the email'],
    unique: true,
    lowercase: true,
    validate: [validator.isEmail, 'Please fill a valid email']
  },
  photo: {
    type: String
  },
  role: {
    type: String,
    enum: ['user', 'guide', 'lead-guide', 'admin'],
    default: 'admin'
  },
  password: {
    type: String,
    required: [true, 'A user must set his password'],
    minlength: 8,
    select: false
  },
  passwordConfirm: {
    type: String,
    required: [true, 'Please confirm your password'],
    validate: {
      // this only works on CREATE and SAVE!!!
      validator: function(el) {
        return el === this.password;
      },
      message:
        'Passwords are not identical. So Please enter the same password as above'
    }
  },
  passwordChangedAt: Date
});
// ------- Another Way Of Doing Password Confirmation = Expand to view --------
// userSchema
//   .virtual('passwordConfirmation')
//   .get(function() {
//     return this.passwordConfirmation;
//   })
//   .set(function(value) {
//     this.passwordConfirmation = value;
//   });
// userSchema.pre('validate', function(next) {
//   if (this.password !== this.passwordConfirmation) {
//     this.invalidate('passwordConfirmation', 'Enter the same password !');
//   }
//   next();
// });

userSchema.pre('save', async function(next) {
  // Only run this function if password was actually modified
  if (!this.isModified('password')) return next();
  // Hash the password with cost of 12
  this.password = await bcrypt.hash(this.password, 12);
  // Delete the passwordConfirm field
  this.passwordConfirm = undefined;
  next();
});

userSchema.methods.correctPassword = async function(
  candidatePassword,
  userPassword
) {
  return await bcrypt.compare(candidatePassword, userPassword);
};

userSchema.methods.changedPasswordAfter = function(JWTTimestamp) {
  if (this.passwordChangedAt) {
    const changedTimestamp = parseInt(
      this.passwordChangedAt.getTime() / 1000,
      10
    );

    console.log(this.changedTimestamp, JWTTimestamp);
    return JWTTimestamp < changedTimestamp; // 100 < 200
  }

  // False means not changed
  return false;
};

const User = mongoose.model('User', userSchema);

module. Exports = User;

authController JS

const { promisify } = require('util');
const jwt = require('jsonwebtoken');
const User = require('../models/userModel');
const catchAsync = require('../utils/catchAsync');
const AppError = require('../utils/appError');

const signToken = id => {
  return jwt.sign({ id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN
  });
};

exports.signup = catchAsync(async (req, res, next) => {
  const newUser = await User.create({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
    passwordConfirm: req.body.passwordConfirm
  });

  const token = signToken(newUser._id);

  res.status(201).json({
    status: 'Success',
    token,
    data: {
      user: newUser
    }
  });
});

exports.login = catchAsync(async (req, res, next) => {
  const { email, password } = req.body;

  // 1) Check if email and apssword exists
  if (!email || !password) {
    return next(new AppError('Please provide email and password', 400));
  }
  // 2) Check if user exists && password is correct
  const user = await User.findOne({ email }).select('+password');

  if (!user || !(await user.correctPassword(password, user.password))) {
    return next(new AppError('Incorrect email or password', 401));
  }

  // 3) If every is okay, end the token to client
  const token = signToken(user._id);

  res.status(200).json({
    status: 'success',
    token
  });
});

exports.protect = catchAsync(async (req, res, next) => {
  // 1) Getting the token and check if it exists
  let token;
  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith('Bearer')
  ) {
    token = req.headers.authorization.split(' ')[1];
  }

  if (!token) {
    return next(
      new AppError('You are not logged in! Please log in to get access', 401)
    );
  }

  // 2) Verfication token
  const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET);
  // 3) Check if user still exists
  const currentUser = await User.findById(decoded.id);
  if (!currentUser) {
    return next(
      new AppError(
        'The user belonging to this token, does no longer exist',
        401
      )
    );
  }
  // 4) Check if user changed password after the token was issued
  if (currentUser.changedPasswordAfter(decoded.iat)) {
    return next(
      new AppError(
        'User has changed the password! Please log in with the new password',
        400
      )
    );
  }
  // Grant Access to the protected route
  req.user = currentUser;
  next();
});

exports.restrictTo = (...roles) => {
  return (req, res, next) => {
    // roles ['admin', 'lead-guide]
    if (!roles.includes(req.user.role)) {
      return next(
        new AppError('You do not have permission to perform this action', 403)
      );
    }

    next();
  };
};

Welcome message for discord.js

Every time i get my code done, no matter which way i have tried. When the user joins it restarts the bot when the user joins discord rather than posting message. What am i doing wrong?

client.on(‘guildMemberAdd’, member =>{

const channelId = '1160392336866549882';

    const welcomeEmbed = new Discord.MessageEmbed()
    .setColor(pink)
    .setAuthor('FrankFromH', '', '')
    .setTitle('Welcome!')
    .setDescription(`${member} just joined the discord! Make sure to read #rules!`)
    .setThumbnail(message.user.avatarURL)
    .setFooter('Note: The maximum amount of answers is 9.')
    .setTimestamp();

channel.send(welcomeEmbed);

Discord bot restarts on user join

Else and if statements not doing job [closed]

I have a game called “Harvex”, and I am adding a mining feature, but this is a problem:

var durability = 0;

var rockOne = 1;

var zero = 0;

function mine() {
    var rock = Math.floor(Math.random() * 14) + 1;
    var rockImg = document.getElementById('rockImg');
    var rockType = document.getElementById('rockType');

    if (rock == rockOne) {
        if (durability <= zero) {
        rockImg.src = "Img/rocks/andesite.png";
        rockType.innerHTML = "You picked up Andesite";
        }
        else {
            rockType.innerHTML = "You don't have a pickaxe!";
        }
    }

It says “You picked up Andesite” instead of “You don’t have a pickaxe”, when the durability is 0, meaning NO PICKAXE!!

Please tell me what I did wrong..?

Having a extra optional type, why its required when its being set as a prop?

so I’ve recently came across this case, having these 3 interfaces:

interface a {
  id: string,
  name: string
}

interface b {
  id: string,
  name: string,
  age: string,
}

interface c {
  id: string,
  name:string,
  color: string
}

Assinging these types to a variable:

const selectedType: Ref< a | b | c | null> = ref(null);

and having a component (lest call it modal):

<LW2Modal :title="'modal'" v-model:currentType="selectedType" /></LW2Modal>

which its props are:

const props = withDefaults(
    defineProps<{
        currentType: a | b | null
    }>(),
    {},
);

It’s giving an error that I’m missing (“c”) obviously, but this modal is only intended to modify a | b, I’m doing this TO NOT HAVE MULTIPLE VARIABLES WHEN SELECTING ANY TYPE

is there a way for typescript to accept this?

Thanks guys 🙂

Whats the difference between these two codes. Why is one wrong and one right?

Below code is incorrect.

function lookUpProfile(name, prop) {
  // Only change code below this line
  for (let i = 0; i < contacts.length; i++){
    if (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)){
      return contacts[i][prop];
    }
    else if (contacts[i]["firstName"] === name && contacts[i].hasOwnProperty(prop) === false){
      return "No such property";
    }
    else if(contacts[i]["firstName"] != name){
      return "No such contact";
    }
  }
  // Only change code above this line
}

Below code is correct. Why is the top code incorrect and the below correct? I can’t seem to find where the fault is on the code at the top. I was under the impression both are correct.

function lookUpProfile(name, prop) {
  for (let i = 0; i < contacts.length; i++) {
    if (contacts[i].firstName === name) {
      if (prop in contacts[i]) {
        return contacts[i][prop];
      } else {
        return "No such property";
      }
    }
  }
  return "No such contact";
}

How can get clearer frequency data from the js AnalyserNode

I’m working on a site which will take live audio input and perform AI analysis. The model requires an fft data plot as input – which I can create using the AnalyserNode from the JS audio API (get frequency method).

Having plotted this data – whilst the technique picks up a little on the dominant frequencies of the audio sample – it tends to register large decibel values for many frequencies across the board (0-20k Hz) for sounds which should really produce an uneven distribution weighted towards the “pitch” of the sample (when I say ‘should’ I refer to the result from a FFT analysis of wav samples from the same microphone ran through a python FFT module); I know there are background frequencies picked up from these samples so perhaps it is simply being oversensitive but the decibel readings are surely too great at extremely high frequencies for that to be the sole cause.

Any ideas how I can improve the accuracy of these FFT results? The AI needs clear data with obvious dominant frequencies.

Here is the sort of decibel distro I would like for a sample of someone talking: enter image description here

And here is what I get: enter image description here