flask-socketio join room working only only with the first user

Im learning to use socketio with flask(sorry for the horrible code)
and im trying to create a private chat for a social network but when i try to join a room only the first person joins it and the seccond one doesn’t

Server code

from flask import Blueprint, redirect, render_template, request, flash, session, url_for
import sqlite3
from . import socketio
from flask_socketio import join_room, leave_room, emit, send

chat = Blueprint("chat", __name__)

@chat.route("/joinchat", methods=["POST", "GET"])
def joinchat():
    if request.method == "POST":
        name = request.form.get("name")

        con = sqlite3.connect("DB.db")
        cur = con.cursor()
        cur.execute("SELECT id FROM users WHERE username = ?", (name,))
        id = cur.fetchone()
        if id:
            id = id[0]
            con.close()

            return redirect("/chat/" + str(id))
        else:
            con.close()
            flash("There is no user with that username", category="error")

    return render_template("select_chat.html")

@chat.route("/chat/<int:id>")
def chats(id):
    
    return render_template("chat.html")

@socketio.on("mesage")
def handlemesage(mesage, url):
    print(mesage, url)
    socketio.emit("postmesage", mesage, to=url)

@socketio.on("connect1")
def connect1(id):
    print(id, type(id))
    join_room(id)
    emit("connectinter", id, broadcast=True)
    

@socketio.on("connect2")
def connect2(id):
    if session["id"] == int(id):
        print(id, type(id))
        join_room(id)
        emit('redirect', "/chat/" + str(id))

Client js

    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>

<script>
    var socket = io();
    
    $("#send").on("click", function (){
        console.log(document.getElementById('inputmesage').value);
        socket.emit("mesage", document.getElementById('inputmesage').value, window.location.href.split("/").pop());
    });

    $("#connect").on("click", function (){
        socket.emit("connect1", window.location.href.split("/").pop());
    });

    socket.on("connectinter", function (id) {
        console.log(id);
        socket.emit("connect2", id);
    });

    socket.on('redirect', function (url) {
        window.location = url;
    });

    socket.on("postmesage", function (mesage) {
        console.log(mesage)
    });
</script>

html

<div class="row">
        <div class="col-sm-10">
            <input id="inputmesage" class="form-control" type="text">
        </div>
        <div class="col-sm-2" id="send">
            <button type="submit" class="btn btn-outline-warning btn-block align-middle">Send</button>
        </div>
    </div>
    <button id="connect" type="submit" class="btn btn-outline-warning btn-block align-middle">Connect</button>

only the person who clicked the connect button gets joned to the room(connect1)

Unrecognized parameter to $filter: limit MongoDB-Mongoose

I have the following error on my console:: Invalid $project :: caused by :: Unrecognized parameter to $filter: limit

The irony of this is that the documentation tells us that it exists and can be used.

This is my code

const docWorker = await _worker.aggregate([
    {
      $project: {
        credencial: {
          $cond: {
            if: {
              $eq: [{ $size: "$identificacionObra" }, 0],
            },
            then: false,
            else: {
              $cond: {
                if: {
                  $gte: [
                    {
                      $size: {
                        $filter: {
                          input: "$identificacionObra",
                          cond: {
                            $eq: ["$$credencial.estado", true],
                          },
                          as: "credencial",
                          limit: 1,  <--------- the limit parameter does not work
                        },
                      },
                    },
                    1,
                  ],
                },
                then: true,
                else: false,
              },
            },
          },
        },
      },
    },
    { $match: _match },
    { $sort: _sort },
    {
      $facet: {
        paginatedResults: [
          { $skip: req.query.page * req.query.limit - req.query.limit },
          { $limit: parseInt(req.query.limit) },
        ],
        totalCount: [
          {
            $count: "count",
          },
        ],
      },
    },
  ]);

Please help me, what did I do wrong?

How to Display Selected gif in react js?

I am stuck with a problem , I don’t know how to do it. I want to display selected gifs , when I search its work properly , when I click on any gifs only this gifs is selected and display when I click on post button..

In This problem if anyone have any query please free feel to ask

App.js

This is the App.js file only single file I wrote my all code.

import "./App.css";
import { useEffect, useState } from "react";
import Axios from 'axios';

function App() {

const Api_key="QlYtlejKAxArXXXXXXXXXXXXXXXXX";
const Base_Url = "http://api.giphy.com/v1/gifs/search";

const [searchText,setSearchText] = useState("");
const [searchGif,setSearchGif] = useState("");

const [addText,setAddText] = useState([]);
const [gifs,setGifs] = useState([]);


const postValue = ()=>{

  const addData = {
    id:Date.now(),
    name:searchText
  }
  console.log(addData);
  setAddText([...addText,addData])
  setSearchText("");

  // Add Gifs
  gifResponse();
 
}

const gifResponse = async()=>{
  const response = await Axios.get(`${Base_Url}?api_key=${Api_key}&q=${searchGif}`)
    //  const res = await response.json();
    setGifs(response.data.data);
   console.log(response.data.data)
 }

  return (
    <div className="App">
      <div className="container">
        <textarea
          type="text"
          className="form-control shadow-none mt-3"
          rows="15"
          cols="50"
          placeholder="Write Something Here..."
          value={searchText}
          onChange={(e)=>setSearchText(e.target.value)}
        />
        <div class="input-group mb-3 mt-2">
          <input
            type="text"
            class="form-control shadow-none"
            placeholder="Search Gif..."
            aria-label="Recipient's username"
            aria-describedby="basic-addon2"
            value={searchGif}
            onChange={(e)=>setSearchGif(e.target.value)}
          />
          <div class="input-group-append">
            <span class="input-group-text" id="basic-addon2" onClick={postValue}>
              POST
            </span>
          </div>
        </div>
        {
          addText.map((add,index)=>{
            return <h4 key={index}>{add.name}</h4>
          })
        }
        {
          gifs.map((gif)=>{
            return <img src={gif.images.fixed_height.url} />
          })
        }
      </div>
    </div>
  );
}

export default App;

Hide Custom Cursor on mobile

I have the following code for a custom cursor. I am trying to hide the cursor on mobile, but I don’t know which code I need to use and where I need to paste it. Can someone help me? Thank you!

<div class="cursor__ball cursor__ball--small">
    <svg height="10" width="10">
      <circle cx="5" cy="5" r="4" stroke-width="0"></circle>
    </svg>
  </div>
</div>
<style>
 
  body .cursor {
  pointer-events: none;
}
body .cursor__ball {
  position: fixed;
  top: 0;
  left: 0;
  mix-blend-mode: difference;
  z-index: 1000;
}
body .cursor__ball circle {
  fill: #f7f8fa;
    }}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.3/TweenMax.min.js"></script>
<script>
const $bigBall = document.querySelector('.cursor__ball--big');
const $smallBall = document.querySelector('.cursor__ball--small');
const $hoverables = document.querySelectorAll('a');

// Listeners
document.body.addEventListener('mousemove', onMouseMove);
for (let i = 0; i < $hoverables.length; i++) {if (window.CP.shouldStopExecution(0)) break;
  $hoverables[i].addEventListener('mouseenter', onMouseHover);
  $hoverables[i].addEventListener('mouseleave', onMouseHoverOut);
}

// Move the cursor
window.CP.exitedLoop(0);function onMouseMove(e) {
  TweenMax.to($bigBall, .4, {
    x: e.clientX - 15,
    y: e.clientY - 15 });

  TweenMax.to($smallBall, .1, {
    x: e.clientX - 5,
    y: e.clientY - 7 });

}

// Hover an element
function onMouseHover() {
  TweenMax.to($bigBall, .3, {
    scale: 4 });

}
function onMouseHoverOut() {
  TweenMax.to($bigBall, .3, {
    scale: 1 });

}
</script>

Tried to add @media, but didn’t know where to paste is.

Can’t specify exact date when retrieving Facebook request dates

https://m.facebook.com/friends/center/requests/outgoing/#friends_center_main
enter image description here

Hello, I am coding a chrome extension that will cancel friend requests sent on Facebook after a certain date. The problem is that Facebook writes the request dates in minutes, days, months, years etc. It is not possible to detect them perfectly on the plugin.

<abbr data-store="{&quot;time&quot;:1642405814,&quot;short&quot;:true,&quot;forceseconds&quot;:false}" data-sigil="timestamp" data-store-id="0">3 ay</abbr>

The dates are given as attributes in json format as below, but I could not find how to process this date.
{“time”:1642405814,”short”:true,”forceseconds”:false}

console.log(new Date(1642405814))

If I want to use new date directly as above, the year is 1970, but the request was sent a few months ago. It is outputting the wrong date.

 console.log(new Date(Date.now() - new Date(1642405814)))

Although I converted it as above, it shows that it is 1 month, but 3 months have passed since the request. I can’t figure out how to set this date. Can you please help?

My Website jitters when scrolling, whilst using the “onScroll” function to resize the header and Nav Bar

Hey everyone,

I am working on a small school project website, and I wanna make my header and nav bar change when scrolling past a certain point.

So far so good, I managed to do that. However there is a point where the website starts to freak out and switches very fast between the two states I set, as can be seen here:

Furthermore, the speed of the scroll slows down significantly upon reaching the point of change/where it freaks out, though I’d assume that simply is due to the function being called upon to many times.

As can be seen in the code, I tried adding some kind of cooldown on the function, this didnt really work (I did try it in a few more ways then the one currently in the code).

Ill be using the header as the code example, as Header and nav bar freak out in the same way.

HTML

<header id="header">
            <div>
                <h1 class="invisible">----</h1>
            </div>
</header>

CSS

header{
    background-color: #227C9D;
    position: sticky;
    top: 0;
    z-index: 2;
    height: 100px;
    transition: 0.2s;
}

JavaScript

var header;
var nav;
var delay = 800;
var lastChange = 0;

function scrollFunction() {
  header = document.getElementById("header");
  nav = document.getElementById("nav");
  

  if (document.body.scrollTop > 50 ) {
    if (lastChange >= (Date.now())) return;
    header.style.height = "50px";
    nav.style.fontSize = "20px";
    
  } else {
    if (lastChange >= (Date.now())) return;
    header.style.height = "100px";
    nav.style.fontSize = "40px";
    
  }
  lastChange = Date.now();



}

Full Code: https://github.com/DefenetlyNotSimon/InfoWebsiteProjekt/blob/beta/styles.css

If anyone has any ideas or solutions, I’d appreciate it 😀

The provided `as` value is incompatible with the `href` value error in next.js

I have three pages

  1. home/start which navigates to
  2. home/users/[type] which navigates to
  3. home/settings/[type].

home/start

import { useRouter } from 'next/router';
const Start = () => {
  const router = useRouter();
  return (
    <>
      <button
        onClick={() => {
          router.push('/home/users/native');
        }}
      >
        GO
      </button>
    </>
  );
};

export default Start;

home/users/[type]

import { useRouter } from 'next/router';

const User = () => {
  const router = useRouter();
  return (
    <>
      <button
        onClick={() => {
          router.push('/home/settings/subscription');
        }}
      >
        Go Again
      </button>
    </>
  );
};

export default User;

home/settings/type

const Settings = () => {
  return <div>Confirm docs</div>;
};

export default Settings;

I navigate from home/start to /home/users/native by clicking on the button, then to /home/settings/subscription.Then, I click on the back button to go back to home/users/native.Now, when I click on forward button to get to home/settings/subscription, I get the following error

Error: The provided as value (/home/settings/subscription) is incompatible with the href value (/[type]).

I am not using as anywhere.Can someone point out as to what I am doing wrong?

Geo Locate component in Leaflet React v3 – unwanted duplication on each refresh

I’m currently using Leaflet in React (v3) where you need to add components in order to render them on the map. This is the unwanted result output I am getting (green circles are duplicates and don’t work on click either):
Map Render Image

This keeps duplicating on each map interaction. I am not sure how to fix it and presume it is the library that is the issue as no other components replicate this behavior. If it can’t be fixed, an alternative is welcome – as long it is compatible with leaflet-react v3.
In short: – prevent duplicates on each map render. Geo locate user with permision in browser (on the first load, and then if the user pans away manually, to relocate/flyto with a button click)

import { useMap } from "react-leaflet";
import Locate from "leaflet.locatecontrol";
import "leaflet.locatecontrol/dist/L.Control.Locate.min.css";
import * as L from "leaflet";

const UserLocate = () => {
  const map = useMap();

  var lc = L.control
    .locate({
      position: "topright",
      strings: {
        title: "Show me where I am, yo!",
      },
    })
    .addTo(map);
  return null;
};

export default UserLocate;

/====================================================/

import EsriLeafletGeoSearch from "react-esri-leaflet/plugins/EsriLeafletGeoSearch";
import {
  MapContainer,
  Marker,
  TileLayer,
  Popup,
  ZoomControl,
  LayersControl,
  useMapEvents,
  useMapEvent,
  useMap,
} from "react-leaflet";

    import { Container, Button, Form, Row, Nav } from "react-bootstrap";
    import "leaflet/dist/leaflet.css";
    import "esri-leaflet-geocoder/dist/esri-leaflet-geocoder.css";
    import L from "leaflet";
    import { BiMapPin } from "react-icons/bi";
    import UserLocate from "./ProfilePage/UserLocate";


function GeneralMap() {
  const defaultZoom = 14;
        <MapContainer
          center={[48.856614, 2.3522219]}
          zoom={defaultZoom}
          style={{ height: 400, width: "100%" }}
        >
          <LayersControl>
            <BaseLayer checked name="Standard">
              <TileLayer
                attribution='"<a href="https://www.jawg.io" target="_blank">&copy; Jawg</a> - <a href="https://www.openstreetmap.org" target="_blank">&copy; OpenStreetMap</a>&nbsp;contributors"'
                url="https://{s}.tile.jawg.io/jawg-streets/{z}/{x}/{y}{r}.png?access-token="
              />
            </BaseLayer>
            <BaseLayer name="Black and White">
              <TileLayer
                attribution='"<a href="https://www.jawg.io" target="_blank">&copy; Jawg</a> - <a href="https://www.openstreetmap.org" target="_blank">&copy; OpenStreetMap</a>&nbsp;contributors"'
                url="https://{s}.tile.jawg.io/jawg-light/{z}/{x}/{y}{r}.png?access-token="
              />
            </BaseLayer>
          </LayersControl>
             <EsriLeafletGeoSearch
            position="topleft"
            useMapBounds={false}
            eventHandlers={{
              requeststart: () => console.log("Started request..."),
              requestend: () => console.log("Ended request..."),
              results: (r) => console.log(r),
            }}
          />
          <UserLocate />
        </MapContainer>

  );
}

export default GeneralMap;

JavaScript: Parse data in object and convert it to array of items

This topic will be a continuation of this thread: Format object with some keys to array

The problem is more complex and I tried to match the current solutions, unfortunately without success.

It receives from the database this format:

const response = [
  {
    short: 'en',
    value: 'John Smith',
    path: [
      'person',
      'add-22da-da-8c93-dae11e',
      'firstname'
    ]
  },
  {
    short: 'en',
    value: {
      '29ca6xx-5200-3d45-aad2-2da4dddadad': {
        name: 'Marianna',
        content: 'Person 1',
      },
      '66fdsfdsf-da22-ada-rrd-uuid21131': { name: 'Josh' },
      'rr433d-a21d-aaadd-uuid-sas333dd': {
        name: 'Elizabeth',
        otherkey: 'Seventy',
      },
      'uuid21e1-dda-da2211-dad2-gfhfyfyf': {
        data: {
          0: { name: 'Adrian' },
        },
      },
    },
    path: [ 'items', '*' ]
  },
];

And I have to parse it in such a way to get exactly that result:

[
  {
    short: 'en',
    value: 'John Smith',
    path: 'person.add-22da-da-8c93-dae11e.firstname'
  },
  {
    short: 'en',
    value: 'Marianna',
    path: 'items.29ca6xx-5200-3d45-aad2-2da4dddadad.name'
  },
  {
    short: 'en',
    value: 'Person 1',
    path: 'items.29ca6xx-5200-3d45-aad2-2da4dddadad.content'
  },
  {
    short: 'en',
    value: 'Josh',
    path: 'items.66fdsfdsf-da22-ada-rrd-uuid21131.name'
  },
  {
    short: 'en',
    value: 'Elizabeth',
    path: 'items.rr433d-a21d-aaadd-uuid-sas333dd.name'
  },
  {
    short: 'en',
    value: 'Seventy',
    path: 'items.rr433d-a21d-aaadd-uuid-sas333dd.otherkey'
  },
  {
    short: 'en',
    value: 'Adrian',
    path: 'items.uuid21e1-dda-da2211-dad2-gfhfyfyf.data.0.name'
  }
]

This is such a difficult parser to write that it’s not really clear how many subkeys there are of this object and how nested it is. In any case, I always have to get the result in the format I wrote above.

I’ve tried a great many combinations of map, object.keys, for loop functions but I just give up.

JavaScript Set a Bit at position 0 in the last byte of a Buffer/Uint8Array

I am trying to replicate the following Java code in JavaScript that will set a Bit in a byte[].

The Java Class has two private method functions to set a bit and check if a bit is set.

    private boolean isBitSet(byte b, int pos) {
        byte test = 0;
        return (setBit(test, pos) & b) > 0;
    }

    private byte setBit(byte b, int pos) {
        return (byte) (b | (1 << pos));
    }

The byte[] payload has a length of 80 with the last 13 empty and setBit is called on the last byte as follows:

payload[79] = setBit(payload[79], 0);

The whole payload is then Base58check encoded

The JavaScript looks like this:

const payload = new Uint8Array(80);// Buffer.alloc(80, 0) for node
payload[79] = setBit(payload[79], 0)

What I have tried:

Setting it to 128 (0b10000000) but I realised that would be the last Bit.

Setting it to 1 (0b00000001)

Setting it to 2, 4, 8, 16, 32, 64.

Setting using bitwise and assignment operators from this answer: payload[79] |= 1 << 0

Using an online Java to JS converter:
const setBit = (byte, pos) => ((byte | (1 << pos)) | 0);

How I know none of these worked:

After running both payloads through a (definitely equivalent) base58check.encode function, only the last few characters are different, representing the last byte and the checksum.

Other help I have sought:

I have asked for help from the Java code developer and was told regarding signed/unsigned that “We treat the values as unsigned. Java doesn’t have unsigned byte so the values are integers cast to bytes : val = (byte)0xFF (for example). You might have to check on the endianness in your implementation. Java uses big endian as the default.” What I understand about endians is that it is about the order that bytes are written to memory and so I thought that it wouldn’t matter for a single Byte.

Question:

Please help me to find a solution? I would like to understand where I went wrong.

Thanks

Resize a span highlighting a word to include multiple words of a text by dragging the span element

I want to resize the size of a span by dragging its border following the text characters.

Here’s an image to better understand:
enter image description here

I leave a stackblitz using React: https://stackblitz.com/edit/react-qvvqfe?file=src/App.js

As I said I’m using React, but a solution using Javascript alone it’s fine.

Here’s what I tried:

since I know the offset of the mention in the text like so:

{
   startPos: 5,
   endPos: 10
}

I just changed the mention positions to make the span larger and rerendered the document content. I’m doing this using an onClick event because I’m kind of lost when including the drag part.

Google Maps Api – when is map.panto(latlng) smooth

Can someone please explain in pseudocode, or at least less ambiguous language, the API Refence Manual definition for smooth transition requirements of the panTo() method: –

panTo panTo(latLng)
Parameters: latLng: LatLng|LatLngLiteral The
new center latitude/longitude of the map.
Return Value: None
Changes the center of the map to the given LatLng. If the change is less
than both the width and height of the map, the transition will be smoothly
animated.

Specifically, what is “the change” in this context?

Example: –

Zoom Level = 6
LatLng1 = lat: -31.9523, lng: 115.8613 Pixel X = 13464 Pixel Y = 9728
LatLng2 = lat: -33.8688, lng: 151.2093 Pixel X = 15073 Pixel Y = 9831
Current Map Center is LatLng1 and panning to LatLng2
I make the "change" to be horizontal 1609px and vertical 103px

If the map’s DIV container is at least 616px wide and 344px high the pan is smooth if not it jumps.

Can someone please help me heuristicly marry up those figures with an algoithm?

Pentaho version 7.1 community edition fails to load the scripting engine for ECMAScript. How do I resolve the issue?

I downloaded Pentaho CE 7.1 so that I can modify some reports but when I try to test them I get the error: Failed to locate scripting engine for language ‘ECMAScript’. The global scripting is written in ECMAScript that is why I need the ECMAScript Engine. If someone can help convert to this to groovy that would also help.

function init(dataRow){  
    var tenantUrl = dataRow.get("tenantUrl");
    var user = dataRow.get("username");
    var password = dataRow.get("password");
    dataFactory.getConnectionProvider().setProperty("user", user);
    dataFactory.getConnectionProvider().setProperty("password", password);
    dataFactory.getConnectionProvider().setUrl(tenantUrl);
 }