Add MapBox map in a html video tag

I have a MapBox map object

<div class="#" id="map">
var map = new maplibregl.Map({
container: 'map',
style: 'https://api.maptiler.com/maps/hybrid/style.json?key=mykey'

});

I would like to add this map on a html video tag like this beautiful example https://www.matsim.org/gallery/paris.
I tried this without success

<video src="">
   <div class="#" id="map"></div>
</video>

Could you please help me if there exist a solution?

React hooks cause unintentional re-render

thanks for reading. I’m working with a React/Leaflet map and noticing the map container / elements re-render any time I show or close a modal. I’ve created a sandbox to demonstrate the problem but this occurs in other places throughout my app if additional examples would help.

https://codesandbox.io/s/elegant-rain-01f9l?file=/src/App.js

From reading alternative SO posts, such as this very similar one, I recognize this is likely caused by my hooks (ex. handleShow/setShow) which force the entire component to re-render. The unintended behavior is noticed as follows:

If you drag the map so that the current location is out of view and open a modal, we force the re-load of and . This is evident because the map re-pans to the current location, and a new ‘search icon’ appears in the top right on the map.

Steps to replicate:

*If you notice an issue in sandbox related to react-bootstrap/Modal, just update the dependency to latest (refresh icon) – this is a weird sandbox issue but unrelated to my question.

  1. Drag map so that current location is out of view
  2. Click menu icon (top right) > Add Location
  3. When modal appears, notice map re-centers to current location and another search icon appears.

I can’t download the pdf file with FileStreamResult when I call it from ajax

I am trying to call my FileStream Result function from an ajax, the question is that it is calling the method and it does everything inside, I checked this with a breakpoint, but at the end it is not downloading the pdf I want. Before it was downloading and it was calling it from
like this: “using (Html.BeginForm("EmisionAllLabel", "WareHouseReceipt", FormMethod.Post))“. But now I need to do it from an ajax but it doesn’t work for me. Maybe it’s because I’m missing something but I don’t have much experience with ajax regarding this and I can’t identify the problem. I appreciate your comments.
Attached are the codes used:

    $('#btnValidarEmision').on("click", function () {

        let emisionguia = $('#guiaAerea').val();
        $.ajax({
            url: "/WareHouseReceipt/" + "EmisionEtiqueta",
            type: "POST",
            data: { "guiaAerea": emisionguia },
            success: function (saved) {

            },
            error: function () {
                console.log("Error");
            }
        });
    });

FileStreamResult

public FileStreamResult EmisionEtiqueta(string guiaAerea)
{

    IList<ICriterion> criterionlist = new List<ICriterion>();
    criterionlist.Add(Expression.Eq("Econtainer", true));
    criterionlist.Add(Expression.Eq("StatusId", 1));
    criterionlist.Add(Expression.Eq("Emision", false));
    IList<VwWareHouseReceipt> etiquetas = vwWarehouseReceiptDao.findByCriteria(criterionlist);


    //mem buffer
    MemoryStream ms = new MemoryStream();



    //the document
    Document document = new Document(new Rectangle(float.Parse("289.50"), 370, 0, 0));

    BaseFont bf2 = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

    BaseFont helveticanormal = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, true);
    BaseFont helveticanegrita = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, true);

    //create the fonts
    BaseFont timesNormal = BaseFont.CreateFont(BaseFont.TIMES_ROMAN,
                                               BaseFont.CP1252,
                                               BaseFont.NOT_EMBEDDED);

    Font fontSmall = new Font(timesNormal, 7, Font.NORMAL);

    Font fontNormal = new Font(timesNormal, 9, Font.NORMAL);

    Font fontH1 = new Font(timesNormal, 16, Font.NORMAL);

    //the writer
    PdfWriter writer = PdfWriter.GetInstance(document, ms);//fs);

    // step 3: we open the document
    document.Open();

    for (int i = 0; i < etiquetas.Count; i++) { 
    

    }
    document.Close();

    //close the document
    // document.PageSize = PageSize.HALFLETTER;
    //document.PageSize = PageSize.

    //prepare output stream
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=EtiquetasEmisionEcont" + guiaAerea + ".pdf");
    Response.Buffer = true;
    Response.Clear();
    Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
    Response.OutputStream.Flush();
    Response.End();

    return new FileStreamResult(Response.OutputStream, "application/pdf");

Note: I deleted the “for” so that there would not be too much text.

Pass by reference – what is the better way to reassign the value of the property?

let spaceShip = {
   homePlanet : 'earth',
   color: 'black
}



//first way to reassign the value of the property
let reassign = obj => {
  obj.homePlanet = 'mars';
};
 
reassign(spaceShip);

//second way to reassign the value of the property
spaceship.homePlanet = 'mars'

What is the difference?? and What is the better way to do it??
Is both way changes the value permanantly??

How to redirect 404 page inside an axios service – nextjs

I’m using axios.
I want to check status when I got response of my api.
for example I want to redirect to 404 page.

const api = axios.create({
  headers: {
    common: {
      'Content-Type': 'application/json'
    },
    post: {

    }
  }
});
api.interceptors.response.use(
  ...

  (error) => {
const code = parseInt(error.response && error.response.status)
     if (code === 404) {
          console.log("responsive",error)
          if(data){
            data.forEach(itemError => {
              toast.error(itemError, {
                theme: 'colored',
              });
            });
          }else{
            //redirect to 404 page. but it doesn't work. 
            //return window.location.href = '/404';
          }
...

But I don’t know How I can to redirect inside of it.

POST a form in which some element are file

In a js web project,
I want to POST a form with a complexe json schema, and in which some field will be file.

How do I do It?

I currently upload a file alone like this

  const data = new FormData();
    data.append('mimetype', file.type);
    data.append('filename', file.name);
    data.append('file', file);
    return this.httpClient.post(url, data)

but I want my new form look like this:

 var data ={username:"John doe", 
    profilPhoto:{mimetype:..., filename:..., file: ...},
    house:{
       photo:{mimetype:..., filename:..., file: ...},
    },
    documents:[{mimetype:..., filename:..., file: ...}]

  }

How can I return the value of a key based on a different value in a dictionary (JavaScript)

    const array = [
  {
    username: "john",
    team: "red",
    score: 5,
    items: ["ball", "book", "pen"]
  },
  {
    username: "becky",
    team: "blue",
    score: 10,
    items: ["tape", "backpack", "pen"]
  },
  {
    username: "susy",
    team: "red",
    score: 55,
    items: ["ball", "eraser", "pen"]
  },
  {
    username: "tyson",
    team: "green",
    score: 1,
    items: ["book", "pen"]
  },

];

I have the above array. I have filtered the users that are in team red. Is there a way to return only the usernames of all users in team red instead of returning the whole data entry? So the output should be “[ John, Susy ]”. I have this code so far.

const filterArray = array.filter(user3 => {
  return user3.team === "red";
})

How to display all JSON objects with arrays on React JSX?

I only learned React 3 days ago. It’s very alien to me cos I come from a beginner’s PHP background.

I’m given a GitHub code that looks like below called NFTBalance.jsx which displays the JSON. It calls useNFTBalance.js which parses the JSON.

I wish to display the attributes each in a meta element like <Meta title={nft.name} description={nft.contract_type} />

I’ve been reading about this and more but I still failed to efficiently render the JSON attributes objects array.

I could do like NFT.type = data.attributes[0].value; but I find that’s very inefficient because I need to name each object and the attributes’ objects will change.

Could we use map function or something?

NFTBalance.jsx
...
 )}
        {NFTBalance &&
          NFTBalance.map((nft, index) => (
            <Card
              hoverable
              actions={[
                <Tooltip title="View On Blockexplorer">
                  <FileSearchOutlined
                    onClick={() =>
                      window.open(
                        `${getExplorer(chainId)}address/${nft.token_address}`,
                        "_blank"
                      )
                    }
                  />
                </Tooltip>,
                <Tooltip title="List NFT for sale">
                  <ShoppingCartOutlined onClick={() => handleSellClick(nft)} />
                </Tooltip>,
              ]}
              style={{ width: 300, border: "2px solid #e7eaf3" }}
              cover={
                <Image
                  preview={false}
                  src={nft?.image || "error"}
                  fallback="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAADDCAYAAADQvc6UAAABRWlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSSwoyGFhYGDIzSspCnJ3UoiIjFJgf8LAwSDCIMogwMCcmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis7PPOq3QdDFcvjV3jOD1boQVTPQrgSkktTgbSf4A4LbmgqISBgTEFyFYuLykAsTuAbJEioKOA7DkgdjqEvQHEToKwj4DVhAQ5A9k3gGyB5IxEoBmML4BsnSQk8XQkNtReEOBxcfXxUQg1Mjc0dyHgXNJBSWpFCYh2zi+oLMpMzyhRcASGUqqCZ16yno6CkYGRAQMDKMwhqj/fAIcloxgHQqxAjIHBEugw5sUIsSQpBobtQPdLciLEVJYzMPBHMDBsayhILEqEO4DxG0txmrERhM29nYGBddr//5/DGRjYNRkY/l7////39v///y4Dmn+LgeHANwDrkl1AuO+pmgAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAwqADAAQAAAABAAAAwwAAAAD9b/HnAAAHlklEQVR4Ae3dP3PTWBSGcb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kQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiEC/wGgKKC4YMA4TAAAAABJRU5ErkJggg=="
                  alt=""
                  style={{ height: "300px" }}
                />
              }
              key={index}
            >
              <Meta title={nft.name} description={nft.contract_type} />
...
...
export const useNFTBalance = (options) => {
  const { account } = useMoralisWeb3Api();
  const { chainId } = useMoralisDapp();
  const { resolveLink } = useIPFS();
  const [NFTBalance, setNFTBalance] = useState([]);
  const {
    fetch: getNFTBalance,
    data,
    error,
    isLoading,
  } = useMoralisWeb3ApiCall(account.getNFTs, { chain: chainId, ...options });
  const [fetchSuccess, setFetchSuccess] = useState(true);

  useEffect(() => {
    async function fetchData() {
      if (data?.result) {
        const NFTs = data.result;
        setFetchSuccess(true);
        for (let NFT of NFTs) {
          if (NFT?.metadata) {
            NFT.metadata = JSON.parse(NFT.metadata);
            NFT.image = resolveLink(NFT.metadata?.image);
          } else if (NFT?.token_uri) {
            try {
              await fetch(NFT.token_uri)
                .then((response) => response.json())
                .then((data) => {
                  NFT.image = resolveLink(data.image);
                  
                  {/*I think this is how I suppose to grab the JSON attributes object*/}
                  NFT.itemName = data.name;
                  NFT.description = data.description;
                  NFT.type = data.attributes;
                });
            } catch (error) {
              setFetchSuccess(false);
            }
          }
        }
        setNFTBalance(NFTs);
      }
    }
    fetchData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data]);

  return { getNFTBalance, NFTBalance, fetchSuccess, error, isLoading };
};

The JSON file is like this..

{
  "description": "Windsor my cat is found dead. An investigation is being carried out. My neighbor? A car? He goes up to heaven and we are saddened. By Guive Khosravi",
  "name": "The Incredible Windsor",
  "attributes": [
    {
      "trait_type": "Type",
      "value": "Acrylic, Spray paint on Linen"
    },
    {
      "trait_type": "Year",
      "value": "2020"
    },
    {
      "trait_type": "Style",
      "value": "Contemporary"
    },
    {
      "trait_type": "Location",
      "value": "Paris, France"
    }
  ]
}

JavaScript: How to grab thumbnail (first frame) of video with only raw byte data (mp4 and possibly other types)

I want to grab a thumbnail of a video (let’s say the thumbnail is at 0:00 of the video, so the first frame), however, I am streaming the video and want to display the thumbnail before the video fully loads (so fully loading it, saving it as a blob url and using the HTML5Video element isn’t an option).

Also, the URL that I am originally fetching the video from will not accept any more requests after I make the initial request to download the video, so I also can’t use the HTML5Video element to load that URL.

All I have access to are the raw bytes that are being streamed in from the response. So my question is how can I grab the first frame of the video when just enough bytes have loaded for it. Are there any tools for this, or will I have to interpret the file contents myself?

If I were to build my own solution, I assume the steps would be something like:

  • Wait for file metadata/headers to load first.
  • get the dimensions (x.y) of the video from the metadata.
  • the next x.y bytes will be the first frame of the video. Store this as an ArrayBuffer and create a data URL to use with an HTML img tag.

Let’s start with an mp4 solution but a solution to other formats would be appreciated as well, thanks in advance :).

Ojet uses encoded URL when params are used in router.go

When I use router.go in Ojet like below

self.args.router.go({ path: serverData.nextViewUrl, params: { c: serverData.sessionId } });

I get the following URL

?ojr=start_form%3Bc%3D63A4CC7E647582AF7E6C634B7FBF82F2

Above is the encoded URL. How do I get the correct decoded url by default in Ojet like below:

?ojr=start_form&c=D63A4CC7E647582AF7E6C634B7FBF82F2

Additional info:
Following is my router setup:

// Router setup
      let router = new CoreRouter(navData, {
        urlAdapter: new UrlParamAdapter()
      });
      router.sync();

      this.moduleAdapter = new ModuleRouterAdapter(router);

      this.selection = new KnockoutRouterAdapter(router);

      // Setup the navDataProvider with the routes, excluding the first redirected
      // route.
      this.navDataProvider = new ArrayDataProvider(navData.slice(1), { keyAttributes: "path" });

I am using the latest OJet v11

How to check if element has any attributes in it?

I’m trying to make a conditional checker check whether the element has any attributes or not.

var result = parentElm.hasAttribute(); i tried using this but I’m not sure I want a specific attribute by name, I just want to check whether the element has any attributes or attribute like length, size, or idk.

copyFormatCommand.js

    const model = this.editor.model;
    const selection = model.document.selection;
    const parentElm = selection.focus.parent;
    this.isEnabled = !!parentElm;
  

Here is the HTML I’m using to test if there are multiple nested elements and want to check whether the textNode‘s parent element has any attributes
HTML

<p style="font: 11pt Times New Roman, Times, Serif; margin: 0;" xvid="c0fc3b7176d15af5d8c5c488a7fa675e"><span xvid="6f8db94eb5824fc90d39a2d9a127a98d">Annual Fund Operating Expenses</span></p>
<p style="font: 11pt Times New Roman, Times, Serif; margin: 0;" xvid="c0fc3b7176d15af5d8c5c488a7fa675e">
    <span xvid="6f8db94eb5824fc90d39a2d9a127a98d"><span xvid="1">hello</span></span>
</p>
<p>hello</p>

how can i can fix my leaftlat map problems?

I have a div with id map for leatleft and its only show one tile of map
i really have problem to show full map
please help me

enter image description here

my css style is

#map {
        height: 350px;
        width: 100%;
    }

and my code is

var mymap = L.map('map').setView([35.7336466, 51.3458287], 12);

    L.tileLayer('https://b.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
        attribution: 'hello world',
        maxZoom: 18,
    }).addTo(mymap);

mymap.locate({
        setView: true,
        maxZoom: 12
    });

How do I check if object property is true/false and output based on true/false [closed]

I’ve been trying to figure this one out – if someone has some pointers I would appriciate it. Basically I got an object which has 3 properties, I need to check if one of those properties is true or false, and return based true/false.
So far, made this code but as I understand it doesn’t recognize object.properties..

const library = [
  {
    title: "Bill Gates",
    author: "The Road Ahead",
    isRead: true
  },
  {
    title: "Steve Jobs",
    author: "Walter Isaacson",
    isRead: true
  },
  {
    title: "Mockingjay: The Final Book of The Hunger Games",
    author: "Suzanne Collins",
    isRead: false
  }
];

const showStatus = (arg) => {
  let book = arg;
  for(let i = 0;i < book.length; i++){
    if(book.isRead === true){
       console.log(`Already read ${book.title} by ${book.author}.`)
    } else {
      console.log(`You still need to read ${book.title} by ${book.author}`)
    }

  }

};

showStatus(library);

Getting all the objects in the JavaScript from Django

I want to get all my object models from the database and store them in someway, the model I have is:

class Device (models.Model):
    patientId = models.IntegerField(unique=True)
    deviceId = models.CharField(unique=True,max_length=100)
    hour = models.DateTimeField()
    type = models.IntegerField()
    glucoseValue = models.IntegerField()

I’m sending them in views.py:

device_list = list(Device.objects.all())
context = {"filename": filename,
           "deviceList": device_list,
               }

In JS I managed to get each object like that:

{% for item in deviceList%}
console.log( "{{item}}" );
{% endfor %}

What I want is to store those objects in some way, but I don’t really know how, because they are coming like that Model object (1).