Get JSON from URL, return array and count instances

I’m trying to map the JSON from the URL to an array but I think my mapping of the data isn’t correct. I want to find every value inside of attributes and count how many instances of each value there are in the JSON file/ array.

[
  {
    name: "1",
    attributes: [
      {
        trait_type: "hat",
        value: "blue"
      },
      {
        trait_type: "hair",
        value: "red"
      }
    ]
  } 
];

$.getJSON(
  "https://jsonware.com/api/v1/json/3c53cbcd-5351-4fba-8b89-5f1fb009e857",
  function (data) {
    var items = $.map(data.attributes, function (i) {
      return i.value;
      const result = data.reduce(
        (acc, curr) => ((acc[curr] = (acc[curr] || 0) + 1), acc),
        {}
      );
      console.log(result);
      console.log(items);
    });
  }
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

ASP.NET Web Form Page in new window opened via javascript window.open()

I’ve an ASP.NET page already published, and I open it from a third party application widget using a script window.open().

The script is working fine and also the page, but my problem is when I stay for a while not doing anything (for example 5 min) on the opened window the page stopped working, I tried to click a link button in that page but it’s not working. Then I close the window and open it again then everything goes fine.

This problem makes many issues for me because it should affect on the third party system.

I think maybe there is some period of time for that window but I cannot catch the problem.

Is there any solution for this case ?

NOTE: The link button should hide an asp panel and show another one in code behind.

CKeditor Uncaught TypeError: Cannot read properties of undefined (reading ‘p_Ack’)?

I want to send data to the database with Ckeditor, but I get the error “Cannot read properties of undefined (reading ‘p_Ack’)”. The editor I’m using is ckeditor’s document bundle editor where exactly am I going wrong?

<div class="card card-custom">
<div class="card-body">
<div id="kt-ckeditor-3-toolbar"></div>
<div id="p_Ack">
</div>
</div>
</div>
<script>

var KTCkeditorDocument = function () {
   var demos = function () {
       DecoupledEditor
         .create(document.querySelector('#p_Ack'))
         .then(editor => {
 const toolbarContainer = document.querySelector('#kt-ckeditor-3-toolbar');
 toolbarContainer.appendChild(editor.ui.view.toolbar.element);
})
 }

 return {
 // public functions
     init: function () {
     demos();
     }
 };
        }();
        // Initialization
        jQuery(document).ready(function () {
            KTCkeditorDocument.init();
        });
</script>
'Desc': KTCkeditorDocument.instances['p_Ack'].getData(),

JavaScript – begginner questions

I have some difficulties with my first number guessing “game” in JavaScript. Can someone have a look and guide me what I did wrong? Started with that language not that long ago..

Function is assigned to one button

<input id="box;" class="btn" ; type="button" value="Guess" onClick="check()">Click to start !

User (player) have to press the button, guess the number (1-10) within 3 attemps and then play again or not. Every attemp I do it says “number is higher” but at the end result is random, even if you chose 10.

var hiddenNum;
var attemps;

hiddenNum = Math.floor(Math.random() * 10);
hiddenNum = hiddenNum + 1;
attemps = 0;


    function check(guess) {
        window.prompt("Please enter the number between 1 and 10", "10");

        if (hiddenNum == guess) {
            window.alert("Congratulations! You guessed correctly !");

            again = window.prompt("Would you like to try again? Enter Y or N.", "Y");

            if (again == "N" || again == "n") {
                window.alert("Thanks for trying. Goodbye.");
                window.close();
            } else {
                window.alert("The number has been randomized.");
                window.location.reload();
            }

        } else {
            attemps = attemps + 1;

            if (hiddenNum < guess) {
                result = "lower";
            } else {
                result = "higher";
            }

            window.alert("Guess number " + attemps + " is incorrect. The number is " + result + ".");

        }

        if (attemps >= 3) {
            window.alert("Sorry, you have run out of guesses! The number was " + hiddenNum);

            again = window.prompt("Would you like to try again? Enter Y or N.", "Y");

            if (again == "N" || again == "n") {
                window.alert("Thanks for trying. Goodbye.");
                window.close();
            } else {
                window.alert("The number has been randomized.");
                window.location.reload();
            }

        }

    }

How to eval an upload script result

I have this code where I upload several images at once and it does the multiple upload like a prophecy but the only problem is that the output is not “evaled” or does not execute any javascript. So for example on the output page if I do

<script> alert('Yes'); </script>

Nothing happens after the upload. Here is the code for multiple upload

<script>
 
 
 
        var handleUpload_afile = function(event){
              event.preventDefault();
              event.stopPropagation();
        
          var fileInput = document.getElementById('afile');
          var data = new FormData();
        
          for(var i = 0; i < fileInput.files.length; ++i)
          {
             data.append('afile[]',fileInput.files[i]);
          }
         
          
          
                if (window.XMLHttpRequest) 
                {
                    // code for modern browsers
                    xhr_afile = new XMLHttpRequest();
                } 
                else 
                {
                    // code for old IE browsers
                    xhr_afile = new ActiveXObject("Microsoft.XMLHTTP");
                } 
          
           
          
              xhr_afile.upload.addEventListener('progress',function(event){
           
               if(event.lengthComputable)
               {
            
                  var percent = event.loaded / event.total;
                  var progress = document.getElementById('upload_progress_afile');
            
                        while (progress.hasChildNodes())
                        {
                               progress.removeChild(progress.firstChild);
                        }
                        
                     
               }
           
        });
        
                    xhr_afile.upload.addEventListener('load',function(event)
                    {
                    /*
                    document.getElementById('upload_progress_afile').style.display = 'none';
                    */
                    });
                    
                    xhr_afile.upload.addEventListener('error',function(event)
                    {
                    
                    alert("failed");
        
                    });
        
        
                   xhr_afile.open('POST','upload_multiple_article_gallery_travail.php');
                   
                   
                   xhr_afile.setRequestHeader('Cache-Control','no-cache');
                    
                   
                   xhr_afile.upload.onprogress = function(e) 
                  {
                    if (e.lengthComputable) 
                    {
                      var percentComplete = (e.loaded / e.total) * 100;
                       
                      document.getElementById("upload_progress_afile").innerHTML="<img src='images/facebook_style_loader.gif'  width='16' height='11'> <br>" + (Math.round(percentComplete)-1) + ' % uploding'; 
                       
                    }
                  };
                   
                   
                   xhr_afile.onload = function() 
                  {
                        if (this.status == 200) 
                        {
                            
                            
                                if (document.getElementById)
                                {   
                     
                                document.getElementById("upload_progress_afile").innerHTML=xhr_afile.responseText;
                                
                                }
                            
                         
                          
                        }
                  };
         
                    
                   xhr_afile.send(data);
         
                   
        };

 
 

//We submit the form as soon as the file changes
  var uplodons = document.getElementById('afile');
           uplodons.addEventListener('change',handleUpload_afile);
       
</script>

On the page upload_multiple_article_gallery_travail.php I need to be able to call and execute javascript but it does not work. So how to eval the output after upload so the javascript on the page upload_multiple_article_gallery_travail.php will be executed ?

Disabling text selection popup menu without disabling selection altogether

I’m developing a custom e-reader app. I would like to make a custom highlighting menu, but I’m having trouble disabling the “Copy/Paste/Share” menu that pops up when text is selected on mobile devices. As far as I have researched, it seems impossible to disable without disabling selection altogether. But I wonder if by chance anyone has found a workaround.

I am aware of user-select: none which disables all selection. This is not desirable for me because I will need to access the javascript selection API for saving highlights, among other things.

Thanks!

How to redirect in NextJs

I am building an app in NextJS which uses Firebase authentication. After successful authentication, I then wish to fetch additional details about the customer stored within a mongodb instance (or create a new document for the customer on first login). Because I cannot access the firebase auth object inside getServerSideProps, I have to wrap the dashboard in another component which initiates the firebase auth, then redirects to dashboard passing the user.uid as a parameter to fetch customized/dynamic content inside getServerSideProps. I have created a dashboard.js, and then a dashboard/[id].js.

dashboard.js

export default function DashboardAuth(props) {
  
  const [user, loading, error] = useAuthState(firebase.auth())

  if (user){
    return window.location.href = `/dashboard/${user.uid}`
  }else{
    return <SignIn/>
  }
    
  }

/dashboard/[id].js


export async function getServerSideProps({ params }) {

    let userData 
    console.log("Logging in ")
    const { db } = await connectToDatabase();
    console.log("connected to database, awaiting query response with uid")
    const findUserResp = await db
      .collection("users")
      .findOne({'uid': params.id})
    
    if(findUserResp ){
      console.log("user data exists")
      userData = {
        uid: findUserResp.uid,
        email: findUserResp.email,
        displayName: findUserResp.displayName,
        photoURL: findUserResp.photoURL,
        storageQuoteRemaining: findUserResp.storageQuoteRemaining,
        emailVerified: findUserResp.emailVerified,
        currentPage: '/dashboard'
      }
    }else{
        console.log("user data does not exist") 
        userData = {
            uid:params.id,
            email: '',
            displayName: '',
            photoURL: '',
            storageQuoteRemaining: 0,
            emailVerified: false,
            currentPage: '/dashboard'
        }
        const addUserResp = await db
            .collection("users")
            .insertOne(userData)

    }
    console.log("returning userdata below")
    console.log(userData)
    return {
      props: {
        userData
      }
    }
}


export default function Dashboard(props) {
  
  const [user, loading, error] = useAuthState(firebase.auth())
  const userContext = getUserContext()
  useEffect(() => {
    userContext.handleCurrentUser(props.userData)
    }, []);
  if (user && props.userData.uid === user.uid){
    return  <Layout  children={<CreateItem/>}/>
  }else{
    return <SignIn/>
  }
    
  }

My main issue is that after the user is initially added to mongodb on first login, immediatley after redirect to [id].js, I am presented with an error

Error: Error serializing `.userData._id` returned from `getServerSideProps` in "/dashboard/[id]".
Reason: `object` ("[object Object]") cannot be serialized as JSON. Please only return JSON serializable data types.

but on refresh this disappears.

Also I don’t like how I have written my redirect but useRouter does not work. Any advice on how to better do this would be appreciated.

convert flat data to nested object using slug

I have a flatten data like this that has slug property and I have to convert it to a nested object based on this field:

[
    {
        "id": "e4679a79-48b6-5783-a42f-e4b5a1a4a206",
        "slug": "root/01-topic",
        "frontmatter": {
            "title": "Topic 1"
        }
    },
    {
        "id": "b6cd27c5-8786-5f3f-ae60-7dffcb002d6c",
        "slug": "root/02-topic",
        "frontmatter": {
            "title": "Topic 2"
        }
    },
    {
        "id": "eca8b1c5-30a8-54e3-a3e9-7c482ae9d450",
        "slug": "root/01-section/01-topic",
        "frontmatter": {
            "title": "Topic 1"
        }
    },
    {
        "id": "7bb24e88-8e54-5722-93f1-185bf0f1dd6c",
        "slug": "root/01-section/01-subsection/01-topic",
        "frontmatter": {
            "title": "Topic 1"
        }
    },
    {
        "id": "e93bf045-1798-54d2-a2bc-d5a2eb12a49d",
        "slug": "root/01-section/01-subsection/02-topic",
        "frontmatter": {
            "title": "Topic 2"
        }
    },
    {
        "id": "3ac918f1-31af-501e-bc98-37b33d2bccbd",
        "slug": "root/02-section/01-subsection/01-topic",
        "frontmatter": {
            "title": "Topic 3"
        }
    },
    {
        "id": "1c9021a2-d346-57b8-9586-a48e7e3eb54f",
        "slug": "root/02-section/01-title",
        "frontmatter": {
            "title": "Subsection 1"
        }
    },
   
    ]

and I want to convert it to a new structure that has cildrens so I can render them on the screen to users

[
  { id: "", slug: "root/topic-01", title: "Topic 1" },
  { id: "", slug: "root/topic-02", title: "Topic 2" },
  {
    id: "",
    slug: "root/section-01",
    title: "Topic 2",
    children: [
      { id: "", slug: "root/section-01/topic-01", title: "Topic 1" },
      {
        id: "",
        slug: "root/section-01/subsection-01",
        title: "Topic 1",
        children: [
          {
            id: "",
            slug: "root/section-01/subsection-01/topic-01",
            title: "Topic 1",
          },
        ],
      },
    ],
  },
];

I think that I need to use recursive and having a root node and childrens to it but do not know how to it exactly

can anyone help?

youtube block from an hour to an hour

I Have a problem.
My YouTube is available from an hour to an hour an then i cant even open he website.
i think its a sw.js problem, but i dont think so.

I’m asking if its repairable with a JSI (JavaScript Injection) or simply change some of the setting while i can use YouTube.

Before You Ask;

  1. My WiFi Its ok
  2. I’m not that guy that dont know how to startup a computer

About the Number 2, you can use technical language.

Can i have some help?
Thanks

adding instruction points to a route line using leaflet.js

i use leaflet.js to show a route in my web project. I have mastered everything successfully, except that I cannot display instruction points on the route.

i used the following code to show the Route on the map:

api.getRoute(routingLink).then(res =>{
    const routeLayer = L.geoJSON(res.data.features,{}).addTo(layerGroup) //shows route on the map 
})

my question is how can i add instruction points to the route that shows the instruction in popup on clicking it.

here a screenshot from the route:
shows the route between to places but not the instructions

Three.js – How to pre-position objects to merge?

I’ve successfully merged my cubes, although they seem to merge together reverting back to their original position/rotation, ignoring the declared positioning/rotation

var geometries = [];

cube1.position.set( 0, 0, 0 );
geometries.push( cube1 );

cube2.position.set( 1, 0, 0 );
geometries.push( cube2 );

cube3.position.set( 0, 1, 0 );
geometries.push( cube3 );

const cubes = BufferGeometryUtils.mergeBufferGeometries( geometries );

scene.add( cubes );//All the cubes get merged on 0, 0, 0 - overlapping one another

How do I position the cubes so they can be merged in their declared positions?

MathJax – Supporting $ $ delimeters within HTML – Canvas

I am able to add DOM elements to HTML canvas via the code.

<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="//code.createjs.com/createjs-2013.09.25.combined.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!----------------------------- Start Game ------------------->

<style>
#gameCanvas {
  background-color: lightyellow;
}
</style>
<div class="canvasHolder1">
  <div id="eqn1"> $3+3=$<input type="text" id="q1j" />
    </div>
  <div id="eqn2"> 3+2=<input type="text" id="q2j" />
    </div>
  <div id="eqn3"> 5+2=<input type="text" id="q3j" />
    </div>
  <canvas id="gameCanvas" width="600" height="600">Not supported</canvas>
<script type="text/javascript">
var m=1;
var quest=[];
quest[m]= document.getElementById(`q${m}j`);

  var values = [];
  var stage = new createjs.Stage("gameCanvas");
  var obj=[];
  can = document.getElementById("gameCanvas");
function response(){
    alert("New Question");
    document.getElementById(`eqn${m}`).remove();
    m=m+1;
    
    quest[m] = document.getElementById(`q${m}j`);
    quest[m].addEventListener("keyup", enterFunction);
    values[m] = document.getElementById(`q${m}j`);
    obj[m] = new createjs.DOMElement(document.getElementById(`eqn${m}`));
    obj[m].x = Math.random()*can.width;
    obj[m].y = 0.5;
    stage.addChild(obj[m]);
}
function startGame() {  
    quest[m].addEventListener("keyup", enterFunction);
    values[m] = document.getElementById(`q${m}j`);
    obj[m] = new createjs.DOMElement(document.getElementById(`eqn${m}`));
    obj[m].x = Math.random()*can.width;
    obj[m].y = 0.5;
    stage.addChild(obj[m]);
    createjs.Ticker.addEventListener("tick", handleTick);
    createjs.Ticker.setFPS(2);
    function handleTick(event){
    drop(m);
    stage.update();
    }
}
 function drop(i){
      obj[i].x += 1;
      obj[i].y +=3;
 }
 function enterFunction(){
  if (event.keyCode === 13 ) {
   document.getElementById("myBtn").click();
   }
 }
</script>
<body onload="startGame();">
    <div >
  <canvas>This browser or document mode doesn't support canvas object.</canvas>
    </div>
</body>
<button id="myBtn" onclick="response()">New Question</button>
</html>

When I teach math, I typically make a worksheet where the delimeters are set to $ $ (i.e. single dollar signs around math equations (see question of the post here). I also attached the code to change the delimeters accordingly below.

<script>
MathJax = {
  tex: {
    inlineMath: [['$', '$'], ['\(', '\)']]
  }
};
</script>
<script id="MathJax-script" async
  src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js">
</script>

Placing the delimeters inside, e.g. the $3+3$ part, messes up the code to the point where it does not work. I do not know if it is jquery or something that isn’t allowing it, but I would really any help to get the $ $ delimeters to respond within div elements in canvas by adding the tiny bit of code above to canvas. I can get them to work if the delimeters are like this (3+3) but I do not want that.

Allowing only one person to create blog entries on the site [closed]

I have created a website for a photographer that has a blog page on the site. I want only that photographer to have permission to create blog entries to the site. Do I need to make a user login that checks if that user (the photographer) has logged into the site and then allow posts to the blog using JavaScript? Do I need backend languages to make this happen (I only am familiar with frontend technology)? Just looking to be pointed in the correct direction.

How retrieve element from 1-dimensional array?

There is an array 8×8:

var tiles: [
    1, 3, 3, 3, 1, 1, 3, 1,
    1, 1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 2, 1, 1,
    1, 1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 2, 1, 1, 1, 1,
    1, 1, 1, 1, 2, 1, 1, 1,
    1, 1, 1, 1, 2, 1, 1, 1,
    1, 1, 1, 0, 0, 1, 1, 1
  ];

How to get element by column, row index, I tried this function from network:

getElement(row, column) {
    var index = row * 8 + column; 
}

But I did not get how does this function work, why we multiply on 8 and plus column?