Flask Socketio with flask-sqlalchemy

I am having a hard time with flask_socketio. I want the messages added to the database simultaneously with realtime updating functionality. I have tried some ways but usually the post is successful and it gets added to database but the messages are not being updated and also I am unable to see messages existing in database which was previously working with for loop. Hope there are other and better ways and the problem in this one to be solved . I have the following code in my routes.py function:

@app.route('/<int:team_id>/<int:channel_id>/<string:channel_name>' , methods=["GET","POST"])
def channel(team_id,channel_id, channel_name):
    *Irrelevant code*
    form = MessageForm()
    if form.validate_on_submit():
        message = Messages(msg_cntnt=form.msg_cntnt.data,msg_file
        =form.picture.data, sender_id=current_user.id)
        emit('anounce message', {"msg_cntnt": form.msg_cntnt.data}, broadcast=True, 
        namespace='/1/2/Planning%20Team')
        db.session.add(message)
        db.session.commit()

    messages = Messages.query.filter_by(parent_channel=_channel_name).all()

return render_template('team.html', _channel=_channel, team=team, channels=channels,
team_members_count=team_members_count, form=form, messages=messages)

The namespace I have given is for a particular room, channel is there a way to dynamically give it? I have specified this in my route as I was unable to understand how to do it using @socketio.on(‘random’) having a database in which data is to be added. My jinja-html template

<form method="post" id="form">
        {{ form.hidden_tag() }}
            {% if *logic for error* %}
            {% else %}
            <div class="formInput">
                {{form.msg_cntnt(autocomplete="off", placeholder="Message", id="msg_cntnt")}}
                <span class="formInputHeading"></span>
                <span class="line"></span>
            </div>
            {{form.submit(id="send_msgBtn")}}
        </div>
    </form>
{% endif %}
            <h2>Send Message </h2>

            <div id="messages">
            {% for message in messages %}
                {% if current_user in _channel.channel_members['name'] %}
                        {{message.msg_cntnt}}
                        <small>{{message.msg_time.strftime('%H-%M-%S ,%d/%m/%Y')}}</small>
                {% else %}
            {% endif %}
            {% endfor %}

            </div>

My js file is below:

 var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
 socket.on('announce message', msg_cntnt => {
    const li = document.createElement('li');
    li.innerHTML = `${msg_cntnt}`
    const messages = document.getElementById('messages_')
    messages.append(li)
  })

I have also tried only li.innerHTML = msg_cntnt or changing this parameter with data and then data[‘selection’]. I hope there is also another way and this to be fixed. I have also tried the socket variable by chnaging it to var socket = io.connect('127.0.0.1:5000//1/2/Planning%20Team');
Regards

How can I include values in my javascript populated drop down list to include in a price calculator?

Here is my code sample:

    <script>
    const td=new Date();               // set Date object td to today
    const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
    td.setDate(td.getDate()+3)
    ndays = td - new Date();
    let deadline = td.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
    document.cookie = "ndays = " + ndays;
    offset = td.getTimezoneOffset();
    const opts=[...Array(18)].map(_=>{  // generate an Array of 7 (empty) elements
    let r=td.toLocaleString("en-us",{weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'}) + " @ "+deadline+" "+timezone+" Time ("+ Math.round(ndays/60/60/24/1000) + " days)"; // format date td
     td.setDate(td.getDate()+1);       // increment td by one calendar day
     ndays = td - new Date();
     return r                          // return date string to opts array 
      })
     </script>
    <select name="deadline" id="deadline" class="form-control" required="required">             
    <script>
    document.querySelector("select").innerHTML=opts.map(o=>`<option>${o}</option>`).join("") // make options
    </script>
    </select>

I need to be able to add incremented values based on the deadline selected to include in a pricing calculation. For example, if the order is 15 or more days out the price would be $10 per unit (a factor of 1). If it is 10 to 14 days, it would be $12 per unit (a factor of 1.2); 7 days, $13 per unit (a factor of 1.3); 5 days, $14 (a factor of 1.4); 3 days, $15 (a factor of 1.5).

Vuejs Router Link Not Opening Correct URL

My VueJS application has a router link that looks as follows – <router-link to="items/new">. When I enter the URL in the web browser (http://localhost:3000/items/new), the correct component is displayed. However, when that router link is clicked, the application redirects to http://localhost:3000/new instead, the component is not displayed, and the following error is displayed in the console –

[Vue Router warn]: No match found for location with path “items/new”

This is how my index.js file looks like –

[...]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    {
      path: '/items/:kind',
      component: Items
    }
  ]
})

[...]

I’m guessing this issue may have something to due with the history mode, but I haven’t been able to find any resource that deal with the specific occurrence I’m experiencing. I would appreciate any help, thank you in advance!

Is it possible to call event.stopPropagation after click in mapbox Geocoder?

Hi I am looking a way to stopPropagation on click event after I click on my geocoder component inside mapbox. I try it this way but it is not working. Only one event type which I found works is .on(‘result’ () => {…} ). Is there other way to achieve this ?? Thx.

  const geocoder = new MapboxGeocoder({
    accessToken: mapboxgl.accessToken,
    mapboxgl: mapboxgl,
    language: 'cs'
  });

  geocoder.on('click', (e: any) => {
    console.log('click'); // This never happen
    e.originalEvent.stopPropagation();
  });

  map.addControl(
    geocoder
  );

Firebase Auth takes too long to reflect on the page

I’m using firebase auth for a project to login the user using google.

I have two buttons, Login and Logout with conditional rendering so that only one button shows depending on if there’s a logged in user or not. Logout button functions okay, when clicked it signs out and switchs back to login button fast enough.

But when i press the login and sign in with my google account. The signin button still appears and dont switch to signout for about 5 seconds which is too long regarding UX.

How can I get rid of this problem, It was working fine but i remade the app and now it behaves like this.

index.vue:

<template>
  <div>
    <button @click="login" v-if="!isUserLoggedIn">
      Login
    </button>

    <button @click="logout" v-else>
      Logout
    </button>
  </div>
</template>

<script>
export default {
  computed: {
    isUserLoggedIn() {
      return this.$store.getters["isLoggedIn"];
    },
  },

  methods: {
    async login() {
      var provider = new this.$fireModule.auth.GoogleAuthProvider();
      let authData = await this.$fire.auth.signInWithRedirect(provider);
    },

    async logout() {
      await this.$fire.auth.signOut();
    },
  },
};
</script>

This is my store configuration

store/state.js:

export default () => ({
  authUser: null
})

store/actions.js:

export default {
  async nuxtServerInit({ dispatch }, { res }) {
    if (res && res.locals && res.locals.user) {
      const { allClaims: claims, ...authUser } = res.locals.user;

      await dispatch("onAuthStateChanged", {
        authUser,
        claims,
      });
    }
  },

  async onAuthStateChanged({ commit }, { authUser }) {
    if (!authUser) {
      commit("RESET_STORE");
      return;
    }

    if (authUser && authUser.getIdToken) {
      try {
        const idToken = await authUser.getIdToken(true);
        commit("SET_AUTH_USER", { authUser, idToken });
      } catch (e) {
        console.error(e);
      }
    } else {
      commit("SET_AUTH_USER", { authUser, undefined });
    }
  },
};

store/mutations.js:

import initialState from "./state";

export default {
  RESET_STORE: (state) => {
    Object.assign(state, initialState());
  },

  SET_AUTH_USER(state, { authUser, idToken }) {
    state.authUser = {
      displayName: authUser.displayName,
      photoURL: authUser.photoURL,
      email: authUser.email,
      id: authUser.uid,
      token: idToken,
    };
  },
};

store/getters.js:

export default {
  isLoggedIn: (state) => {
    if (state.authUser === null) {
      return false;
    } else {
      return true;
    }
  },

  user: (state) => {
    if (state.authUser === null) {
      return null;
    } else {
      return state.authUser;
    }
  },
};

Nodejs | Object property is available but it’s returning ‘undefined’

I’ve been trying to solve this for about 2 hours. I am returning an object in Nodejs. This object has 3 properties. I can access the first two, but when I try to access the third property, I get the ‘undefined’ warning. I’m about to go crazy can you help me please?

Object Result:

  category: [],
  _id: new ObjectId("6257233b897c3b8785ff625b"),
  mainCategories: [
    { id: 1000010100, name: 'Konut', subCategories: [Array] },
    { id: 1000010200, name: 'Devremülk', subCategories: [Array] },
    { id: 1000020100, name: 'İşyeri', subCategories: [Array] },
    { id: 1000020200, name: 'Arazi', subCategories: [Array] },
    {
      id: 1000020300,
      name: 'Turistik İşletme',
      subCategories: [Array]
    }
  ]
}

enter image description here

dygraphs values higher than 1000000 displayed as 1.00e+6. Is there any fix?

I have many sensors in home dashboard, one of them is the energy production, the values are grabbed from my MPP solar inverter, now the values are higher than 1 milion and unfortunately when I hover the mouse over the chart I see 1.04e+6 on any point.

Is there a setting I can change to force it to display numbers higher than 1000000?

function data_totalOutputEnergy() {
    return "" +
    "2022-06-05 08:54,1041020.00n"+"2022-06-05 08:55,1041020.00n"+"2022-06-05 08:55,1041020.00n"+"2022-06-05 20:53,1043330.00n"+"2022-06-05 20:53,1043330.00n"+"2022-06-05 20:53,1043330.00n"+"2022-06-05 20:53,1043330.00n"+"2022-06-05 20:54,1043330.00n"+"2022-06-05 20:54,1043330.00n"+"2022-06-05 20:54,1043330.00n"+"2022-06-05 20:54,1043330.00n"+"2022-06-05 20:54,1043330.00n"+"2022-06-05 20:54,1043330.00n"+"2022-06-05 20:54,1043330.00n"+"2022-06-05 20:54,1043330.00n"+"2022-06-05 20:54,1043330.00n"+"2022-06-05 20:54,1043330.00n" ;
    }



g_totalOutputEnergy = new Dygraph(document.getElementById("graph_totalOutputEnergy"),
        data_totalOutputEnergy,
        {
         labels: [ "Date", "High" ],
         labelsDiv: "labels_totalOutputEnergy",
         axisLineColor: "#ccc",
         fillGraph: true,
         valueRange: [0.00, 1043330.00],zoomCallback: function() {
                         g.updateOptions({valueRange:[0.00,1043330.00]});
                     },
         colors:
                [ "#EDA21F", "#008080", "#00BFFF", "#FFD700", "#FF69B42", "#20B2AA",
                 "#FF0000", "#FFFF00", "#FF1493", "#000080", "#00FF00", "#6B8E23", "#00FA9A",
                 "#B0C4DE", "#F0E68C", "#DAA520"],
        
        axes : {
            x : {
              drawGrid: show_box,
              drawAxis : true,
            },
            y : {
              
              gridLineColor: '#5f666d',
              drawAxis : true,
            }
        }   
             
                 /*,
        showRangeSelector: true,
        rangeSelectorHeight: 80*/        
        });

Returning value corresponding to a searched key in a deeply nested Javascript object

I have an object like below in Javascript,

const obj = {
      "group1": {
        "sub_group1_1": {
          "inner_sub_group1_1_1": {
            "name": "abc"
          },
          "inner_sub_group1_1_2": {
            "name": "def"
          }
        },
        "sub_group1_2": {
          "inner_sub_group1_2_1": {
            "name": "ghi"
          },
          "inner_sub_group1_2_2": {
            "name": "jkl" 
          }
        }
      },
      "group2": {
        "sub_group2_1": {
          "inner_sub_group2_1_1": {
            "name": "mno"
          },
          "inner_sub_group2_1_2": {
            "name": "pqr"
          }
        },
        "sub_group2_2": {
          "inner_sub_group2_2_1": {
            "name": "stu"
          },
          "inner_sub_group2_2_2": {
            "name": "wxy" 
          }
        }
      }
    }

I want to write a function which could search for a key in the above object and return me the corresponding value of that key, for e.g.,

Input

filterObject(obj, 'inner_sub_group2_2_2')

Output

{
   "name": "wxy
}

Input

filterObject(obj, 'inner_sub_group1_1_1')

Output

{
   "name": "abc
}

Approach

I have written a recursive function for the same, but it doesn’t seem to work for the second scenario,

  const filterObject = (obj, searchedKey) => {
    let result = {};
    for (const key in obj) {
      const currentObj = obj[key];
      if (key === searchedKey) {
        result = currentObj;
        break;
      } else if (typeof currentObj === 'object') {
        result = filterObject(currentObj, searchedKey);
      }
    }
    return result;
  };

Any sort of help would be highly appreciated. Thanks!

Chrome Extension: Focus on my search input field when user open a new tab

I am building a chrome extension that overrides the default new tab. I have a search input field on this new tab page that I want to focus this field on when a user opens a new tab. I have seen many answers, but none of them is satisfactory since they all have some URLs on the address bar. This extension Ocean Hero has managed to achieve this neat and clean.
One thing I notice with this extension is when we open a new tab, initially, the focus is on the address bar then after a blink, it goes to the below searchfield.

**one more thing, When I am adding autoFocus to the field it is not visible in the browser elements attributes.

Error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering

I am making a website using next.js and the above error is shown every time.

Don’t know what is wrong in my code

  const [userMsg, setUserMsg] = useState("");
  const [email, setEmail] = useState("");
  const router=useRouter();

  const handleOnChangeEmail = (e) => {
    e.preventDefault();
    setUserMsg("");
    console.log("event", e);
    const email = e.target.value;
    setEmail(email);
  };
  const handleLoginWithEmail = (e) => {
    e.preventDefault();
    if (email) {
      if (IsEmail.validate(email)){
        router.push("/")
        
      }else{
        setUserMsg("Enter a valid email address")
      }
      
    } else {
      //show usermssg
      setUserMsg("Enter an email address");
    }
  };
  return (
    <div className="bg-[url('/static/bglg.jpg')] flex items-stretch flex-col h-screen w-full">
      <head>
        <title>NeoVest SignIn</title>
      </head>
      <header className="text-4xl px-10 py-2 font-black">
        <span className="text-indigo-700">NeoVest</span>
      </header>
      <div className="w-full max-w-xs m-auto bg-[#C9C9C9] rounded p-5 bg-opacity-50 border-gray-200">
        <header>
          <div className="text-indigo-700 font-black text-3xl py-2">
            <p>Sign In</p>
          </div>
        </header>
        <form className="py-5">
          <div>
            <label className="block mb-2 text-indigo-500" for="username">
              Email
            </label>
            <input
              className="w-full p-2 mb-6 text-indigo-700 border-b-2 border-indigo-500 outline-none focus:bg-gray-300"
              type="text"
              name="username"
              placeholder="Email Address"
              onChange={handleOnChangeEmail}
            />
            <div className="block mb-2 text-red-700">
              <p>{userMsg}</p>
            </div>
          </div>
          <div>
            <input
              className="w-full bg-indigo-700 hover:bg-pink-700 text-white font-bold py-2 px-4 mb-6 rounded"
              type="button"
              value="Submit"
              onClick={handleLoginWithEmail}
            />
          </div>
        </form>
      </div>
    </div>
  );
};

Another error shown is due to some suspense boundary causing root to switch to client side rendering :

“Error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.”

I am also using tailwind if that information is important.

Website for plotting and displaying NEXRAD files

I have a simple question –

Does anybody know of a website or javascript framework that will allow one to upload a NEXRAD file, either level 2 (e.g. KCRP20210919_000249_V06) or level 3 (e.g. LWX_N0Q_2022_04_18_15_21_24), and it will give you a decoded image, or even better, plot that image on, say, a leaflet map?

Any suggestions would be awesome.

How make input RESET Button?

How make input RESET Button?

INFO:
Hi I’m trying to do that if I click on my input which has the ID search-input so that if I write something in the input then class cancel which is the cross that resets the value it’s like <button type =" reset "> so if I write something so that it appears to me sodisplay: block;and if I delete or input it won’t have a value to dodisplay: none;and I would like to do all this to make it work even if the user doesn’t have Javascript so I would like to do it in PHP version but I don’t know what I have so far I only have this code which shows the icon when something is in the input but unfortunately the code has stopped working and especially when I delete the input via the button so the icon doesn’t disappear for more information be sure not to be afraid to ask.

const input = document.getElementById("search-input")
const button = document.getElementById("cancel")
const icon = document.getElementById("icon")

input.addEventListener('keyup', test);
button.addEventListener("button", test)

function test() {
  let isShown = false

  if (input.value.trim() == "" || isShown == false) {
    icon.style.display = "none"
    isShown = true
  } else {
    icon.style.display = "flex"
  }
}

PS:

Everything was translated by Google translator if there was a mistake or you did not understand something write and I will definitely tell you how it should be thought in advance thank you very much for your help.

Swiper jumps to previously active slide on transitionEnd

I am trying to implement mouse drag module which would allow to transverse all the slides in swiper with single mouse drag equal to entire height of wrapper div (functionality similar to scrollbar but working no matter where you click). To do so I’ve implemented the following code:

function longDrag({ swiper, extendParams, on }) {
    let prevY = null;
    on('sliderMove', (swiper, e) => {
        if (!swiper.params.debugger) return;
        if (!prevY) prevY = e.clientY;
        if (prevY < e.clientY) {
            swiper.slideNext(0, false);
        }
        if (prevY > e.clientY) {
            swiper.slidePrev(0, false);
        }
        prevY = e.clientY;
    });
    on('slideChange', () => {
        if (!swiper.params.debugger) return;

        console.log(
        'slideChange',
         swiper.previousIndex,
         '->',
         swiper.activeIndex
         );
    });
}

When running the code the slideChange event fires indicating that active slide index changes, however in the browser slide does not change. In addition when mouse drag is finished the index of active slide returns to the first slide. I’ve tried modyfing some other events and it appears that this return to the first slide is caused by something just after transitionEnd event is emitted; adding

on('transitionEnd', (swiper) => {
    throw new Error("Not an error, just workaround")
  });

to longDrag function makes the script work as intended, however I do not think that this is the right way to do it.