Structure of a multilingual dictionary in mongodb

I want to design a Multilanguage dictionary, So I have 2 options for the structure of the database in mongodb:

1) Create a new database and include dics like en, es, de, etc as collections. then in each collection we can have the structure like this:

This is the en collection for instance:

{
    word: 'entrust',
    meaning: {
        es: 'konfidi',
        de: 'anvertrauen',
        ar: 'ودع'
    }
}

2) or we can create collections like this, en-es, en-de, en-ar:

This is the en-es collection for instance:

{
    word: 'entrust',
    meaning: 'konfidi'
}

Please help how do you design this structure ?

Which one is faster to query a word ?

My discord bot is not being online when I run it [closed]

I was watching a video on how to make a discord bot with discord.js, this is the code.
This code is in a file that was set by NPM to the entry point.
This file is called index.js

const discord = require('discord.js');

const client = new discord.Client();

client.once('ready', () => {
    console.log("Management bot is now online!")
})

client.login('Private info') // =========> I did not put the actual discord token.

I tried to maybe change the import to another way but it did not work.

When I want to run the project by saying node . / node index.js,

I get this error:

at Object. (C:UsersSashaDesktopCustom Discord BotsTutorialindex.js:3:16)

I do not know what is the problem here.

When I get e.target, the same 3 numbers appear, How can I get number 1 every time I press it?

   const cards = document.querySelectorAll(".cards")

   function click_x(e){ let click_card = e.target; click_card.innerText = "x";

   let card1 = click_card.id   
   let card2 = click_card.id
   let card3 = click_card.id
    

            
  console.log(card1,card2,card3)
   
  cards.forEach(card=>{ card.addEventListener("click",click_x);

    });
  

When I make console.log, 3 of the same number comes out every time, but I want to leave 1 number every time I press it

setting state in nested setTimeouts bug

I’m trying to add JSX elements to a state array on a timer. So once the component is rendered, after 1200ms, a JSX element should be added to the array. 2 Seconds later, another JSX element should be added to the array.

The issue is, once the second setBlocks is called, the first JSX Element gets removed. Wondering if there is a way around this, or a better way to pull this off. Here is the useEffect:

  useEffect(() => {
    setTimeout(() => {
      setBlocks([...blocks, serverBlock]);
      setTimeout(() => {
        setBlocks([...blocks, commandBlock]);
      }, 2000);
    }, 1200);
  }, []);

And here is how I’m rendering the elements:

{blocks.map((block) => block)}

How can I save data of products from the same template after pressing the add-to-cart button many times and display them in the shopping cart file?

**The code consists of 3 separated HTML file as follows:
**

1- “SHOP.html” An HTML file representing the shop (from where we can select a product)

2- “SPRODUCT.html” An HTML file with a varying content representing a template for the single selected product (includes the “add-to-cart” button, to add the selected product to the shopping cart)

3- “CART.html” An HTML file representing the shopping cart (In where I would like to have the list of the selected product from the “SPRODUCT.html”).

Whenever I select a product from the SHOP, the product details takes a place in the SPRODUCT template, then, I press the “add-to-cart” button to add it to the shopping cart. Then, I get back to the SHOP to select another product.

The problems is:
1- When I press the “add-to-cart” button (representing a specific product at that moment), I lose the old saved data of the previously selected product in the dataset “cartData”.

Here are my codes for the HTML files and their Javascripts:

FILE: SPRODUCT.html

        <section id="prodetails" class="section-p1"> 
            <div class="single-pro-img">
                <a class="single-pro-img-class"></a>
            </div>
            <div class="single-pro-details">
                <span class="prod-brand"></span>
                 <h5 class="prod-name"></h5>
                <div class="star">
                    <i class="fas fa-star"></i>
                    <i class="fas fa-star"></i>
                    <i class="fas fa-star"></i>
                    <i class="fas fa-star"></i>
                    <i class="fas fa-star"></i>
                </div>
                <h5 class="prod-price"></h5>
                <select>
                    <option>SELECT TYPE OF NUTS (Stuffing and Decoration)</option>
                    <option>الكاوكاو</option>
                    <option>اللوز</option>
                    <option>الجوز</option>
                    <option>الفستق</option>ذ
                    <option>خليط من كل المكسرات</option>
                </select>
                <input type="number" value="1">
                <a class="add-cart-button"><button class="normal">Add To Cart</button></a> 
            </div>
        </section>

FILE: SPRODUCT.js

// ########## ADD TO CART BUTTON ########################################################

    var addToCartButtons = document.getElementsByClassName('add-cart-button')
    console.log(addToCartButtons)
    const cartItem = [];
   
    var button = addToCartButtons[0]
    button.addEventListener('click', function (event){
        var button = event.target
        var shopItem = button.parentElement.parentElement.parentElement
        var title = shopItem.getElementsByClassName('prod-name')[0].innerText.replace('Name:','')
        var price = shopItem.getElementsByClassName('prod-price')[0].innerText.replace('Price:', '').replace('DZD', '')
        var imgSrc = shopItem.getElementsByClassName('prod-img')[0].src
        console.log(title, price, imgSrc)
        // return(title, price, imgSrc)
        const productItem = [title, price, imgSrc]
        cartItem.push(productItem);
    
        localStorage.setItem('cartData', JSON.stringify(cartItem));
        console.log(cartItem)

    });

FILE: CART.html

        <section id="cart" class="section-p1">
            <table width="100%">
                <thead>
                    <tr>
                        <td>REMOVE</td>    
                        <td>IMAGE</td>    
                        <td>PRODUCT</td>    
                        <td>PRICE</td>    
                        <td>QUANTITY</td>    
                        <td>SUBTOTAL</td>    
                    </tr>
                    <tbody class="cart-items">

                        
                    </tbody>
                </thead>
            </table>
        </section>

FILE: CART.js

        <script>

                let cartData = JSON.parse(localStorage.getItem("cartData"));
                var cartItems = document.getElementsByClassName("cart-items")[0]

                for (var i = 0; i<cartData.length; i++) {
                    this["cartData"+i]=cartData[i]
                }

                    let cartHTML = `
                    <tr class="cart-row">
                        <td><a href="#" type="button" class="cart-remove-button"><i class="far fa-times-circle"></i></a></td>
                        <td><img src="${cartData0[2]}" alt=""></td>
                        <td>${cartData0[0]}</td>
                        <td class="cart-price">DZD ${cartData0[1]}</td>
                        <td><input class="cart-quantity-input" type="number" value="1"></td>
                        <td class="cart-sub-total">DZD ${cartData0[1]}</td>
                    </tr>`;
                    cartItems.innerHTML = cartHTML;

        </script>

1- I expect saving and maintaining all the selected products after pressing the common “add-to-cart” button in the SPRODUCT.html template. But it does achieve this.

2- I don’t know how to creat a “for” loop that loops in the “cartData” and displays all the products in the cartData not only the first. I think this requires making the cartHTML variable in the “for” loop and I don’t know how to achieve that.

Could you please provide me with guidance to achieve the above two tasks that I believe will solve it?

Converting Decimal, Binary & Hex using JavaScript (JS)

I’m I senior in high school, and I have a make or break project due in 2 days. I’ve started some it. It’s a program that’s supposed to convert between Decimal/Binary/Hexadecimal. I found this tutorial. However, I want to do things differently, as he has 6 textboxes with a button for each, and the result goes into a separate space. But I want 3 textboxes with a convert button for each, and the result to goes into the other boxes. As so:
My Site so far

Here’s my important code:
My HTML code, besides the visual aspect
My JS file, renamed some of the values

Lmk if I should keep it as the tutorial did, and if my binary to decimal conversion is wrong or bad, as I think it’s the easiest to convert, but it still isn’t.

We both have a singular function, but I want 2 separate results from it on one onClick event. As you can see I tried to do 2 onClick events on with the button too no avail. And I don’t know how to give 2 results from the output parameter. And I’m skeptical of adding a parameter called output2, because, I feel I’m going to have to null one parameter for a base conversion and another parameter for the other conversion.

I would’ve posted actual code, however, unfortunately, Stack Overflow gives me a hard ass time when trying to post any, sorry. And I apologize if it’s really long, but I wanted to be as detailed as possible. If I post extra questions in the comments, please respond, as I really need it, and would appreciate it.

I can’t figure out why any I’m getting the following error even I am passing a value

regionsData: RegionData[]=[];//this array has the properties as id and name

  findRegion(regionId: string) {
    console.log(regionId)
    this.regionsData.find(x => {
      console.log(x)
      
        if (x.location.id === regionId) {//----------Here at this point I'm getting the error as 
//ERROR TypeError: Cannot read properties of undefined (reading 'id') which is the above line
          this.region.location.id = x.location.id;
          this.region.location.name = x.location.name;
          console.log(this.region, x)
        }
        
    })
  }
  
  region: RegionData={
    location: {
      id: '',
      name: ''
    }
  }
  edit(regionId: string) {
    console.log(regionId, this.regionsData)
    this.findRegion(regionId)//----calling the find method here from top
    console.log(this.region)
    const dialogRef = this.dialog.open(NewRegionComponent, {
      data: {
        isUpdate: true,
        id:regionId,
        name:this.region.location.name
        // regionData: this.region.location
      }
    })

  }

I tried alot to find the reason to the following undefined problem but I’m failed to identity it.
Help me out to get rid of it
I tried

if(x.location.id!==undefined){...}

But Still I didn’t got it and on the console its pointing error at the html part which is totally fine

I am trying to declare some types and keep getting TS1131 errors. Data come from API

So I understand the issue and know that the object need to be labeled. But the data from the API comes back without any specific label. Just an Object in an array.

Now when I only write for the first object only, everything is well. But I need data from the second object aswell. So, I need to declare the types.

Here is My code.

This is the data from the API .json

Those objects are two distinct objects that need to be accessed separately.


{

label_1: {
        "arr_1": [{
            "key": "value",
        }],
        "arr_2": [{
            "key": "value"
            "arr_3": [{
                "key": "value"
            }],
            "arr_3": [{
                "key": "value"
                    "label_2": {
                        "key": "value"
                        "arr_4": [{
                            "key": "value"
                            "arr_5": [{
                                "key": "value"
                            }]
                        }],
                        "arr_6": [{
                            "key": "value"
                            "label_3": {
                                "key": "value"
                                "label_4": {
                                    "key": "value"
                                    }
                            }
                        }]
                    }
                }
            , **This is the Huge issue** **How can I fix this** {
                "key_x": "value_x"
                "label_x_1": {
                    "label_x_2": {
                        "key_x": "value_x"
                        "arr_x_1": [{
                            "key_x": "value_x"
                            "label_x": {
                                "key_x": "value_x"
                            }
                        }]
                    }
                }
            }] 
        }]

}


}


This is the Type declarations.
I can’t declare arr_3 because it has two distinct objects. I would love to access those objects separately. If I am to only declare for on object, everything works well. and TS uses the label for the array as the name of the object.

I can’t do so for 2 objects in the same Array.


Data: {



label_1: {
        "arr_1": {
            "key": "string"
        }[];
        "arr_2": {
            "key": "string";
            "arr_2_1": {
                "key": "string"
            }[];
            
            
            **This is the issue**
            
            "arr_3": [{
                "key": "string";
                    "label_2": {
                        "key": "string";
                        "arr_4": {
                            "key": "string";
                            "arr_5": {
                                "key": "string"
                            }[];
                        }[];
                        "arr_6": {
                            "key": "string";
                            "label_3": {
                                "key": "string";
                                "label_4": {
                                    "key": "string"
                                    };
                            };
                        }[];
                    };
                };
            ,
**This is the Huge issue** **How can I fix this** 

 {
                "key_x": "string";
                "label_x_1": {
                    "label_x_2": {
                        "key_x": "string";
                        "arr_x_1": {
                            "key_x": "string";
                            "label_x": {
                                "key_x": "string"
                            };
                        }[];
                    };
                };
            };
            
          
          **end of array with issue**
            ] 
            
            
            
        }[];

};


}


I was expecting no issues. I tried naming the object with the name of the of the array but I get this error Duplicate identifier ‘arr_2’.ts(2300) . Have anyone had this issue ? How can I fix this ?

I want to customize MUI Grid height

I’m new to React. I want to limit MUI Grid height.

I divided my project in to 3 parts using MUI grid. I want to limit the height of the page to remove Browser scrollbar. If the content overflow in any grid I want to add custom scrollbar. But I can’t Limit the size of my page I used height: 100vh, height: 100%, max-Height: 100vh etc… in css file none of them worked for me. Is it possible?

AJAX sending POST request and asp.net receiving GET

Halo, Im doing my cs project for school in web service using asp.net, c#. Im having a problem that when Im sending an AJAX POST request Im receiving a GET request, I couldnt find the problem myself pls help 🙂

I tried to send an AJAX POST request when a textbox is being changed to the backend to write the textbox to a file, but when Im doing Request.HttpMethod Im getting a GET request.

this is my AJAX function:

        function saveText() {
            event.preventDefault();
            var url_string = window.location.href;
            var url = new URL(url_string);
            var name = url.searchParams.get("name");
            var id = url.searchParams.get("id");
            var filename = name + id;
            var text = document.getElementById('fileTextArea').value;
            $.ajax({
                method: "POST",
                url: "FilePage.aspx?id=" + id + "&name=" + name,
                data: {
                    "text": "hello world"
                },
                dataType: "html",
                success: function (response) {
                    console.log('File written successfully!');
                },
                error: function (xhr, status, error) {
                    console.log('Error writing file: ' + error);
                }
            });
        }

and this is my Page_Load function:

        protected void Page_Load(object sender, EventArgs e)
        {
            string name = Request.QueryString["name"];
            string id = Request.QueryString["id"];
            string path = "C:\Users\User\source\repos\filmhelperschoolproject\filmhelperschoolproject\Files\";
            if (Request.HttpMethod == "POST")
            {

                string text = Request.Form["text"];
                File.WriteAllText(path + name + id + ".txt", text);
                return;

            }
            if (!IsPostBack)
            {
                fileTextArea.InnerText = "";


                string [] lines=File.ReadAllLines(path + name + id + ".txt");
                foreach( string line in lines)

                {
                    fileTextArea.InnerText += line + "n";
                }

            }
            
        }

pls help 🙂

(P.S u look very nice today sir! )

NavLink in my nav-header is not working when I turn to Mobile view

I have problems with a navlink in my Navbar that wouldn’t work in mobile view.
Problem is I totally don’t see what’s the problem…

Can someone please help me with this!

Thanks!

Here is my JS-code:

const Navbar = () => {

function colConCollapse() {
        const colCon = document.querySelector(".container-fluid");
        setOpen(!Open)
        colCon.classList.toggle("collapse")
    }


return(

<div className="container-fluid m-2">
                <div className="navbar-header">
                    <NavLink className="navbar-brand" to="/">
                        <span className="p-2"><img src={Logo} width="50" height="50" alt=""/></span>
                        Newsaggregator
                    </NavLink>
                </div>
                <div className="toggle-collapse">
                    <div className="toggle-icon">
                        <span><Hamburger toggled={Open} onToggle={colConCollapse}/></span>
                    </div>
                </div>
                <ul className="nav navbar-nav allign-items-center mr-4">
                    <li>
                        <NavLink to="/" onClick={colConCollapse}>Home</NavLink>
                    </li>
                    <li>
                        <NavLink to="/about-us" onClick={colConCollapse}>About Us</NavLink>
                    </li>
                    
                </ul>

            </div>

);
};

And this is my CSS code for the mobile view:

@media only screen and (max-width: 910px) {
  .container-fluid .navbar-header {
    position: fixed;
    padding-top: 8px;
    padding-left: 20px;
    width: 100%;
  }

  ul.nav.navbar-nav {
    flex-direction: column;
    justify-content: center;
  }

  ul.nav.navbar-nav.text-center {
    text-align: center;
  }

  .nav.navbar-nav li {
    justify-content: center !important;
    align-content: center;
    width: 100%;
    border-bottom: 1px solid black;
  }

   .nav.navbar-nav li:active {
    justify-content: center !important;
    align-content: center;
    width: 100%;
    border-bottom: 1px solid black;
  }

  .nav.navbar-nav li:first-child {
    margin-top: 60px;
  }

  .nav.navbar-nav li:nth-child(2) {
    padding-bottom: 1rem;
  }

  .navbar {
    background-color: #fef7e5;
    box-shadow: 0 1px 7px rgba(0, 0, 0, 0.25);
  }

  .container-fluid {
    flex-direction: column !important;
    justify-content: center;
    display: block;
    height: 0;
    min-height: 5vh;
    overflow-y: hidden;
    transition: all 1s ease;
  }

  .toggle-collapse {
    position: absolute;
    top: 0%;
    width: 100%;
  }

  .toggle-collapse .toggle-icon {
    display: flex;
    justify-content: flex-end;
    padding: 1rem 2rem;
  }

  .collapse {
    height: auto;
  }

  .nav.navbar-nav a {
    font-size: 25px;
    font-weight: 400;
    color: black;
    text-decoration: none;

    padding: 0px;
    display: table-cell;
  }

.navbar-brand img {
    width: 30px;
    height: 30px;
  }

.navbar-brand{
    z-index: -1;
}
}

I already changed the z-index, because I think/thought it was just the toggle-icon covering the newsaggregator, but that didn’t work…

Why nextjs api route can’t fetch microsoft azure cloud function?

When I try to make a request to my api route i get 500 Internal Server Errorm and error is fetch failed, and I utterly baffled about the reason of this error. If I open my cloud function url in the browser it gives me my response and works fine, and the authLevel is anonymous so everyone can make a request to this func.

API route

export async function GET(request: Request) {
    try {
        // Connect to mcrft azure func endpoint
        const response = await fetch(
            `${process.env.VERCEL_URL || "http://localhost:7071"
            }/api/getChatGPTSuggestion`,
            {
                cache: "no-store",
            }
        );

        const textData = await response.text();

        return new Response(JSON.stringify(textData.trim()), {
            status: 200,
        });
    } catch (error) {
        console.log("error inside get route", error)
        if (error instanceof Error) {
            return new Response(error.message, { status: 500 });
        }

        return new Response("Internal Server Error", { status: 500 });
    }
}

Cloud function

const { app } = require('@azure/functions')
const openai = require('../../lib/openai')

app.http('getChatGPTSuggestion', {
  methods: ['GET'],
  authLevel: 'anonymous',
  handler: async (request, context) => {
    const response = await openai.createCompletion({
      model: 'text-davinci-003',
      prompt:
        '...',
      max_tokens: 100,
      temperature: 0.8, different and sharp
    })

    context.log(`Http function processed request for url "${request.url}"`)

    const responseText = response.data.choices[0].text

    return {
      body: responseText,
    }
  },
})

How can I create an Array of objects from arr array in javascript using spread operator?

Need to create one object per objectid and create an array of contacts for that object.
I have done it without spread operator but wondering how this can be done using spread operator.

const arr = [
  {
    "objectid": 1,
    "userid": "1",
    "associationid": "123"
  },
  {
    "objectid": 1,
    "userid": "2",
    "associationid": "456"
  },  
  {
    "objectid": 2,
    "userid": "2",
    "associationid": "456"
  }
];
//My working code without using spread operator
let res = Object.values(
  arr.reduce((acc, {objectid, userid, associationid}) => {
    (acc[objectid] ??= {objectid, contacts : []}).contacts
      .push({isdelete: '1', contactid: userid, associationid});
    return acc;
  }, {})
);
console.log(res);

//Tried the following code using spread operator but not working
const res = arr.reduce((acc, {objectid,userid,associationid}) =>
  ({ ...acc, (acc[objectid] ??= {objectid, contacts : []}).contacts.push({isdelete: '1', contactid: userid, associationid}) }),
  {})
  
console.log(res);

How to combine multiple row values fetched from excels (to HTML) if Col A cell values is blank or doesn’t exist?

This is the uploaded excel sheet.

enter image description here

After running through my code, the black color of the image is the current output according to the code. The blue check means it works well, but I want to achieve the Red Output.

enter image description here

.table{
    border:solid 1px;
    //width: 50mm;
    //height: 30mm;
    table-layout: fixed;
    border-collapse:collapse; //in table css, collapse is equivalent to cellspacing in table css and paddling is :enabled in td
    padding:0mm 0mm 0mm 0mm;
}

td {
    //border:solid 1px;
}

.itemname{
    //border:solid 1px;
    height: 10mm;
    width:  48mm;
    margin: 0mm;
    font-family: Helvetica, sans-serif;
    font-size:  3mm;
    line-height:    3mm;
    z-index:    1;
    padding-top:    0mm;
    padding-bottom: 0mm;
    padding-left:   1mm;
    padding-right:  1mm;
    text-align: center;
    vertical-align: top;
    overflow:   hidden;
    max-width:  100%;
    max-height: 100%;   
}

.price{
    //border: solid 1px;
    height: 8mm;
    width:  28mm;
    margin: 0mm;
    margin-right: 0mm;
    font-family:    Helvetica, sans-serif;
    font-size:  1.5em;
    font-weight:    600;
    padding-top:    0mm;
    padding-bottom: 0mm;
    padding-left:   0mm;
    padding-right: 1mm;
    text-align: right;
    vertical-align: top;
    overflow:   hidden;
    max-width:  100%;
    max-height: 100%;
}

.suppliers{
    //border:solid 1px;
    height: 5mm;
    width:  15mm;
    margin: 0mm;
    font-family:    times new roman;
    font-size:  2mm;
    line-height:    2mm;
    z-index:    1;  
    padding-top:    0mm;
    padding-bottom: 0mm;
    padding-left:   0mm;
    padding-right:  0mm;
    text-align: right;
    vertical-align: top;
    overflow:   hidden;
    max-width:  100%;
    max-height: 100%;    
}



  .pagebreak {
    page-break-inside:avoid;
}
<html>
    <head>
        <body>
            

<script>
    // Method to upload a valid excel file
function upload() {
  var files = document.getElementById('file_upload').files;
  if(files.length==0){
    alert("Please choose any file...");
    return;
  }
  var filename = files[0].name;
  var extension = filename.substring(filename.lastIndexOf(".")).toUpperCase();
  if (extension == '.XLS' || extension == '.XLSX') {
      //Here calling another method to read excel file into json
      excelFileToJSON(files[0]);
  }else{
      alert("Please select a valid excel file.");
  }
}

//Method to read excel file and convert it into JSON 

function excelFileToJSON(file){
    try {
      var reader = new FileReader();
      reader.readAsBinaryString(file);
      reader.onload = function(e) {

          var data = e.target.result;
          var workbook = XLSX.read(data, {
              type : 'binary'
          });
          var result = {};
          var firstSheetName = workbook.SheetNames[0];
          //reading only first sheet data
          var jsonData = XLSX.utils.sheet_to_json(workbook.Sheets[firstSheetName]);
          //displaying the json result into HTML table
          displayJsonToHtmlTable(jsonData);
          }
      }catch(e){
          console.error(e);
      }
}

//Method to display the data in HTML Table
function displayJsonToHtmlTable(jsonData){
  var table=document.getElementById("display_excel_data");
  if(jsonData.length>0){
      var htmlData=''
      
      for(var i=0;i<jsonData.length;i++){
        
          var row=jsonData[i];
          var itemname = row["Item Name"] || '';
          var price = row["Price"] || '';
          var suppliers = row["Suppliers"] || '';

          
          htmlData+='<table class="table">'
           +'<tr><td class="itemname" colspan=3>'+itemname+'</td></tr>'
           +'<td class="price">'+price+'&nbsp;</td></tr>'
           +'<td class="price">'+suppliers+'&nbsp;</td></tr>'
           +'</table>';
      }
      table.innerHTML=htmlData;
      
  }else{
      table.innerHTML='There is no data in Excel';
  }
}
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.5/xlsx.min.js"></script>  

 

<h1>Upload an excel file to display in HTML Table</h1>
<!-- Input element to upload an excel file -->
<input type="file" id="file_upload" />
<button onclick="upload()">Upload</button>  
<br>
<br>
<!-- table to display the excel data -->

<p style="page-break-after: always;">&nbsp;</p>

<div id="display_excel_data"></div>


</body>
</head>
</html>

1. I was thinking something like If Cell[Price] is not blank but Cell[Item Name] is blank, then add this value to the nearest cell[Suppliers] above that has a nonblank Cell[Itemname]. And If Cell[Suppliers] is not blank but Cell[Item Name] is blank, then add this value to the nearest cell[Suppliers] above that has a nonblank Cell[Itemname]. But I am not sure if it will always work, And I don’t know how and where to syntax it in JAVA..

2. For each cell[Price] that is not blank, put it in a separate square box (like a table). But if there cell[Price] is empty (null or undefined or blank), then do not draw the square box.

3.Maybe we can loop for each row of col A value is not blank, to create a table and append all values below that row until the next col A row value is not blank? But how to modify the code?