customer.name.trim is not a function
TypeError: customer.name.trim is not a function
react js The code I wrote gives this error:
I have a save button that doesn’t work and gives an error like this. If you want, I can send all the codes.I would be happy if you help me.
Category: javascript
Category Added in a WPeMatico Campaign
CSS and JavaScript not applying correctly after migrating HTML content to Angular app component due to view encapsulation and script load order issues
I’m currently migrating a static HTML template into an Angular application. The original template works perfectly when placed directly in the index.html file of the Angular project. However, when I move the body content of this template into an Angular component (app.component.html), some of the CSS and JavaScript do not apply correctly, leading to styling and functionality issues.
Issue:
When I replace the <app.component.html> tag with the actual HTML content, everything works fine. But when I use the Angular component to render this content, some styles and JavaScript functionalities do not work as expected.
Request for Help:
I’m looking for insights into why this might be happening and how to properly migrate the content into an Angular component without losing the styling and JavaScript functionality. Any advice on troubleshooting steps or best practices for this kind of migration would be greatly appreciated.
Steps I’ve Taken:
Checked View Encapsulation: I have already investigated Angular’s view encapsulation settings. I tried setting the encapsulation to ViewEncapsulation.None in my component, but the problem persists.
Inspecting Styles: I used browser developer tools to inspect the applied styles. It seems that certain styles are either missing or overridden when the content is moved into the Angular component.
Script Loading Order: I’ve also checked the order in which the scripts are loaded. All necessary scripts (jQuery, Bootstrap, custom JS files) are included in the index.html and appear to be loading correctly.
TypeDoc Monorepo: Failed to convert one or more packages, result will not be merged together
It’s my first week as a junior in a frontend team and I was tasked with figuring out how to implement Typedoc in our monorepository to generate documentation for it. They told me to first try and document 2-3 components just to see how it works and also as an overall introduction with the code that I’m going to be working on in the future and then we can move on to documenting all of it. However, I have some trouble generating any Typedoc documentation…
I followed the instructions for Monorepos/Workspaces from the official documentation. There they have put a git repo as an example setup, which I followed closely for the implementation in our repo.
Here is a rough structure of our monorepository:
└── PROJECT-NAME/
├── packages/
│ ├── components/
│ │ ├── BarChart
│ │ ├── Chart
│ │ ├── Button
│ │ ├── Filter
│ │ └── etc
│ ├── libs/
│ ├── shared-internal/
│ └── types/
├── package.json
├── package-lock.json
├── tsconfig.json
├── typedoc.json
├── tsconfig.base.json
└── typedoc.base.jsonc
Here is what I have in my root level json files:
In the scripts in package.json i adde this script:
"docs": "typedoc --tsconfig tsconfig.base.json --out docs"
tsconfig.json:
{
"compilerOptions": {
"target": "ES2020",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"resolveJsonModule": true,
"paths": {
"libs/*": [
"./packages/libs/*"
],
"components/*": [
"./packages/components/*"
],
"types/*": [
"./packages/types/*"
]
},
"allowSyntheticDefaultImports": true,
"allowJs": true,
"esModuleInterop": true
},
"include": [
"./packages/**/*",
"packages/types.ts"
],
"exclude": [
"node_modules",
"**/__tests__/*"
],
"typeRoots": [
"node_modules/@types"
],
"files": [],
"references": [
{
"path": "./packages/components/Filter"
}
],
"composite": true,
// These options are necessary so that TypeDoc can resolve references across packages
"declaration": true,
"declarationMap": true
}
tsconfig.base.json:
{
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"composite": true,
"declaration": true,
"declarationMap": true
}
}
typedoc.json:
{
"entryPoints": [
"./packages/components/Filter"
],
"name": "Packages Example",
"entryPointStrategy": "packages",
"includeVersion": false,
"packageOptions": {
"includeVersion": true,
"entryPoints": [
"./packages/components/Filter"
]
},
"logLevel": "Verbose"
}
typedoc.base.json:
{
"$schema": "https://typedoc.org/schema.json",
"includeVersion": true
}
I am currently just focusing on generating a documentation for the Filter component. Here is what’s inside the Filter folder:
└── Filter/
├── src/
│ └── index.ts
├── package.json
├── tsconfig.json
└── typedoc.json
Here is what I have in my Filter json files:
tsconfig.json:
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "dist",
// "baseUrl": "../../../",
"paths": {
"components/*": [
"./packages/components/*"
]
}
},
"include": [
"src"
]
}
typedoc.json:
{
"extends": [
"../../../typedoc.base.json"
],
"entryPoints": [
"src/index.ts"
]
}
This is the currents status of these files. I build the project successfully and then I run:
npm run docs
I get this output in the terminal:
> typedoc --tsconfig tsconfig.base.json --out docs
[debug] Reading tsconfig at ./tsconfig.base.json
[debug] Using TypeScript 5.3.2 from ./node_modules/typescript/lib
[debug] Expanded ./packages/components/Filter to:
./packages/components/Filter/package.json
[debug] Reading project at ./packages/components/Filter
[debug] Reading tsconfig at ./packages/components/Filter/tsconfig.json
[info] Converting project at ./packages/components/Filter
[debug] Using TypeScript 5.3.2 from ./node_modules/typescript/lib
[debug] Expanded ./packages/components/Filter/src/index.ts to:
./packages/components/Filter/src/index.ts
[debug] Converting with 1 programs 1 entry points
packages/components/Filter/src/index.ts:1:18 - error TS2307: Cannot find module 'components/Base/src/index' or its corresponding type declarations.
1 import Base from 'components/Base/src/index';
~~~~~~~~~~~~~~~~~~~~~~~~~~~
packages/components/Filter/src/index.ts:2:19 - error TS2307: Cannot find module 'components/Panel/src' or its corresponding type declarations.
2 import Panel from 'components/Panel/src';
~~~~~~~~~~~~~~~~~~~~~~
packages/components/Filter/src/index.ts:3:27 - error TS2307: Cannot find module 'components/FilterElement/src' or its corresponding type declarations.
3 import FilterElement from 'components/FilterElement/src';
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
packages/components/Filter/src/index.ts:4:30 - error TS2307: Cannot find module 'types/index' or its corresponding type declarations.
4 import { FilterConfig } from 'types/index';
~~~~~~~~~~~~~
packages/components/Filter/src/index.ts:5:24 - error TS2307: Cannot find module 'components/CommandBar/src' or its corresponding type declarations.
5 import CommandBar from 'components/CommandBar/src';
~~~~~~~~~~~~~~~~~~~~~~~~~~~
packages/components/Filter/src/index.ts:94:11 - error TS2353: Object literal may only specify known properties, and 'properties' does not exist in type '{ objectName: string; type: string; orderIndex: number; title: string; parentItem: string; }'.
94 properties: {
~~~~~~~~~~
packages/components/Filter/src/index.ts:111:11 - error TS2353: Object literal may only specify known properties, and 'disabled' does not exist in type '{ objectName: string; type: string; orderIndex: number; title: string; parentItem: string; }'.
111 disabled: 'yes',
~~~~~~~~
[error] Failed to convert one or more packages, result will not be merged together
[debug] Full run took 4521ms
[error] Found 8 errors and 0 warnings
I suddenly get all of these errors that weren’t there before. I even tried it on another component but I get similar errors. I tried a lot of things, reached out to different people in my team and even to TeamGPT but my efforts were all in vain and i’m out of ideas as to how to solve this problem. So I would greatly appreciate it if you can give me a hand. 🙂
Why Safari dos not support overflow-anchor and how can I fix it?
When I insert a large element to the top of container, it will lose scroll position in Safari.
this.container.insertBefore(someLargeElement, first);
But when in Chrome it work fine.
How can I get same effect?
I try to use this code, but it will get crash when scroll fast:
var beforeTop = this.container.scrollTop;
var beforeHeight = this.container.scrollHeight;
this.container.insertBefore(sectionBefore, first);
var afterHeight = this.container.scrollHeight;
var addHeight = afterHeight - beforeHeight;
this.container.scrollTo(0, beforeTop + addHeight);
Cannot record audio on iOS Safari browser
I’m using MediaRecorder to record audio and sending it to the backend as a blob but I’m facing issue with iOS Safari browser where I’m getting blob of length 0 at the backend. Same code was tested on older iPhone (iOS 15.5) and everything works fine there, problem seems to be with iOS version 17.4 and above. Facing same issue with chrome as well on iOS.
Below is the code that converts chucks into blob:
async readFile(chunks, type = "audio/wav", filename = "abc") {
const name = `${filename}.${type.split("/")[1]}`;
return new Promise((resolve, reject) => {
const modifiedFile = new File(chunks, name, {
type: type,
});
const fileReader = new FileReader();
fileReader.readAsDataURL(modifiedFile);
fileReader.onloadend = () => {
resolve(fileReader.result);
};
fileReader.onerror = () => {
reject(fileReader.error);
};
});
}
Remove audio from specific audio track
I have this code, and i would like to remove audio from tracks 5 and 6. I had tried everything but is not working, I can mute the audio tracks but on edition program i can see the waves, can you help me ?
if (conv.format === 'mxf') {
// Add 8 audio tracks
ffmpeg(inputFile)
.audioCodec('pcm_s16le') // Codec de áudio para MXF
.outputOptions([
'-c:v mpeg2video', // Codec de vídeo para MXF
'-q:v 2', // Qa vídeo
'-map 0:v:0',
'-map 0:a:0',
'-map 0:a:0',
'-map 0:a:0',
'-map 0:a:0',
'-map 0:a:0', // this track i want to remove the audio but keep the track
'-map 0:a:0', //this track i want to remove the audio but keep the track
'-map 0:a:0',
'-map 0:a:0',
'-disposition:a:0 default' // Marcar trilha 1 como padrão
])
.save(outputFile)
.on('start', commandLine => console.log(`FFmpeg comando iniciado: ${commandLine}`))
.on('progress', progress => console.log(`Progresso: ${progress.percent}%`))
.on('end', () => console.log(`Conversão concluída: ${outputFile}`))
.on('error', err => console.error(`Erro na conversão de ${inputFile} para ${outputFile}: ${err.message}`));
} else {
// Outras conversões
ffmpeg(inputFile)
.outputOptions(conv.options)
.save(outputFile)
.on('start', commandLine => console.log(`FFmpeg comando iniciado: ${commandLine}`))
.on('progress', progress => console.log(`Progresso: ${progress.percent}%`))
.on('end', () => console.log(`Conversão concluída: ${outputFile}`))
.on('error', err => console.error(`Erro na conversão de ${inputFile} para ${outputFile}: ${err.message}`));
}
I tried to use ffmpeg comands to remove audio from track.
Sum of all values in array in Karate framework
-
def sum =0
-
def addToSum = function(x) { sum += x }
-
karate.forEach(array, addToSum)
-
karate.log(‘Sum of array elements:’, sum)
-
print sum
-
Match sum == value
-
I am using this function to add all the values in an array.
When using karate.log the actual value is displayed, while using print 0 is printed when evaluating sum is 0 only, value is not reflected
Embeed signup payment feature addd in facing issue
To enhance the embedded sign-up metadata by incorporating a feature that allows for the inclusion of card details, the following steps can be considered:
Objective: The primary objective is to integrate a functionality within the embedded sign-up form that securely captures and processes card information.
Implementation:
Data Fields: Introduce additional data fields in the metadata schema specifically designed to accommodate card details, ensuring these fields are aligned with PCI DSS (Payment Card Industry Data Security Standard) compliance requirements.
Encryption: Implement robust encryption mechanisms to protect sensitive card information both at rest and in transit, safeguarding it against unauthorized access.
Validation: Develop and integrate real-time validation algorithms to verify the accuracy and authenticity of the card details provided by the user.
Security: Emphasize the importance of maintaining rigorous security protocols, including tokenization and secure storage practices, to mitigate the risks associated with handling card data.
By adopting these measures, the embedded sign-up feature can be effectively enhanced to securely include card details while adhering to industry standards and best practices.
plzz provide the full details with code i i can execute this
Adding new row to the Django template table
I have a simple table generated from Django template variable:
{% for object in object_list %}
<tr>
<td class="c9">{{object.first_name}}</td>
<td class="c9">{{object.last_name}}</td>
<td class="c9">{{object.tel}}</td>
</tr>
{% endfor %}
I’m making insert to this model and the server side is done, but how to add a new row in top of this table?
With this method: var row = table.insertRow(0)?
or can I change this variable ‘object_list’ and row will be added automatically?
This simple solution ‘var row = table.insertRow(0);’ is not adding columns with CSS classes.
Resizing image without keeping the aspect ratio – three.js
So, I am trying to implement a feature of resizing an image like in PowerPoint: resizing the image without keeping the aspect ratio when the image is resized by dragging the edges.
For instance, if the user drags the top arrow upwards, the image height is increased, but the image is not moved at all and the bottom edge is not moved either. This logic also works when you rotate the image in powerpoint.
I am having some issues with my code in which when the top edge is dragged, the image is also moved horizontally. So, the horizontal vector of the top edge is NOT BLOCKED.
The important thing is that the solution should also work when the image is rotated.
I have no clue how to fix this.
This is the code for the resizing of the top edge:
if (object === arrows[0]) {
// Top edge
// object.position.x = mesh.position.x;
// object.position.z = mesh.position.z;
const height = Math.abs((object.position.z - arrows[2].position.z) * cos + (object.position.x - arrows[2].position.x) * sin);
mesh.scale.y = height/ (image.height * scale );
// Get the direction from the current object to arrows[2]
const direction = arrows[2].position.clone().sub(object.position).normalize();
// Get the new position of the object
const newPosition = object.position.clone().add(direction.multiplyScalar(height / 2));
// Set the position of the object
mesh.position.set(newPosition.x, mesh.position.y, newPosition.z);
}
I noticed that if I enable the object.position.x = mesh.position.x in the beginning of the if statement, the image is blocked from moving horizontally when the image IS NOT ROTATED. But when the image is rotated, the image moved very fast horizontally when dragging the top arrow.
If I change the code mesh.position.set(newPosition.x, mesh.position.y, newPosition.z); to mesh.position.set(mesh.position.x, mesh.position.y, newPosition.z); the image is blocked from moving horizontally when dragging the top edge, but then the bottom edge is moved.
So, my conclusions so far is that I cannot modify the code of the height, mesh.scale.y, direction, newPosition and the mesh.position.set. There is something else that I should add to block the horizontal vector of the top edge.
Forcing browsers to recheck the `:active` state?
div:active {
color: red;
}
<div>test</div>
In this trivial example, on Chrome, the element can be stuck in the :active state. Here’s a video: https://i.imgur.com/6GeQJlM.mp4
Even though my mouse has left the element, Chrome is still applying :active to it.
On desktop Chrome, it’s not a big deal, since :active styles get removed after I interact with the page. However, on Android Chrome, the :active style can persist until I refresh the page. I noticed that this issue often occurs when I switch apps right after tapping an element with :active. My hypothesis is that after switching back to Chrome, Chrome doesn’t check that the element is no longer in the :active state.
Is there a way to force browsers to recheck the :active state for every element? I’d do this when switching back to my web app, i.e. using visibilitychange.
I tried adding and removing display: none, document.activeElement.blur(), calling focus() on another element, adding tabindex, etc. The only thing that worked was removing and adding back the style, but that seems error-prone.
Error with the width of elements on the responsive page
I had a problem with a page I’m developing. For some reason, when I readjusted the size of the page to test the responsiveness, in netbook resolutions, the content does not occupy the entire screen but only a part. The strange thing is that when inspecting the elements, they all appear to have the same width as the screen, when at first glance it seems that they do not.
I tried to assign it to occupy the entire width of the screen but it clearly didn’t work
NextAuth Twitter authentication not working
Every time I attempt to authenticate with Twitter using the code I’ve implemented with NextAuth, I encounter issues. The authentication process involves storing the relevant data in a Supabase database. Despite my efforts to configure everything correctly, I’m running into obstacles that are preventing a successful authentication. Specifically, I suspect there might be issues related to how the authentication tokens or session information are being managed and stored in Supabase, but I’m not entirely sure where the problem lies. I’m seeking guidance on how to properly troubleshoot and resolve this issue so that Twitter authentication works seamlessly with my Next.js application:
import NextAuth from 'next-auth';
import TwitterProvider from 'next-auth/providers/twitter';
import { createClient } from '@supabase/supabase-js';
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.SUPABASE_SERVICE_ROLE_KEY!
);
export const authOptions = NextAuth({
providers: [
TwitterProvider({
clientId: process.env.TWITTER_CLIENT_ID!,
clientSecret: process.env.TWITTER_CLIENT_SECRET!,
}),
],
secret: process.env.NEXTAUTH_SECRET!,
callbacks: {
async jwt({ token, account, user }) {
if (account) {
token.accessToken = account.access_token;
const { data, error } = await supabase
.from('accountsx')
.upsert({
userid: user?.id,
provider: account.provider,
provideraccountid: account.providerAccountId,
accesstoken: account.access_token,
refreshtoken: account.refresh_token,
}, {
onConflict: 'provideraccountid',
});
if (error) {
console.error('Error storing Twitter access token in Supabase:', error);
}
}
return token;
},
async session({ session, token }) {
session.accessToken = token.accessToken as string | undefined;
return session;
},
},
});
export { authOptions as GET, authOptions as POST };
I get this error (I am sure from all the keys and callback url)
[next-auth][error][SIGNIN_OAUTH_ERROR]
https://next-auth.js.org/errors#signin_oauth_error undefined {
error: {
statusCode: 401,
data: '{"errors":[{"code":32,"message":"Could not authenticate you."}]}'
},
providerId: 'twitter',
message: undefined
}
I tried and checked all the keys and parms, but I couldn’t sign in
div is opening upside/upwards on mobile screen when we do hide and show
I have something similar to accordion in vuejs, when i click on it, it shows specifications, when i click again on it, it hides the specifications, its working fine on desktop, but on mobile screen the div opens upward/upside, don’t know why. I need that it should open downward. I can’t given static height, as the data is dynamic.
Below is my code:
<template>
<div
class="bg-white border boder-light px-4 relative"
>
<div @click="show = !show" class="py-3 cursor-pointer">
<h1 class="text-xl m-0" :class="[show ? 'text-black' : 'text-blue-600']">{{getLabel('Specifications')}}</h1>
<div class="text-primary text-[25px] absolute top-4 right-8">
<i v-if="!show" class="fa fa-angle-down"></i>
<i v-else class="fa fa-angle-up"></i>
</div>
</div>
<div :class="{'flex': show, '!hidden': !show}" class="row gy-1 mb-4 cursor-default">
<hr class="my-[9px] bg-gray-400" />
<dl class="custom-columns">
<template v-for="(item, innerIndex) in data" :key="innerIndex">
<div>
<dt class="text-gray-500 text-base font-normal">{{ getLabel(item.title) }}</dt>
<dd class="text-md py-1 text-sm vehicle-details-span" v-if="item.value">{{ getLabel(item.value)}}</dd>
<dd class="text-md py-1 text-sm vehicle-details-dash-span" v-else>-</dd>
</div>
</template>
</dl>
</div>
</div>
</template>
<script>
import { mapGetters } from "vuex";
import {
getLabel as getLabelHelper, checkIfInputIsOptional as checkIfInputIsOptionalHelper
} from "../Utils/helper.js"
export default {
props: {
data: {
type: Array,
},
},
data() {
return {
show: false,
}
},
computed:{
...mapGetters(["allLabels"]),
...mapGetters(["selectedLang"]),
},
methods:{
getLabel(currentLabel) {
return getLabelHelper(currentLabel, this.allLabels)
},
checkIfInputIsOptional(currentLabel) {
return checkIfInputIsOptionalHelper(currentLabel, this.allLabels)
}
}
}
</script>
On Desktop sreen, div opens downward, but on mobile div opens upward, page doesn’t scrolls, user stays where he was, the only problem is it should open downwards.
please check my above code, i have tried several different things, but nothing worked.
Check the image:
enter image description here // Spesifikasjoner means Specifications
How to Ensure Type Safety in TypeScript When Transforming Objects Through Multiple Stages?
I’m working on a NestJS application where I need to create different types of entities (like Users, Products, Orders, etc.) and apply some transformations before saving them to the database. Specifically, I want to add a version number and some IDs to the entity if it’s of a certain type (e.g., User).
I created new interfaces (EntityWithVersion, EntityWithIds) to handle the additional properties. Is this the best approach to ensure type safety, or is it better to user an interface that represent the whole object?
I will be using nestjs, since I’m with familiar with to illustrate this example:
interface CreateEntityDto {
type: EntityType;
data: any; // Generalized to any type
}
enum EntityType {
User,
Product,
Order,
}
interface EntityWithVersion extends CreateEntityDto {
version: number;
}
interface EntityWithIds extends EntityWithVersion {
ids: string[];
}
@Injectable()
export class EntityService {
constructor(
@InjectModel('Entity') private readonly entityModel: Model<Entity>,
) {}
async create(createEntityDto: CreateEntityDto): Promise<Entity> {
if (createEntityDto.type === EntityType.User && createEntityDto.data) {
const entityWithVersion = await this.addEntityVersion(createEntityDto);
const entityWithIds = await this.addEntityIds(entityWithVersion);
return await this.entityModel.create(entityWithIds);
}
return await this.entityModel.create(createEntityDto);
}
async addEntityVersion(
entity: CreateEntityDto,
): Promise<EntityWithVersion> {
return {
...entity,
version: 1,
};
}
async addEntityIds(
entity: EntityWithVersion,
): Promise<EntityWithIds> {
return {
...entity,
ids: ['id1', 'id2'],
};
}
}
In my project, I needed to manage objects that go through various transformations, with new properties being added at different stages. To ensure type safety, I decided to create new interfaces that extend the original data transfer object (DTO) each time a new property was added.