Reset Dropdown value before Submit

I have two dropdown list and both are selected with values and when i want to change the first dropdown i want to reset the second before submit, but it doesn’t works. He sends every time on post the second value who was selected before. I have no submit button, it is submitted on change on dropdown
Here’s my code :

<!-- First Dropdown -->
<select class="form-select mb-3" id="first" name="first" onsubmit="this.form.reset();" onchange="this.form.submit()">
    <option value="1" >Hello</option>
    <option value="2" >World</option>
</select>

<!-- Second Dropdown -->
<select class="form-select mb-3" id="second" name="second" onchange="this.form.submit()">
    <option value="1" >Hello</option>
    <option value="2" >World</option>
</select>

function reset() {
    $('#second').val("");
}
    

Any Idea?

using two database in mongoose

I want to use another db in mongoose so I have this:

const mongoose = require('mongoose');
const connectionOptions = { useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false };
const conn = mongoose.createConnection("mongodb://localhost/db_en", connectionOptions);

const Schema = mongoose.Schema;

const priceSchema = new Schema({

    fixed: {
        1: { type: Number, default: 199 }, 
        3: { type: Number, default: 499 }, 
        6: { type: Number, default: 729 },
        12: { type: Number, default: 999 }
    }
});

conn.model('Price', priceSchema);

Then I want to add data to the Price model in the new database:

const ggg = new conn.Price();

 await ggg.save(); 

But it returns this error everytime:

TypeError: conn.Price is not a constructor

JS slice and promise not waiting for response

I am implementing a translation app and the API is limited to 20 messages. Right now I have an array of infinite messages. I am using slice to create chunks of 20 messages and hit the api and then compiling the data.

async function callFun(mssgs) {
  var index = 0;
  const chunkSize = 20;
  for (let i = 0; i < mssgs.length; i += chunkSize) {
    const chunk = mssgs.slice(i, i + chunkSize);
    await new Promise(function (resolve, reject) {
      google.translateTextTest(
        chunk,
        current_user.language,
        (data) => {
          data = JSON.parse(data);
          //console.log(data);
          data.forEach(function (key) {
            var original_index = mssgs[index].index;
            console.log("original_index", original_index);
            chats[original_index].message =
              key.translations[0].text;
            index++;
            console.log("index", index);
            if (index == mssgs.length) {
              console.log(chats);
              return;
            }
          });
          resolve();
        }
      );

      setTimeout(() => {
        resolve();
      }, 5000);
    });
  }
}

The sample response can be seen below

{
    "translated_array": [
        {
            "detected_language": "en",
            "object_id": 1,
            "remarks": "",
            "text": "نعم"
        },
        {
            "detected_language": "en",
            "object_id": 2,
            "remarks": "",
            "text": "نعم"
        },
        {
            "detected_language": "en",
            "object_id": 3,
            "remarks": "",
            "text": "نعم"
        },
        {
            "detected_language": "en",
            "object_id": 4,
            "remarks": "",
            "text": "نعم"
        },
        {
            "detected_language": "en",
            "object_id": 5,
            "remarks": "",
            "text": "مرحبًا"
        },
        {
            "detected_language": "en",
            "object_id": 6,
            "remarks": "",
            "text": "مكالمة صوتية"
        },
        {
            "detected_language": "en",
            "object_id": 7,
            "remarks": "",
            "text": "مكالمة صوتية"
        },
        {
            "object_id": 8,
            "remarks": "couldn't detect the text language",
            "text": "f"
        },
        {
            "detected_language": "en",
            "object_id": 9,
            "remarks": "",
            "text": "جيج"
        },
        {
            "detected_language": "da",
            "object_id": 10,
            "remarks": "da is not supported",
            "text": "fdfd"
        },
        {
            "detected_language": "en",
            "object_id": 11,
            "remarks": "",
            "text": "من؟"
        },
        {
            "detected_language": "en",
            "object_id": 12,
            "remarks": "",
            "text": "ملاحظة اختبار"
        },
        {
            "detected_language": "en",
            "object_id": 13,
            "remarks": "",
            "text": "حصلت على جميع رسائلك س"
        },
        {
            "detected_language": "en",
            "object_id": 14,
            "remarks": "",
            "text": "مكالمة صوتية"
        },
        {
            "detected_language": "ms",
            "object_id": 15,
            "remarks": "ms is not supported",
            "text": "Yyu"
        },
        {
            "detected_language": "en",
            "object_id": 16,
            "remarks": "",
            "text": "حسنًا ، شكرًا"
        },
        {
            "object_id": 17,
            "remarks": "couldn't detect the text language",
            "text": "C"
        },
        {
            "object_id": 18,
            "remarks": "couldn't detect the text language",
            "text": "4"
        },
        {
            "detected_language": "en",
            "object_id": 19,
            "remarks": "",
            "text": "أهلاً"
        },
        {
            "detected_language": "en",
            "object_id": 20,
            "remarks": "",
            "text": "مرحبًا"
        }
    ],
    "response_code": 100,
    "remarks": "Success",
    "time": "2023-05-15 7:27:6",
    "characterCountBalance": "Unlimited"
}

The issue is that I get response of only 20 messages. Some times, it returns the other data as well but mostly it is just returning me 20 messages and I am not able to get the rest of the data. Is that any other approach that I can take?

Arrow functions behaviour inside promises

Q1.) Why I am getting undefined if i pass console.log in then block in a promise chian?

new Promise((resolve, reject) => {
  console.log(4)
  resolve(5)
  console.log(6)
}).then(() => console.log(7))
.catch(() => console.log(8))
.then(() => console.log(9))
.catch(() => console.log(10))
.then(() => console.log(11))
.then(console.log)
.finally(() => console.log(12))

Output:

4
6
7
9
11
undefined
12

Q2.) However if I pass console.log in then block using arrow function, i get nothing as output wrt that then block.

new Promise((resolve, reject) => {
  console.log(4)
  resolve(5)
  console.log(6)
}).then(() => console.log(7))
.catch(() => console.log(8))
.then(() => console.log(9))
.catch(() => console.log(10))
.then(() => console.log(11))
.then(()=>console.log)
.finally(() => console.log(12))

Output:
4
6
7
9
11
12

Can anyone explain this behaviour?

I am just curious to understand this behaviour of our beloved JS.

React Native Expo – the splash image does not update on both Android and Ios

I was trying to update the image of the splash screen.

This is what my app.json looks like.

{
  "expo": {
    "name": "My App",
    "slug": "react-native-app",
    "version": "1.18.0",
    "icon": "./assets/images/app-icon.png",
    "assetBundlePatterns": ["**/*"],
    "splash": {
      "image": "./assets/images/splash.png",
      "resizeMode": "contain",
    }
  },
}

My first step is to replace the splash.png with the new one, which is also called splash.png.

I have checked it works correctly in Simulator for both Android and Ios.
However, after building in App Centre, I download the app and find that below issue happens.

Android: It still uses the previous image
Ios: There is NO Splash Image.

I have no idea how to start debugging. Can anyone share experience for that?

jQuery change event fires once [closed]

I have an HTML form and I am using jquery that is supposed to fire every time I select from a drop-down list in the form (the id of the drop-down list is ABC). Depending on the selection, a text box is going to be enabled/disabled. But, the change event is firing just once. what is the problem?

$(document).ready(function(){
    $('#abc').on('change',function(){ 
        console.log($('#abc').val()) ;
        if($('#abc').val() == "22") {
            $("#tarikheRejectionId").prop('disabled', false);
        } else {
            $("#tarikheRejectionId").prop('disabled', true);
        }
    });
});
<form>
    <select id="abc">
        <option>11</option>
        <option>22</option>
        <option>33</option>
        <option>44</option>
        <option>55</option>
    </select>
    <input type="button" id="tarikheRejectionId" value="tarikheRejectionId">
</form>

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

Angular – Canvas not redrawing shapes on resizing it

I have an Angular application where I use canvas that I can resize based on the user selection. Now, when I resize my canvas size in the form, the canvas correctly changes size but everything on it disappears, I understand that the canvas clears itself. But then I call a method called redraw which tries to draw those shapes in the canvas again, but it does not.

When I change a coordinates for a element in the canvas, here also I call that redraw method and all shapes again reappears. Can someone please help me resole this issue.

Here is video showing the issue.

enter image description here

ngOnInit(): void {
        console.log('ngOnInit');
        const canvas: HTMLCanvasElement = this.myCanvas.nativeElement;
        this.context = canvas.getContext('2d');
        this.form = this.formBuilder.group({
            labelName: ['', Validators.required],
            labelOrientation: ['VERTICAL', Validators.required],
            labelWidth: [, Validators.required],
            labelHeight: [, Validators.required],
            barcodeLeft: [, Validators.required],
            barcodeTop: [, Validators.required],
            barcodeWidth: [,],
            barcodeHeight: [,],
            gtinLeft: [, Validators.required],
            gtinTop: [, Validators.required],
            gtinWidth: [,],
            gtinHeight: [,],
        });

        this.form.setValue(this.verticalOrientationData);
        this.objSerialLabelDesignModel = this.form.value;
        if (this.context) {
            console.log('ngOnInit check this.context', this.context);
            this.redrawLabel(this.objSerialLabelDesignModel);
        }
        this.onChanges();
    }

    ngAfterViewInit() {
        console.log('ngAfterViewInit');
        this.startDrawing(this.shapesToDrawArray);
    }

    onChanges(): void {
        console.log('onChange!!!!!!');
        // Subscribe to changes in the form value to redraw the label when it changes
        this.form.valueChanges.subscribe((newVal) => {
            this.objSerialLabelDesignModel = newVal;
            this.redrawLabel(this.objSerialLabelDesignModel);
        });
    }

    redrawLabel(result: ISerialLabelDesign) {
        console.log('inside redrawLabel');    
        this.clearDrawing();
        console.log(this.shapesToDrawArray.length);
        this.shapesToDrawArray.length = 0;
        console.log('result::::::::', result); // giving the entire form.value object
        this.defaultLabelWidth = result.labelWidth * 3.7795; // convert from mm to pixel
        this.defaultLabelHeight = result.labelHeight * 3.7795;            
        this.storeDrawing(result);          
        this.startDrawing(this.shapesToDrawArray);
    }

    startDrawing(shapesToDraw: Shape[]) {
        console.log('inside startDrawing::');
        for (var i = 0; i < shapesToDraw.length; i++) {
            const shape = shapesToDraw[i];
            if (shape.type === 'barcode') {
                this.drawRectangle(this.context, shape.x, shape.y, shape.w, shape.h);
            } else if (shape.type === 'text') {
                this.drawText(this.context, shape);
            }
        }
    }

showing TypeError: Cannot read properties of undefined (reading ‘tryPointToLocation’) while adding BingMap (bingmaps-react v^1.2.10) in Nexjs v13

I for last many days I have been trying to add BingMap (bingmaps-react v^1.2.10) in Nexjs v13, But I am constantly getting the error ‘TypeError: Cannot read properties of undefined (reading ‘tryPointToLocation’)’ at location let infobox = await new Microsoft.Maps.Infobox(map.getCenter(), {

Can any one help please?

Thank
enter image description here

const map = await new Microsoft.Maps.Map(this.mapRef.current, {})
    const pushpinClicked = (e: any) => {
      if (e.target.metadata) {
        infobox.setOptions({
          location: e.target.getLocation(),
          title: e.target.metadata.title,
          description: e.target.metadata.description,
          visible: true,
        })
      }
    }

    console.log('map', map);
    
    let infobox = await new Microsoft.Maps.Infobox(map.getCenter(), {
      visible: false,
    })

    //Assign the infobox to a map instance.
    infobox.setMap(map)

I expect the BingMap to appear on the page

Google Apis Drive push notification not working

I’m using google service account for the push notification to get in my console so I can handle it afterwards ,I’ve set up the credentials, put a watch on my drive root folder and watching any changes happens on my ngrok url which is https url of localhost 3000 but the problem is after I run the program it showed me that it has successfully put a watch but I’m not getting any notification even though I have made changes (uploaded some images)

this is my code for the reference

// googlpis set up 

const { google } = require("googleapis")
const { v4: uuidv4 } = require("uuid")
const path = require("path")
const credentials = path.resolve(__dirname, "../googleKey.json")

const auth = new google.auth.GoogleAuth({
    keyFile: credentials,
    scopes: ["https://www.googleapis.com/auth/drive"]
})
const drive = google.drive({ version: "v3", auth })

//watch on my drive 


async function setUpPushNotification() {
    const response = await drive.files.watch({
        fileId: "root",
        requestBody: {
            id: uuidv4(),
            type: "web_hook",
            address: "https://0642-202-189-239-146.ngrok-free.app/",
            payload: true
        }
    })

    console.log("Push notification channel set up:", response.data)
}


//console log 

Push notification channel set up: {
  kind: 'api#channel',
  id: '57adb753-5ccb-4782-83b3-82532e1e147a',
  resourceId: 'qHo857F_9Dp6NQ-zRAwcxdiGkw4-js',
  resourceUri: 'https://www.googleapis.com/drive/v3/files/root?alt=json&null',
  expiration: '1684133269000'
}

I have tried going through all the document related drive watch but not found any good solution even chat gpt does not able to resolve this problem.
I have tried to use different api for example create file api to upload something on drive and I successfully able to upload a image on my folder, so the set up is correct.

I’m expecting a response when I upload images on my drive, I should able to get the details like which image is uploaded when, where , by who etc.

ultimately I have to get that image which is uploaded and again upload it on my AWS account, but from the document It seems I cannot get the the image directly through notification so I have to run another api to get the image

If checkbox is checked, check another box

I’m trying to create a few checkboxes that when checked, will check another… which I got to work! But, the problem I’m having now is that if multiple are selected and one is unchecked at any point, the additional checkbox get unchecked no matter what. I’d like to find a way to have the additional checkbox stay checked, as long as one of the others is, and uncheck if none are selected.

For example: I have 4 checkboxes, if a user selects #1 I want to check #2. Or if a user selects #1 + #3, check #2, but if #3 is unchecked, #2 stays as long as 1,3, or 4 are. I hope this makes sense. I’ve been trying different things, but this is the code where I landed. Any help, advice on a better way to accomplish this would be greatly appreciated.

var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
var chk3 = $("input[type='checkbox'][value='3']");
var chk4 = $("input[type='checkbox'][value='4']");

chk1.on('change', function(){
  chk2.prop('checked',this.checked);
});
chk3.on('change', function(){
  chk2.prop('checked',this.checked);
});
chk4.on('change', function(){
  chk2.prop('checked',this.checked);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="1" class="user_name">1
<br>
<input type="checkbox" value="2" class="user_name">2
<br>
<input type="checkbox" value="3" class="user_name">3
<br>
<input type="checkbox" value="4" class="user_name">4

CouchDB: JavaScript Fetch API Fails To Connects Due To CORS on localhost

Using Chrome browser I navigate to 127.0.0.1:5984 and get response from couchdb server.

When I call the same address using Chrome’s JavaScript it fails:

Access to fetch at 'http://localhost:5984/' from origin 'http://localhost:8080' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

The local.ini file on the couchdb box has:

[chttpd]
enable_cors = true
[cors]
origins = *
credentials = true
methods = GET, POST, PUT, DELETE, OPTIONS, HEAD, TRACE, PATCH
headers = accept, authorization, content-type, origin, referer, cache-control, x-requested-with, X-Couch-Id, X-Couch-Rev

My fetch options currently have:

{
  "headers": {
    "Content-Type": "application/json",
    "method": "GET",
    "credentials": "include",
    "mode": "cors"
  }
}

Change value of ng-model from popup windows

I have input that generates dynamically by ng-repeat. for setting the value the user should click on the button and the popup windows will open. After selecting the value, the user will click on confirm button and I set the value by this code:

function SetLatLng() {
        if (!window.opener || window.opener.closed) {
          
            return;
        }

        var txtLat = window.opener.document.getElementById(latId);
        var txtLng = window.opener.document.getElementById(lngId);

     
        var lat = document.getElementById('latitude').value;
        var lng = document.getElementById('longitude').value;

        if (txtLat) {             
            window.opener.angular.element(txtLat).$rootScope().$apply(function () {
                window.opener.angular.element(txtLat).controller('ngModel').$setViewValue(lat);
            });
        }

        if (txtLng) {
            // Update the value of the ng-model attached to txtLng
            window.opener.angular.element(txtLng).$rootScope().$apply(function () {
                window.opener.angular.element(txtLng).controller('ngModel').$setViewValue(lng);
            });
        }

        window.close();
    }

The value of input visibly changes but the ng-model does not change. I also write a directive but it doesn’t work either.

myapp.directive('setNgModelFromValue', function () {

return {
    restrict: 'A',
    require: '?ngModel',
    link: function (scope, element, attrs, ngModel) {
       
        if (!ngModel) return;
       
        ngModel.$parsers.push(function (value) {
           
            ngModel.$setViewValue(value);
            ngModel.$render();
            return value;
        });

        ngModel.$formatters.push(function (value) {
           
            ngModel.$setViewValue(value);
            ngModel.$render();
            return value;
        });

        element.on('input', function () {
          
            scope.$apply(function () {
                var value = element.val();
                ngModel.$setViewValue(value);
                ngModel.$render();
            });
        });
    }
};

});

I don’t why It’s not working. I also use scope.$apply() instead of $rootScope().$apply but still not working.

How to let values as it is when conditionally rendering from one component to another

I am condinitionally rendering two componenets with the same route. First components has two input field and one next button. After pressing the next button I am rendering to the next page.
But when clicking on the back button how can I get the that I have entered earlier. I am using useRef() but when I am coming to the first page again then all the data that I have entered are not present.
So how can I set the data as it is while I am conditionally rendering between two components

I have tried with the useRef() but the entered values are not there when I am pressing the back button and reaching to that first component again.

How to compare between values in two diffrent JSON array

const fruits = [{id: '1', name: 'Apple'},
{id: '2', name: 'Orange'},
{id: '3', name: 'Cherry'}];

const food=[{id: '1', food_name: 'Orange', deleted="0"},
{id: '2', food_name: 'Bread' ,deleted="0"},
{id: '3', food_name: 'Cheese', deleted="0"},
{id: '4', food_name: 'Apple', deleted="1"},
{id: '5', food_name: 'Salt',deleted="0"}
]
//Code that I tried:
var foodSet = new Set(food.map(item => item.food_name));
for(var j=0; j < fruits.length; j++){
    if(!foodSet.has(fruits[j].name) && fruits[j].deleted!=1){
        dep_data.push({id: fruits[j].id, name: fruits[j].name});
    }
}
console.log(dep_data)

I want to compare between two arrays to get the id and name of the fruits that not exists in the food and deleted not equal to 1 then save the results in new array.

For example here we have the Orange exist in the food array, the results should store the id and name of fruits that doesn’t exist in food and deleted !=1. (orange).