Azure SDK Direct Line / Web chat

I want to use DirectLine/Webchat on my Website. Now I’m onto connecting the Bot, i made the GUI and its working fine but i can’t connect it. I’ll show my JS Code and my Controller (controller is trying to do the token inquiry, so JS can work with it)

JS:

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const botDiv = document.getElementById('bot-div');
        const botHeader = document.getElementById('bot-header');
        const webchat = document.getElementById('webchat');

        botHeader.addEventListener('click', toggleBotWindow);

        function toggleBotWindow() {
            const isCollapsed = botDiv.classList.toggle('collapsed');
            botDiv.setAttribute('aria-expanded', !isCollapsed);
            webchat.classList.toggle('hidden', isCollapsed)
        }

        async function fetchToken() {
            const response = await fetcher.postJson('/ChatBot/GetToken');
            const tokenData = await response.json();
            return tokenData.token;
        }
        
        async function inittalizeBot() {
            try {
                const token = fetchToken();
                window.WebChat.renderWebChat({
                    directLine: window.WebChat.createDirectLine({
                        token: token
                    }),
                    userID: 'YOUR_USER_ID', //optional
                    username: 'Web Chat User', //optional
                    locale: 'en-US'
                }, webchat);

                const styleSet = window.WebChat.createStyleSet({
                    rootHeight: '100%',
                    rootWidth: '50%',
                    backgroundColor: 'azure2'
                });
            } catch (error) {
                console.error('Fehler Erstellen des Bots', error);
            }
        }
        inittalizeBot();
    });
</script>
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;

namespace Web.Controllers
{
    public class ChatBotController : Controller
    {
        private readonly string directLineSecret = "Imagine my Secret here";

        [HttpPost]
        public async Task<JsonResult> GetToken()
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", directLineSecret);
                var response = await client.PostAsync("https://directline.botframework.com/v3/directline/tokens/generate", null);
                if (response.IsSuccessStatusCode)
                {
                    var tokenResponse = await response.Content.ReadAsStringAsync();
                    var token = JObject.Parse(tokenResponse)["token"].ToString();
                    return Json(new { token });
                }
                return Json(new { error = "Unable to generate token" });
            }
        }
    }
}

BOT GUI

I tried it multiple times with some other code but it won’t, maybe im just not seeing something?
If im doing the inquiry with my GIT Bash it work and gives me back a Token.
I want to get the same Token from my Controller. Maybe you see my mistake.

got `unknown` transaction error in transfering ton

I make a code on js with tonweb to generate ton wallet and transfer, just act like a tonkeeper wallet , but it’s only generate EQ instead of UQ and in transfering and sending it gaves unknown transaction error and didn’t complete the transaction

I used wallet.all.v4r2 but nothing changes

db.Collection Is Not a Constructor

I’m having this issue where I’m trying to create a leveling system in Discord using discord.js and MongoDB. Every time I try to upload my data to the database, I keep getting the error message

db.Collection is not a constructor

I’ve followed the instructions from How do I save a new data to MongoDB? post on saving new data to MongoDB, but I’m still getting the same error.

Here is my code that I’ve been working on:

async execute(message) {
  if (!message.inGuild() || message.author.bot) return;

  const XPToGive = getRandomXP(5, 15);

  const query = {
    userId: message.author.id,
    guildId: message.guild.id,
  };

  try {
    const level = await Level.findOne(query).then(async (level) => {
      if (!level) {
        const newLevel = new level({
          userId: message.author.id,
          guildId: message.guild.id,
          xp: XPToGive,
        });

        await newLevel.save();

        return;
      }

      level.xp += XPToGive;

      if (level.xp > getLevelXP(level.level)) {
        level.xp = 0;
        level.level += 1;

        message.channel.send(
          `@${message.member} have been leveled up to **Level ${level.level}**`,
        );
      }

      await level.save().catch((error) => {
        console.error(`[ERROR] ${error}`);
        return;
      });
    });
  } catch (error) {
    console.error(`[ERROR] ${error}`);
  }
}


I’m having trouble with using find() instead of findOne() in my code. It’s giving me more errors, and I really want my code to be error-free and able to save my data in the database.

How to output variable values from addeventlistener [duplicate]

let xc = null;
let yc = null;
var el = document.getElementById("canvas");

el.addEventListener('mousemove', function(f) {
  console.log('Coordinates: x=' + f.clientX + ' y=' + f.clientY);
  xc = f.clientX;
  yc = f.clientY;
  return xc;
  return yc;
})

console.log(xc, yc);

As a result, when you touch the screen, the coordinates are shown, but are not updated separately via console.log

Marker custom does not work correctly on the static map of Google Maps

I’m trying to create a static image to replace the dynamic map in Google Maps. I’m having problems when creating the image because the icon I’m using does not recognize it to generate the marker inside the map, in this case this image https://statics.radissonhotels.com/main/img/icons/markers/rdb.png , however if I use another image, like this https://cdn.sstatic.net/Sites/stackoverflow/img/favicon.ico, it generates the marker correctly.

I also have problems with the signature since it does not recognize my credentials, however, if I generate the image with this app https://staticmapmaker.com/google/, adding my api key and signature, it does not give error, except for the marker image. Any idea what could be happening?

I’m using vue.js 2

I changed the icon size to 48x64px and 2.83KB and it doesn’t work either.

What to do with a 504 Bad Gateway response from 3rd party API using Javascript?

I have a function that calls a 3rd party API (via the function checkPosition) which sometimes fails after a 30 second timeout.

I have the function in a try/catch block, but the 504 crashes the program.

try {
  // Check if position is still open
  if (!(await checkPosition(client, item.dealID))) {
    // If position has been manually closed
    console.log(`Position with period ${key} has been manually removed.`);
    continue;
  }
 
  await closePosition(client, item.epic, item.purchaseAmount, direction);
}
catch (err)
{
  console.error(err);
  res.redirect("/");
}

I tried to catch the 504 but this is not working for me.

Removing shapes in Google Maps with JavaScript

Namely, I’m working on an app that allows users to mark certain parts of the land on the map (by drawing shapes) and then get feedback information about the size of that land. Also, there is an option to exclude certain parts on the marked land (for example if there is a house and they don’t want to calculate it in the total results).

Now, the part where I got stuck is this: I’ve created X buttons that would allow the users to easily remove the whole shapes for the marked land (colored with black) or for the excluded parts (colored with red). Still, clicking on those X buttons triggers no action for some reason.

enter image description here

I believe that the cause lies in the functions, but I cannot confirm that. I can only forward the ones I’ve came up with that doesn’t work:

Here are the functions I’ve tried using for removing the land and exclusion shapes:

function removeLand(landIndex) {
    const land = areas[landIndex];
    // Remove the overlay from the map
    land.overlay.setMap(null);

    // Remove all exclusion overlays from the map
    land.exclusions.forEach(exclusion => exclusion.overlay.setMap(null));

    // Remove the land from the areas array
    areas.splice(landIndex, 1);

    // Update the display
    updateDisplay();
}

function removeExclusion(landIndex, exclusionIndex) {
    const exclusion = areas[landIndex].exclusions[exclusionIndex];
    // Remove the exclusion overlay from the map
    exclusion.overlay.setMap(null);

    // Remove the exclusion from the exclusions array
    areas[landIndex].exclusions.splice(exclusionIndex, 1);

    // Update the display
    updateDisplay();
}

Now, since I cannot guarantee that the issue lies in these functions, maybe it is in some other parts of my code, I will here share the GitHub page where I’ve updated the HTML and JS, and they are currently configured:
https://github.com/NoToolsNoCraft/Google-Map-Land-Size-Calculator/tree/main/Version%20with%20the%20X%20button%20not%20working

Material Table React – Apply To All and Apply To Group BY

I want to Apply, “Apply To All” and “Apply to GroupBy” for the rows I’m using with the use of Material UI.

  1. I want to create a button “Apply to All”. When the user Edit on a row and update all the columns and when we click on “Apply to All” it should apply to all the rows (ex: In the below code, I have two rows, it should update all the 2 rows)

  2. I want to create a button “Apply to Group”. When the user drag a column and get the grouped value (ex: I grouped by Name and it has only one row. When I click on Apply to Groupby it should update only one row)

I want to show one button at a time. If the user start drag, it should show only “Apply to Group” or by default it should show “Apply to All”

function ConditionalActions() {
  return (
    <MaterialTable
      title="Conditional Actions Preview"
      columns={[
        { title: 'Name', field: 'name' },
        { title: 'Surname', field: 'surname' },
        { title: 'Birth Year', field: 'birthYear', type: 'numeric' },
        {
          title: 'Birth Place',
          field: 'birthCity',
          lookup: { 34: 'İstanbul', 63: 'Şanlıurfa' },
        },
      ]}
       options={{
        grouping: true
      }}
      data={[
        { name: 'Mehmet', surname: 'Baran', birthYear: 1987, birthCity: 63 },
        { name: 'Zerya Betül', surname: 'Baran', birthYear: 2017, birthCity: 34 },
      ]}
      actions={[
        {
          icon: 'save',
          tooltip: 'Save User',
          onClick: (event, rowData) => alert("You saved " + rowData.name)
        },
        
        rowData => ({
          icon: 'delete',
          tooltip: 'Delete User',
          onClick: (event, rowData) => confirm("You want to delete " + rowData.name),
          disabled: rowData.birthYear < 2000
        })
      ]}
    />
  )
}

How do I use different config files for environment variables, ensuring that these files are distinct for development and production environments?

I’m currently developing a NestJS application and want to manage environment variables using different configuration files for development and production environments. I understand that it’s common practice to separate configurations to avoid accidentally exposing sensitive information or misconfiguring settings.

I would like to know the best approach to achieve this in a NestJS application. Specifically, I’m looking for guidance on:

How to create and structure separate configuration files (e.g., .env.development and .env.production).
How to load the appropriate configuration file based on the environment (e.g., using NODE_ENV).
Any recommended libraries or modules to facilitate this process (e.g., @nestjs/config).

Audio API Not Playing on Mobile Devices in Next.js Application

I’m working on a Next.js application that includes playing audio using the HTML5 Audio API. It works perfectly on desktop browsers, but I’m encountering issues when trying to play audio on mobile devices (both iOS and Android). The audio does not play, and there are no error messages in the console.

Here’s a simplified version of the code I’m using:

import { useEffect } from "react"

const AudioPlayer = () => {
  useEffect(() => {
    const audio = new Audio("/path/to/audio/file.mp3")
    audio.play().catch(error => {
      console.error("Error playing audio:", error)
    });
  }, []);
  return <div>Audio Player</div>
};

export default AudioPlayer

I’ve tried the following solutions without success:

  • Ensuring the audio file path is correct.
  • Testing different audio formats (MP3, WAV).
  • Using user interaction to trigger the audio play (e.g., button click).
  • Checking for mobile-specific restrictions or permissions.

Has anyone faced a similar issue or have any suggestions on how to resolve this?

Thanks in advance!

Cypress TypeError : Cannot read properties of undefined (reading ‘then’)

I have this function below :- checkStatusCode

I check if a response is OK then I try to return a value and based on that I try to visit the URL (ex:- if response status is 200)

  checkStatusCode(href) {
    cy.request({
      url: href,
      failOnStatusCode: false,
    }).then((response) => {
      expect(response.status).to.eq(200);
      return true;
    });
  }

This is how I call the function, but I am getting following Cypress error

Cannot read properties of undefined (reading ‘then’)

even if the assertion expect(response.status).to.eq(200) passes, what am I doing wrong here?

navigatetoHomepage(url) {
    this.checkStatusCode(url).then((isStatus200) => {
      if (isStatus200) {
        cy.visit(url);
      } else {
        cy.log("Fail");
      }
    });
  }