Manipulate embedded / recreated web page

I want to be able to “embed” a web page, and be able to manipulate the resulting page (click(), textContent etc).

I now understand that’s not possible for security reasons. I tried iframe, embed, objects.

Is it possible to fetch the HTML of the page, insert that into a frame / div, and then manipulate that ‘recreated’ page? I guess I’d need to write a function to add parts to the code so it all looks like a faithful recreation (I don’t think I need help with this part).

Blueimp Gallery – Add a static generic linkable image as last slide

I have been struggling on how to add a static linkable image as the last slide at the end of a slideshow before it loops back to the beginning. Any help is greatly appreciated.

                        <#assign photoIndex = 0>
                        <#assign albums = listingElementDetail.getAlbums('${urlPrefix}')>
                        <#if (albums)?has_content>
                        <div id="cont-gallery">
                            <div id="blueimp-gallery-carousel" class="blueimp-gallery blueimp-gallery-controls blueimp-gallery-carousel">
                                <div class="slides"></div>
                                <a class="prev"><h4 class="icon-chevron-left" style="top: -8px; position: relative;"></h4></a>
                                <a class="next"><h4 class="icon-chevron-right" style="top: -8px; position: relative;"></h4></a>
                                <ol class="indicator"></ol><div class="indicator-container"></div>
                            </div>

                            <div id="links" style="display:none;">
                                <#if (albums)?has_content>
                                    <#list albums as album>
                                        <#list album.photos as photo>
                                                <a href="" title="${listingPropertyStreet!}, ${City!} ${StateName!}">
                                                    <img width="48" height="33" src="" alt="${Street!}, ${City!} ${StateName!}" />
                                                </a>
                                            <#assign photoIndex=photoIndex+1>
                                        </#list>
                                    </#list>
                                </#if>
                            </div>

                            <script src="<@resource.url '/static/lib/Gallery-2_15_2/js/blueimp-gallery.min.js'/>"></script>
                            <script>
                                document.getElementById('links').onclick = function (event) {
                                    event = event || window.event;
                                    var target = event.target || event.srcElement,
                                        link = target.src ? target.parentNode : target,
                                        options = {index: link, event: event},
                                        links = this.getElementsByTagName('a');
                                    blueimp.Gallery(links, options);
                                };

                                blueimp.Gallery(
                                    document.getElementById('links').getElementsByTagName('a'),
                                    {
                                        container: '#blueimp-gallery-carousel',
                                        carousel: true,
                                        stretchImages: "cover",
                                        startSlideshow: false,
                                        onslide: function (index, slide) {
                                            var thumbWidth = jQuery("#blueimp-gallery-carousel .indicator li").first().outerWidth(true);
                                            var thumbContMargin = parseInt(jQuery("#blueimp-gallery-carousel .indicator").css("margin-left"));
                                            var slideWidth = $j(slide).width();
                                            var numThumbs = $j('#blueimp-gallery-carousel .indicator li').length;
                                            var thumbContainerWidth = ((numThumbs) * thumbWidth) + (thumbWidth);

                                            jQuery("#blueimp-gallery-carousel .indicator").width(thumbContainerWidth);

                                            var currentThumb = $j('#blueimp-gallery-carousel .indicator li')[index];
                                            var currentThumbOffset = $j(currentThumb).position().left + (thumbWidth);
                                            if( thumbContainerWidth > slideWidth){
                                                if( currentThumbOffset > (slideWidth/2) ){
                                                    var offsetLeft = Math.min((currentThumbOffset - slideWidth/2), (thumbContainerWidth - slideWidth + (thumbContMargin/2)));
                                                } else {
                                                    offsetLeft = 0;
                                                }
                                                jQuery("#blueimp-gallery-carousel .indicator").animate({"left":"-" +offsetLeft + "px"}, 200);
                                            } else {
                                                jQuery("#blueimp-gallery-carousel .indicator").animate({"left":"-40px"}, 200);
                                            }
                                        }
                                    }
                                );
                            </script>
                        </div>
                        </#if>

MongoDB – remove after aggregation

trying to remove an object from array after using aggregate(). but im getting this error.
‘subCategory.remove is not a function’

const deleteSubCategory = asyncHandler(async (req, res) => {
 const subCategory = await Category.aggregate([{$unwind: "$SubCats"}, { $replaceRoot: {newRoot: '$SubCats'}}, {$match: {_id: ObjectId(req.params.id)}}])

 if (subCategory) {
     await subCategory.remove()
     res.json({ message: 'sub-category removed' })
 } else {
     res.status(404)
     throw new Error('sub-Category not found')
 }
})

results after aggregation:

[{
  _id: '61cae5daf5bfbebd7cf748ef'
  name: 'subcat 1',
  image: '/assets/images/vr-box-6203301_1920.jpg',
}]

array before aggregation:

[
 {
     _id: '61cae5daf5bfbebd7cf748ee'
     title: 'category 1',
     SubCats: [
         {
             _id: '61cae5daf5bfbebd7cf748ef'
             name: 'subcat 1',
             image: '/assets/images/vr-box-6203301_1920.jpg',
         },
         {
             _id: '61cae5daf5bfbebd7cf748fb'
             name: 'subcat 2',
             image: '/assets/images/galaxy-s20_highlights_kv_00.jpg',
         },
     ]
 },
]

is it saying ‘subCategory.remove is not a function because of the ‘[]’ in the results after aggregation. becasue i find that remove() works fine if the reulsts start with {}

Chart.js not displaying when passing dynamic labels

I am trying to draw a chart by passing values for labels and data dynamically using char.js.

The chart.js module refuses to accept the labels when passed as a variable.
When I hardcode it, it works just fine.
The label variable prints out the values on the page and seems to be correct in format.

Very similar to the problem described in the below query, except that I am already using a proper array.

[https://stackoverflow.com/questions/60453491/chart-js-not-showing-data-when-pass-dynamic-labels][1]

mypage.html:

<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

{{Messages.vm_size_in_use_labels}}
{{Messages.vm_size_in_use_data}}

<canvas id="chart" width="50" height="50"></canvas>

    <script lang="JavaScript">
    let ctx = document.getElementById("chart").getContext("2d");

    let chart = new Chart(ctx, {
      type: "pie",
      data: {
         labels: {{Messages.vm_size_in_use_labels}},
         datasets: [
            {
              label: "Gross volume ($)",
              backgroundColor: "#79AEC8",
              borderColor: "#417690",
              data:   {{Messages.vm_size_in_use_data}},
            }
         ]
      },
      options: {
         title: {
            text: "Gross Volume in 2020",
            display: true
         }
      }
    });
    </script>

The page shows the printed value correctly but chart doesn’t display:


['Standard_B1ls', 'Standard_D2_v2', 'Standard_D4s_v3', 'Standard_B1s'] 
[3, 3, 1, 1] 

If I change the label to hard values,

         labels: ['Standard_B1ls', 'Standard_D2_v2', 'Standard_D4s_v3', 'Standard_B1s'],

this works just fine and chart is displayed.

Not sure what is missing here. the framework is django if it matters.

why React Router not rendering dom

Hi i am having trouble in mapping url in react.i am complete new to react js.i am trying to render a component into my App js,when i render it as component like things goes well but when i try to render it as a Route i am getting this error i tried some available solution form stackoverflow like importing it as ‘react-route-dom’,Routes instead of Router but still unable to fix this bug.please guide me to fix this bug

enter code here
import {
BrowserRouter as Router,
Route,
    }   from "react-router-dom";

import './App.css';
import Header from './componnents/Header'
import NotesPage from './Pages/NotesPage'
import NotePage from './Pages/NotePage'
function App() {
     return (
             <div className="App">
                   <Header />
                   <Router>
                           <Route exact path="/" component={NotesPage} />
                   </Router>
            </div>);}
            export default App;

this is my error:

   index.tsx:19 
   Uncaught Error: A <Route> is only ever to be used as the child of <Routes> element, never 
    rendered directly. Please wrap your <Route> in a <Routes>.
at invariant (index.tsx:19:1)
at Route (index.tsx:230:1)
at renderWithHooks (react-dom.development.js:14985:1)
at mountIndeterminateComponent (react-dom.development.js:17811:1)
at beginWork (react-dom.development.js:19049:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
at invokeGuardedCallback (react-dom.development.js:4056:1)
at beginWork$1 (react-dom.development.js:23964:1)
at performUnitOfWork (react-dom.development.js:22776:1)
invariant @ index.tsx:19
Route @ index.tsx:230
renderWithHooks @ react-dom.development.js:14985
mountIndeterminateComponent @ react-dom.development.js:17811
beginWork @ react-dom.development.js:19049
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
beginWork$1 @ react-dom.development.js:23964
performUnitOfWork @ react-dom.development.js:22776
workLoopSync @ react-dom.development.js:22707
renderRootSync @ react-dom.development.js:22670
performSyncWorkOnRoot @ react-dom.development.js:22293
scheduleUpdateOnFiber @ react-dom.development.js:21881
updateContainer @ react-dom.development.js:25482
(anonymous) @ react-dom.development.js:26021
unbatchedUpdates @ react-dom.development.js:22431
legacyRenderSubtreeIntoContainer @ react-dom.development.js:26020
render @ react-dom.development.js:26103
./src/index.js @ index.js:6
options.factory @ react refresh:6
__webpack_require__ @ bootstrap:24
(anonymous) @ startup:7
(anonymous) @ startup:7
react-dom.development.js:20085 
    
   The above error occurred in the <Route> component:

at Route (http://localhost:3000/static/js/bundle.js:35654:11)
at Router (http://localhost:3000/static/js/bundle.js:35669:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:35149:5)
at div
at App

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
logCapturedError @ react-dom.development.js:20085
update.callback @ react-dom.development.js:20118
callCallback @ react-dom.development.js:12318
commitUpdateQueue @ react-dom.development.js:12339
commitLifeCycles @ react-dom.development.js:20736
commitLayoutEffects @ react-dom.development.js:23426
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
commitRootImpl @ react-dom.development.js:23151
unstable_runWithPriority @ scheduler.development.js:468
runWithPriority$1 @ react-dom.development.js:11276
commitRoot @ react-dom.development.js:22990
performSyncWorkOnRoot @ react-dom.development.js:22329
scheduleUpdateOnFiber @ react-dom.development.js:21881
updateContainer @ react-dom.development.js:25482
(anonymous) @ react-dom.development.js:26021
unbatchedUpdates @ react-dom.development.js:22431
legacyRenderSubtreeIntoContainer @ react-dom.development.js:26020
render @ react-dom.development.js:26103
./src/index.js @ index.js:6
options.factory @ react refresh:6
__webpack_require__ @ bootstrap:24
(anonymous) @ startup:7
(anonymous) @ startup:7
index.tsx:19 
    
   Uncaught Error: A <Route> is only ever to be used as the child of <Routes> element, never 
 rendered directly. Please wrap your <Route> in a <Routes>.
at invariant (index.tsx:19:1)
at Route (index.tsx:230:1)
at renderWithHooks (react-dom.development.js:14985:1)
at mountIndeterminateComponent (react-dom.development.js:17811:1)
at beginWork (react-dom.development.js:19049:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
at invokeGuardedCallback (react-dom.development.js:4056:1)
at beginWork$1 (react-dom.development.js:23964:1)
at performUnitOfWork (react-dom.development.js:22776:1)
invariant @ index.tsx:19
Route @ index.tsx:230
renderWithHooks @ react-dom.development.js:14985
mountIndeterminateComponent @ react-dom.development.js:17811
beginWork @ react-dom.development.js:19049
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
beginWork$1 @ react-dom.development.js:23964
performUnitOfWork @ react-dom.development.js:22776
workLoopSync @ react-dom.development.js:22707
renderRootSync @ react-dom.development.js:22670
performSyncWorkOnRoot @ react-dom.development.js:22293
scheduleUpdateOnFiber @ react-dom.development.js:21881
updateContainer @ react-dom.development.js:25482
(anonymous) @ react-dom.development.js:26021
unbatchedUpdates @ react-dom.development.js:22431
legacyRenderSubtreeIntoContainer @ react-dom.development.js:26020
render @ react-dom.development.js:26103
./src/index.js @ index.js:6
options.factory @ react refresh:6
__webpack_require__ @ bootstrap:24
(anonymous) @ startup:7
(anonymous) @ startup:7

How to export input html data to txt by php (problem)

i found this code on internet and i want to have these inputs:
name
check box with 5 items

this code saves user’s info that selected in checkbox and his name in a text file

can someone help me to fix this?

<!DOCTYPE html>
<?php
if(isset($_POST['submit'])){
$Name = "Username:".$_POST['username']."
";
$Pass = "Password:".$_POST['password']."
";

$file=fopen("saved.txt", "a");
fwrite($file, $Name);
fwrite($file, $Pass,);
echo fwrite($file,"*************************",);
fclose($file);
}
?>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $('.check').click(function() {
        $('.check').not(this).prop('checked', false);
    });
});
</script>
<BODY>

<form action = "post.php" method="POST">

    <p>
        <label>Login Name:</label><input type = "text"  name = "name" /><br>

<input type="checkbox" type = "password"  name="pwd[]" class="check" value="male"> Male
<input type="checkbox" type = "password"  name="pwd[]" class="check" value="female"> Female
<input type="checkbox" type = "password"  name="pwd[]" class="check" value="other"> Other

        <br/>
        <br/>
    </p>
    <input type = "submit" name="submit_btn" id = "submit" value = "submit"/>
    <input type = "reset"  id = "reset" value = "reset"/>
</form>
</BODY>
</html>

How to play sounds in github?

I was making a github repository with a HTLM5 file and a mp3 file.

On the html file i writed:

<script>
var audio = new Audio('sound.mp3');
audio.play();
</script>

And then i uploaded in the repository a mp3 file, imagine if the file name was sound.mp3.

Here’s what the files look like:

index.html

sound.mp3

The problem is that the HTML script i made is not playing the sound on the github page.

I’m 100% sure that i have the volume up but it dosn’t play.

What can i do to make it play the sound in the repository files?

Also i tried using images and looks like the html can get the img file in the repository but not sounds.

Locking down a TypeScript class so that it is final and all invariants are guaranteed, even at runtime?

What is the best way of making a TypeScript class final, and ensure that all its invariants are guaranteed, even during runtime (when it might be accessed by arbitrary JavaScript code)?

A simple example of what I want to do is the following MutableInt class:

export class MutableInt {

    static {
        Object.setPrototypeOf(MutableInt.prototype, null);
        Object.freeze(MutableInt.prototype);
        Object.freeze(MutableInt);
    }

    #value : int

    constructor (value : int = 0) {
        if (new.target !== MutableInt) throw new Error("MutableInt is final");
        if (!Number.isInteger(value)) throw new Error(`Integer expected, found: ${value}`);
        this.#value = value;
        Object.freeze(this);
    }

    get value(): number {
        return this.#value;
    }

    set value(v) {
        if (!Number.isInteger(v)) throw new Error(`Integer expected, found: ${v}`);
        this.#value = v;
    }

}

Is MutableInt properly locked down? Or is there something wrong or missing with this approach?

How to build/What’s the build command for vue2 typescript project for production?

I have vue2 and vuetify project written in typescript. Following is configuration files.

package.json

"scripts": {
    "build": "tsc --build",
  },
"devDependencies": {
    "typescript": "~4.1.5",
  },

tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "outDir": "dist",
    "types": [
      "webpack-env"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

Now, When I try to build using command npm run build, it successfully builds the dist folder but it doesn’t adds .vue files inside dist folder. So, what’s wrong here?

Why can I log an object value before declaration?

I just notice that the code below works even before I declare anything using var, let or const. I read an explanation that I’m creating anything on the global/window object (in non-strict mode), but I’m not doing any variable declaration/creation here (instead just throwing anything out of nowhere).

So, anything = {} is enough for JS to understand that I’m declaring (and initializing) anything? How does this really work?

anything = { 1: "anything" }
console.log(anything) // {1: "anything"}

How to get x number of random document in firestore with web v9

I’m working on a project where an explore page requires random posts. I want to get 10 random posts from the posts collection. I am using firebase web SDK v9.6.3.

This is code I have written to get x number of posts:

export async function getRandomPosts(postCount) {
   const q = query(
      collection(db, "posts"),
      limit(postCount)
      // orderBy("timestamp", "desc")
   );
   const querySnapshot = await getDocs(q);
   let posts = [];
   querySnapshot.forEach((doc) => {
      posts.push({
         id: doc.id,
         ...doc.data(),
         timestamp: doc.data().timestamp?.toDate().toString(),
      });
   });
   return posts;
}

I can’t find anything to get the random documents. Is there anything like rand in mySQL ?

CommonJS JavaScript modules – passing data to parent functions

Using CommonJS JavaScript Modules.
I have a module that I cannot edit or control. I call this the parent module.

I want to build on the parent’s functionality with additional features. Some of these child features need to use the functions in the parent. So I need to pass data to the parent and have it run like it was part of the parent module. The whole of the parent is exported.

Parent

function ParentModule () {
  DefaultElement.setStatus = function (status, block) {
    var statusBlock = block.querySelector('.' + this.statusBlock)
    var statusText = status ? 'Available' : 'Out of Stock';
  
    statusBlock.innerHTML = statusText;
  }
}

Child


function ChildModule () {
  UpdatedElement.update = function (el) {
    var selected = document.getElementById(el)
    var block = this.getBlock(selected)

    window.ParentModule.DefaultElement.setStatus(true, block);
  }
}

(Expected) Error

Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')

What is the syntax or pattern for this?

Calling the relevant function within the child module, simply causes an error. As I understand this is expected – as the child module imports the parent function it runs within the child so doesn’t have access to the same data.

Rather than import into the child is there a way to have the child module simple behave like it was all one file? Or how can I pass data up to the parent and have it behave like it’s always been part of the parent?

JavaScript function calculate square

The HTML page contains an element with the id “number”. The page calls a function calcSquare(), which has to fetch the value of the element, calculate its square (power of two), and print it in the console like so: “The square of X is Y”. Write this function. The HTML page in question will load your code, so you can refer to the page with the document keyword.

<body>
<p id="number">0</p>
<button id="button1" 
onclick="calcSquare()">Click here! 
</button>
</body>

Example output:

The square of … is …

The output of the program must be exactly the same as the example output (the most strict comparison level)

MY CODE:

function calcSquare() {
var number = document.getElementById("number").value;
Math.pow(number, 2);
}
console.log ("The square of" number "is" calcSquare)

That ID is given in the web page

Don’t understand how to write here console.log or maybe problem in the function??