TypeORM entity throwing error when generating migration

I have a simple entity called Picture.ts and is has following content

const { Entity, PrimaryGeneratedColumn, Column } = require("typeorm");

@Entity()
export class Picture {
@PrimaryGeneratedColumn()
id: string;

 @Column()
 name: string;

 @Column()
 path: string;

 @Column()
 is_main: boolean;
}

My tsconfig.json is:

{
   "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": [
      "dom",
      "es6",
      "es2017",
      "esnext.asynciterable"
    ],
    "sourceMap": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "moduleResolution": "node",
    "removeComments": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "allowSyntheticDefaultImports": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "./src/**/*.tsx",
    "./src/**/*.ts"
  ]
}

When try running typeorm migration:generate it throws error like this

Error during migration generation:
/src/src/entity/Picture.ts:3
@Entity()
^

SyntaxError: Invalid or unexpected token
at wrapSafe (internal/modules/cjs/loader.js:1001:16)
at Module._compile (internal/modules/cjs/loader.js:1049:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Module.require (internal/modules/cjs/loader.js:974:19)
at require (internal/modules/cjs/helpers.js:93:18)
at /src/node_modules/typeorm/util/DirectoryExportedClassesLoader.js:42:39
at Array.map (<anonymous>)
at importClassesFromDirectories (/src/node_modules/typeorm/util/DirectoryExportedClassesLoader.js:42:10)

what could be the problem ?

Semicolons make deconstruction assignment problematic in Chrome Javascript Console

I ran the following code in turn in Chrome Javascript Console

{f}={f:3} // it created a new variable f with a value of 3
{f}={f:3}; // Uncaught SyntaxError: Unexpected token '='

{f}={f:3} // There is a blank line on it,error: Uncaught SyntaxError: Unexpected token '='

Why do they behave differently?

The problem extends from here: object_destructuring – Assignment separate from declaration

AoC day5, puzzle two – JS, no errors but wrong solution

I am stuck in debug hell. Code works for testdata, not for realdata

I am not loosing any datasets, as far as i can tell

of course i can provide a dataset, if necessary

console.log('day5a')
import { testData, realData} from "./day5data.js";

let data = testData.split('n')
let grid = createGrid(1000,1000)
let allReadings = []

getReadings()
drawLines()

let crossings = countCrossings()
console.log('crossings: ', crossings)


// console.log('hvReading: ', hvReadings)
function drawLines(){
    let x = allReadings.length
    console.log('allReadings.length ', allReadings.length)
    let noneForgotten = true
    allReadings.forEach(reading => {
        let x1= reading[0][0]*1, y1=reading[0][1]*1, x2= reading[1][0]*1, y2=reading[1][1]*1

        if     (x1 > x2 && y1 > y2) drawX1andY1bigger(x1, y1, x2, y2)
        else if(x1 > x2 && y1 < y2) drawX1andY2areBigger(x1, y1, x2, y2)
        else if(x1 < x2 && y1 < y2) drawX2andY2areBigger(x1, y1, x2, y2)
        else if(x1 < x2 && y1 > y2) drawX2andY1areBigger(x1, y1, x2, y2)
        else if(y1===y2){
            if(x1 > x2) drawHorizontal(y2,x2,x1)
            else drawHorizontal(y2,x1,x2)
        } else if(x1===x2) {
            if(y1>y2) drawVertical(x1, y2, y1)
            else drawVertical(x1, y1, y2)
        }
        else {
            console.log(reading, ' DONT FORGET ME')
            noneForgotten = false
        }
    })
    console.log(noneForgotten, ' noone')
}

// diagonal drawings
function drawX2andY1areBigger(x1, y1, x2, y2){
    for(;x1<=x2;x1++,y1--){
        grid[x1][y1]++
    }
}

function drawX2andY2areBigger(x1, y1, x2, y2){
    for(;x1<=x2;x1++,y1++) {
        grid[x1][y1]++
    }
}

function drawX1andY2areBigger(x1, y1, x2, y2){
    for(;x1>=x2;x1--,y1++) {
        grid[x1][y1]++
    }
}


function drawX1andY1bigger(x1, y1, x2, y2){
    for(;x1>=x2;x1--, y1--) {
        grid[x1][y1]++
    }
}

// horizontal drawings
function drawHorizontal(row, startCol, endCol){
    for (let i = startCol; i <= endCol ; i++) {
        grid[row][i]++
    }
}
function drawVertical(col, startRow, endRow){
    for (let i = startRow; i <= endRow; i++) {
        grid[i][col]++
    }
}

function getReadings(){
    for (let i = 0; i < data.length; i++) {
        data[i] = data[i].split(' -> ')
        for (let j = 0; j < data[i].length; j++) {
            data[i][j] = data[i][j].split(',').map(Number)
        }
        allReadings.push(data[i])
    }
}

function createGrid (cols, rows) {
    let grid = []
    for (let i = 0; i < cols; i++) {
        grid[i] = []
        for (let j = 0; j < rows; j++) {
            grid[i][j] = 0
        }
    }
    return grid
}


function countCrossings(){
    let crossings = 0
    for (let i = 0; i < grid.length; i++) {
        for (let j = 0; j < grid[i].length; j++) {
            if(grid[i][j] >=2) {
                crossings++
            }
        }
    }
    console.log('crossings', crossings)
    return crossings
}

wont let me post without more explanation, so: i am creating a two dimensional array, filled with zeros in createGrid()
i import the dataset, split it at linebrack, split every array in that at the ‘ -> ‘ arrow, split every array in that at the semicolon. i’m mapping it to number, just to be sure

after that, i draw “lines” at drawLines. depending on the coordinates, i raise the grid[i][j]++ in the functions described from line 44 to line 80

will provide further informationbs if nessecary

useEffect dependancy array

I’m using customHook to fetch data from an API.

const useFetch = () => {
   const dispatch = useDispatch();
   return async (callback, ...props) => {
      try {
         return await callback(...props);
      } catch (error) {
         const { msg } = error.response?.data || "Something went wrong";
         dispatch(showModal(msg));
         setTimeout(() => dispatch(hideModal()), 3000);
      }
   };
};

and using it inside useEffect

const customFetch = useFetch();
useEffect(() => {
      (async () => {
         const data = await customFetch(fetchUsers, token);
         if (data) setUsers(data.user);
      })();
   }, [token]);

But eslint is complaining about the missing customFetch dependency. If I add it it will end up in an infinite loop. How can I fix this?

Scrollmagic / I want to create a scene in a loop

I’m trying to use Scrollmagic to create an animation that displays text character by character.

I want to create a scene using a for loop, but it doesn’t work.

HTML


    <p class="letter">
    <span>H</span>
    <span>e</span>
    <span>l</span>
    <span>l</span>
    <span>o</span>
    </p>

JS (Doesn’t work)


    var letterElements = document.getElementsByClassName("letter");
    for (var n=0; n < letterElements.length; n++) {
        var scene = new ScrollMagic.Scene({
            triggerElement: letterElements[n],
            triggerHook:0.8,
            offset:100,
            reverse:false
        })
        .on("enter", function (event) {
            $('.letter').eq(n).children('span').each(function(i) { //Maybe this line is the problem
                $(this).delay(20 * i).queue(function() {
                    $(this).addClass('visible').dequeue();
                });
            });
        })
        .addTo(controller);

}

JS (Work)

It works when I write the following without using the for loop.


    var scene = new ScrollMagic.Scene({
        triggerElement: letterElements[0],
        triggerHook:0.8,
        offset:100,
        reverse:false
    })
    .on("enter", function (event) {
        $('.letter').eq(0).children('span').each(function(i) {
            $(this).delay(20 * i).queue(function() {
                $(this).addClass('visible').dequeue();
            });
        });
    })
    .addTo(controller);
    
    var scene = new ScrollMagic.Scene({
        triggerElement: letterElements[1],
        triggerHook:0.8,
        offset:100,
        reverse:false
    })
    .on("enter", function (event) {
        $('.letter').eq(1).children('span').each(function(i) {
            $(this).delay(20 * i).queue(function() {
                $(this).addClass('visible').dequeue();
            });
        });
    })
    .addTo(controller);
    
    ・
    ・
    ・
    ・

Datatables: Header misaligned with table body when scrolling to the right on reload

I have a datatable which works absolutely fine on page load. It has a horizontal scrollbar as the table width is very large and my first 3 columns are fixed. However, when I refresh the page, and I scroll to the right at the very end, the table header stays fixed and the table body alignment moves to the left such that they are no longer aligned. I removed the left-padding of 17px btw.

Here is the code:

 $(document).ready(function () {
    $('#tblEvents').DataTable({
        destroy: true,
        "scrollX": true,
        "scrollY": "600px",
        "scrollCollapse": true,
        "pageLength": 5,
        fixedColumns: {
            leftColumns: 3
        },
   });

Please help n thanks 🙂

How to mark some of checkbox list value as checked in Angular?

I have a checkbox list with websites. This list is created from 10 values, and I need to mark first 5 elements as checked. How we can do this in Angular? I use Angular Material checkbox.

 <section >
          <p>Value:</p>
          <p *ngFor="let data of websites | async">
            <mat-checkbox [value]="data.name">{{data.name}}</mat-checkbox>
          </p>
</section>

“websites” from *ngForm is an observable in which I get all websites.

Angular routing displaying the same app.component.html

I’m currently using Angular version 13.

As stated by the official documentation, routing should be done by creating a component and routing it like this in the app-routing.module.ts

const routes: Routes = [
{ path: 'first-component', component: 
FirstComponent },
{ path: 'second-component', component: 
SecondComponent },
];

but doing so will render my app.comoponent.html file without actually changing anything. I can see that the url changed, but that’s about it.
Other newer sources consider doing something like

{
path:'mainpage',
loadChildren: () => import('./mainpage/mainpage.module').then(m 
=> m.MainpageModule)
}

and, as the solution above, does not work for me. I’ve also added the <router-outlet></router-outlet> directive, (which was actually already added) but nothing changed. What is currently happening? Thanks!

pubnub removeListener doesn’t trigger on useEffect return

While opening a single chat works flawlessly, entering a chat, then leaving the chat screen and entering the chat again causes double messaging and the listener isn’t being removed despite placing it on the return in useEffect
I’ve even tried the solution in this thread: React Pubnub Chat. Message dublication or no message at all

Hopefully, you guys can help me identify the issue. thanks in advance!

 useEffect(() => {
   
    const listener = {
      message: (envelope: any) => {
        if (envelope) {
          const message = {
            channel: envelope.channel,
            message: {
              ...envelope.message,
            },
            uuid: envelope.publisher,
            timetoken: envelope.timetoken,
          }

          dispatch(setMessage(message))
// this log activates the same amount of times you entered and left the chat, because the listener isn't being removed
          console.log('Message listener activated!') 
        }

        //   setLastTimeToken(message.timetoken)
      },
    }

    pubnub.addListener(listener)
    pubnub.setUUID(employer._id)


    pubnub.fetchMessages(
      {
        channels: [ch],
        count: 100,
      },
      (status, response) => {
        if (response.channels[ch]) {
          dispatch(setMessages(response?.channels[ch]))
        } else {
          dispatch(setMessages([]))
        }
      },
    )
    pubnub.subscribe({ channels: [ch] })

    const usersInfo = channel.split('_')
    if (channel != employer._id && usersInfo[1] !== 'job') {
      const deeberId = usersInfo[0]
      getCandidateById(deeberId).then(res => {
        dispatch(setSelectedChatCandidate(res))
      })
    }
    renderDisplayName()

    return () => {
      pubnub.removeListener(listener) 

      pubnub.unsubscribeAll()
    }

  }, [])

how in javascript to check with the help of regular expressions matches the mask and pattern to this mask?

I’m trying to make a special input that will check the mask by the pattern of this mask for the correctness of the entered characters. I thought that I need to create an array with regular expressions for each character for the pattern. The pattern should include Latin and Cyrillic characters, spaces, dashes and underscores. I’m trying now to check if the check works, but anything can get into my input. What is the correct way to make sure that it checks the pattern and mask which characters should be included in the input?

export default {
  data: ()=>({
    plate_pattern:{
      app11le: "AAA11AA",
      cherr11y:"AAAA11A",
      a111pricot: "A111AAAAA"
    },
    pattern_key: this.plate_pattern,
    handler: "",
    mask: [{app11le:' ___ __ __'}, {cherr11y: '____ ___'}, {a111pricot: '_ _______'}],
    placeholder: '_',
    start: 0,
    isRight: true,

  }),

 methods:{
    isNumber(checkIfNumber){
      return !isNaN(checkIfNumber) && parseInt(+checkIfNumber) == checkIfNumber() && !isNaN(parseInt(checkIfNumber, 10))
    },
    isLetter(checkIfLetter){
      return isNaN(checkIfLetter) && checkIfLetter.toLowerCase() != checkIfLetter.toLowerCase() && checkIfLetter.length == 1
    },
    isRightSymbol(checkIfSymbolInArray){
      let arraySymbolExist = [
          {name: 'app11le', regex: /^[wа-я][wа-я][wа-я][0-9_][wа-я][wа-я]$/, check: true},
        {name:'cherr11y', regex:/^[wа-я][wа-я][wа-я][wа-я][wа-я][0-9_][wа-я]$/, check: true },
        {name:'a111pricot', regex: /^[wа-я][0-9_][0-9_][0-9_][wа-я][wа-я][wа-я][wа-я][wа-я][wа-я]$/ }
      ]
      return !checkIfSymbolInArray.match(arraySymbolExist)
    },
    inputFruitName(fruitsName){
      if(this.isNumber(fruitsName.key) || this.isLetter(fruitsName.key) && this.isRightSymbol(fruitsName.key)){
        this.isRight = false;
      }
    },

Show external json data in html table

I get this error when im trying to display my json data in html it says undefined.
i thinks it’s because it cant find my goods.varer and goods.pris and goods.billede. How can i solve it. Please help, its for an exam project.

this is my code

varer.js

document.getElementById("clickMe").addEventListener('click', async() => {
  let table = document.getElementById('varerTable');
  
  let result = await fetch("http://localhost:8200/varer/getproducts", {method: 'GET', headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
})
  .then(res => res.json())
  .catch(console.log("error"));

  let tableHtml = `<tr>
  <th>varer</th>
  <th>pris</th>
  <th>billede</th>
  </tr>
  `;
  for(const goods in result){
    tableHtml += `
    <tr>
    <td>${goods.varer}</td>
    <td>${goods.pris}</td>
    <td><img src="${goods.billede}" style="height:50px;width:50px;"</td>
    </tr>
    `;

  }
  table.innerHTML = tableHtml;
});

varer-controller.js

router.get("/getproducts", (req, res) =>{
    res.status(200).json(products)
    console.log(products)
   })

//vis varer for en kategori
router.get("/getproductsforenkategori/:varer", (req, res)=>{
let category = req.params.varer;

if(products[category]){
  
  res.status(200).json({[category]:products[category]});
}
else{
  res.sendStatus(404)
}
});

varer.json

[{"varer":"ss","pris":"sss","billede":""},{"varer":"ss","pris":"sss","billede":""}]

Need Help in Json

  1. Local Storage (Weight: 10%) When the user clicks one of the buttons in the top right corner
    (gold or gray), the system stores the color in the local storage and changes the color of “Best
    Cakes” to either gold or gray. When the page first loads, it reads the color in the local storage,
    and styles “Best Cakes” accordingly. Write code in the set_color function (in script.js) so that the
    color is stored in the local storage. Write code in show_color function (in script.js) so that the
    color is red from local storage and used to color “Best Cakes”.
  2. Building the cakes table based on JSON (Weight: 45%) Write JS code in the show_cakes
    function in script.js that does the following: The code loops through the cakes in data.js so that
    it generates HTML for data rows that show the number, cake name, calories, whether the cake
    is nut free, dairy free, and gluten free. The generated HTML should be shown in the body of the
    cakes table (id=cakes). Some data need to be shown in this way. If the calories are greater than
    4500, show the calories in red. Otherwise, if the calories are greater than 4200, show it in
    orange. Otherwise, show it in green (see Figure 1). You can add styling in style.css to help you
    with this part.
    For the nut-free, dairy-free, and gluten-free attributes, if the value is true, show a checkmark
    symbol (which is &#10004). Otherwise, show a symbol dash symbol (-). Again, have a look at
    Figure 1.
    Also, there is a search box on top of the cakes table. When the user types letters, the system will
    find cakes with names that match the names of the cakes in the data. Also, the search can find
    cakes based on the allergy type (e.g. nut free/cake free/etc.)
  3. Building the leaflet map (Weight: 30%) Show a leaflet map for Abu Dhabi. The map should be
    centered in these coordinates: 24.4539,54.3773, and with a zoom level of 12.
    Then, write a script (in the function show_map) that loops through the locations data in data.js
    (the variable locations). Add these as markers on the map. When the user clicks a marker, it
    shows the name of the location. See Figure 2.
  4. Form Validation (Weight: 15%) Validate the Order Your Cake form according to this logic:
     The name must be at least 10 characters long.
     If the user chooses a pecan pie cake, and nut allergies, an error message should show
    up: “Sorry, pecan pies have nuts”. If the user chooses a cheese cake and dairy allergies,
    an error message should show up: “Sorry, cheese cakes have dairy”.

required Output

Here is the Attached Files

Webrtc: how to broadcast one student to all participants

I have a WebRTC system that has one teacher, 10 or more students. The architecture is every student only connects to teacher.

The students are not interconnected since the network bandwidth is not as good as teacher, if too much connection may cause congestion.

But I now have a requirement that one student may need to broadcast to all students as well as the teacher(eg. the student is answing a question)

At this time I don’t want this student to connect to all other students, for the reason I mentioned above.

Is it possible use teacher as a proxy since the all the students have connected to teacher? I googled one possible method to route the teacher’s speaker(the student’s voice can be heared) to teacher’s microphone, but with no luck.

object conversion between objects javascript

how to change object from

const ob = {
  "61ac2727bc40d842e43c8726": {
    nama: {
      value: "dianaasdasd",
    },
    username: {
      value: "diana",
    },
    email: {
      value: "[email protected]",
      error: false,
    },
    userlevel: {
      value: "karyawan",
    },
    password: {
      value: "************************************************************",
    },
    jenis_kelamin: {
      value: "Perempuan",
    },
    alamat: {
      value: "sasddad",
    },
  },
};  

remove “61ac2727bc40d842e43c8726”, value and return object as follows
how to convert to

this image

https://i.stack.imgur.com/6Qi1C.png