How to get and preview the http image url from DB in under the HTML file type

I did achieve the preview image function use js and then I tried to get the http image url from DB, but it doesn’t geted and showed that particular image in image tag

I did try the got dynamic images to preview under the HTML tag element, but the dynamic images get in the DB, but it doesn’t show in the preview area, So How do achieve this in this film?

Note that:::
In the geted image url prefix has http, that set attribute only allowed for https

How to apply each tocbot?

I succeeded in applying tocbot, but only one <div class=”post”></div> was successful.
I want to apply tocbot to each repeated <div class=”post”></div> .

<div class="wrap>"
    <div class="post">
        <div>
            <h2></h2>
            <h3></h3>
        </div>
    <div class="toc"></div>
    </div>
    <div class="wrap>"
        <div class="post">
            <div>
                <h2></h2>
                <h3></h3>
            </div>
        <div class="toc"></div>
    </div>
    <div class="wrap>"
        <div class="post">
            <div>
                <h2></h2>
                <h3></h3>
            </div>
        <div class="toc"></div>
    </div>
</div>

  var content = document.querySelector('.post')
  var headings = content.querySelectorAll('h1, h2, h3, h4, h5, h6, h7')
  var headingMap = {}

  Array.prototype.forEach.call(headings, function (heading) {
    var id = heading.id
      ? heading.id
      : heading.textContent.trim().toLowerCase()
        .split(' ').join('-').replace(/[!@#$%^&*():]/ig, '').replace(///ig, '-')
    headingMap[id] = !isNaN(headingMap[id]) ? ++headingMap[id] : 0
    if (headingMap[id]) {
      heading.id = id + '-' + headingMap[id]
    } else {
      heading.id = id
    }
  })

    tocbot.init({
      tocSelector: '.toc',
      contentSelector: '.post',
      headingSelector: 'h2, h3, h4',
      hasInnerContainers: false,
      headingsOffset: -505,
      scrollSmoothOffset: -70,
    });

This is the source of tocbot, https://tscanlin.github.io/tocbot/
I am using it with this script. https://github.com/tscanlin/tocbot/blob/master/src/utils/make-ids.js

I applied this script, but tocbot was applied only when there was one <div class=”post”></div>.

I want it to be applied to each <div class=”post”></div>.

Extract svg tags and path tags with selenium python

I want to extract the svg tags and path tags of this website https://www.epargne-retraite-entreprises.bnpparibas.com/entreprises/fonds/multipar-actions-socialement-responsable-classique to recreate this chart: enter image description here. I’m using selenium in python and this is the beggining of my code
enter image description here
but something isn’t right. The first time I imported driver.page_source in my notebook I’ve got all the tags like this enter image description here but now when I look at my file temp_html.html the code is different, with graph tag and javascript code. I don’t know how to have the svg tags and path tags if someone can help it would be great.thanks

I tried to use other modules than selenium like requests but it doesn’t change anything. I look at the selenium library documentation to see if there is an option for that but I didn’t find anything.I need the full html like the third screenshot to create a svg image from it.

Why does adding an if block prevent Svelte transitions from playing?

I’m working on some code where I fetch some items in onMount then render them. I don’t want to play a ton of transitions for the big batch of fetched items. However, I do want to play transitions when individual items are added or removed from the list. This is a similar situation to this question.

If I write this, then I get the transition behavior I want.

{#if itemsFetched}
    {#each items as it (it.id)}
        <div transition:slide|local>
            <span>{it.id} {it.name}</span>
            <button on:click={removeItem(it)}>remove</button>
        </div>
    {/each}
{/if}

However, inside of the each block, I need to conditionally render something.
And if I add an if block, then the individual item transitions don’t play at all.

{#if itemsFetched}
    {#each items as it (it.id)}
        {#if it.id >= 0}
            <div transition:slide|local>
                <span>{it.id} {it.name}</span>
                <button on:click={removeItem(it)}>remove</button>
            </div>
        {/if}
    {/each}
{/if}

Here’s a full example.
Sandbox: https://codesandbox.io/s/sleepy-pasteur-st68wb?file=/App.svelte

<script>
import { slide } from "svelte/transition";
import { onMount } from "svelte";

// Initially we have no items.
let items = [];
let id = 0;

let itemsFetched = false;
onMount(() => {
    // Fetch items from API.
    items = [
        {id: id, name: `item ${id++}`},
        {id: id, name: `item ${id++}`},
        {id: id, name: `item ${id++}`},
    ];
    itemsFetched = true;
});

function addItem() {
    items = [
        ...items,
        {id: id, name: `item ${id++}`},
    ];
}

function removeItem(rmIt) {
    return () => {
        items = items.filter(it => it.id !== rmIt.id);
    };
}
</script>

<div>
    <button on:click={addItem}>add</button>

    {#if itemsFetched}
        {#each items as it (it.id)}
            {#if it.id >= 0}
                <div transition:slide|local>
                    <span>{it.id} {it.name}</span>
                    <button on:click={removeItem(it)}>remove</button>
                </div>
            {/if}
        {/each}
    {/if}
</div>

Why does adding an if block break the local transition? If I remove local, then the items play transitions when added or removed, but then I lose the initial onMount behavior I want.

Is there a hacky way for a Chrome Extension to detect if it has ever been disabled?

I’m writing an extension for enterprise environments that needs to detect if a user ever disables it. I know that you can detect the disabling of other extensions with chrome.management.onDisabled, but how does an extension detect when itself is disabled?

I was able to find an answer which uses chrome.runtime from a content script, but that’s impossible if the user does not have any http/https websites open.


This is my current solution, where I use chrome.history to check if the extension was ever disabled:

chrome.history.onVisited.addListener(() => {
  localStorage.lastActive = Date.now();
});

let lastActive = localStorage.lastActive;
if (!lastActive) return;

chrome.history.search({text: "", maxResults: 1}, (data) => {
  let wasDisabled = data[0].lastVisitTime - lastActive > 2000;
  console.log(wasDisabled);
  // if true, there were at least 2 seconds where extension was turned off
})

Basically, the extension constantly checks if it was active the last time the user was browsing. Once it is turned on again, it will take action and realize whether it had been inactive.


However, I feel like this is just too hacky and inconsistent. If a user can clear their browser history, they can fool the extension.

I know that the Chrome API is vast and sometimes weird, so if anybody has knowledge of how you would detect this in a more consistent way, that would be highly appreciated. If having two separate extensions is truly the cleanest and most reliable answer, then I will do that.

React Class Runs Code Excessively and Does Not Update State

In the constructor, I’m running this.onLoadAccountRetrieve(); to use the API to get the account details, and if an account is returned the use setState() to update the account and isLoginActive variables.

// outside of class
export interface PageState {
  account: AccountDTO;
  anchorEl: HTMLElement | null;
  isLoginActive: boolean;
  isMenuOpen: boolean;
}

// inside class
constructor(props: PageProps) {
  super(props);
  this.state = {account: null,anchorEl: null,isLoginActive: false,isMenuOpen: false};
  this.onLoadAccountRetrieve();
  console.log('constructor state', this.state);
}

componentDidMount(): void {
  // if user not found, and login state updated, redirect to login page
  this.redirectIfUserNotFound();
}

private redirectIfUserNotFound() {
  if (this.state.isLoginActive === false) {
    window.location.assign('/login');
  }
}

private async onLoadAccountRetrieve() {
  const res: AxiosResponse = await axios()
    .then((res) => {
    // original version - attempt 1
      this.setState({ account: res.data, isLoginActive: true });
    })
  // updated version - attempt 2 - code was moved here
  return this.setState({ account: res.data, isLoginActive: true });
}

What I’m seeing is the onLoadAccountRetrieve method being run 4 times that fail, and another 12 times that return the account data in a console.log but the state variables don’t get updated.
Questions:

  1. How do I get react to not run the code 16 times?
  2. How do I get my data to run before render()?

If I can get these two to be fixed, I’m expecting that the setState() (which isn’t updating anything now) would self resolve itself.

How do I connect my Apache Server Frontend to my node.js websocket server

Im having a Problem: I try to make a Website using Apache to host it on my VPS. I want the Frontend(HTML/JS) to connect via websocket to the node.js server file. On which port should websocket run? Which address should my Frontend(HTML/JS) send to? What do I need to change in the Apache configs?

I tested the Frontend(HTML/JS) and the node.js file on my PC which worked perfectly. I obviously used the address “ws://localhost:8080” on my Frontend(HTML/JS) and the port 8080 on my node.js file. This obviously doesnt work on the vps / apache using localhost.

Uploading file to Firebase Storage with v9 SDK results in 9 byte file, instead of he actual data [duplicate]

im trying to upload a pdf to a firebase storage, when i do it gets to the right place but as a ” application/octet-stream” dont know what im doing wrong followed the doc to a T, i’ll upload all relevant code in my html and js please i need help with firebase 9

<inputclass="form-control"name="personalFile"type="file"id="PersonalFormFile"/>`
the javascript `submitBtnPersonal.addEventListener('click', e => {

    const personalFile = document.getElementById('PersonalFormFile').files[0]

    const storage = getStorage();
    const storageRef = ref(storage)

    const imageRef = ref(storage, 'personalAccountForms');
    const fileRef = ref( storage, 'personalAccountForms/' + personalFile.name )
 
        uploadBytes(fileRef, File)

})

I’m using a button to trigger the upload.

Here is a snip of what gets to firebase:

database value

i can’t get the option value when i click on currenReading option

i’m trying to get all options and send it to a callback fun
its works fine for all option but current read no

 return (
    <div className="book-shelf-changer">
    <select    
    onChange={(e)=>{console.log(e.target.value);handelChange(ID,e.target.value)}} >
      <option value="none" disabled>
        Move to...
      </option>
      <option value="currentlyReading">Currently Reading</option>
      <option value="wantToRead">Want to Read</option>
      <option value="read">Read</option>
      <option value="none">None</option>
    </select>
  </div>
)

HTML/CSS: How do I create a 4×2 grid layout with images and buttons on the bottom of the image?

I want eight images with a collapsible button below each image to be formatted into a 4×2 grid. Below is a draft of what I’d like to achieve:correct

However, I’m getting the image and buttons stacked in one column:
incorrect

This is the code I have; it uses CSS, HTML, and Javascript to allow for collapsing of the buttons.

<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
/* styles for grid container */
.grid-container {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-template-rows: repeat(2, 1fr);
    gap: 10px;
    position: relative;
}
.grid-item {
    overflow: hidden;
}

/* styles for collapsible button */
.collapsible {
    background-color: #777;
    color: white;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
}


/* styles for active button and hover effect */
.collapsible:hover {
    background-color: #555;
}

/* styles for plus/minus sign */
.collapsible:after {
    content: '+'; /* default content */
    font-size: 13px;
    color: white;
    float: right;
    margin-left: 5px;
}

.collapsible.active:after {
    content: "-"; 
}

/* styles for collapsible content */
.content {
    width: 100%;
    padding: 0 18px;
    overflow: hidden;
    background-color: #f1f1f1;
    display: none;
} 
/* styles for collapsible content */
.content.active {
     display: block;
    }
</style>
<div class="grid-container">
    <div class="grid-item">
        <img src="https://cdn.shopify.com/s/files/1/0567/9847/8524/files/missingProductImage_240x240.png?v=1665864304" alt="" /> <button type="button" class="collapsible">Bob, Course Director</button>
        <div class="content">
            <p>Blahblah</p>
    </div>
    <div class="grid-item">
        <img src="https://cdn.shopify.com/s/files/1/0567/9847/8524/files/missingProductImage_240x240.png?v=1665864304" alt="" /> <button type="button" class="collapsible">Sue, Board Member</button>
        <div class="content">
            <p>blahblah</p>
    </div>
    <div class="grid-item">
        <img src="https://cdn.shopify.com/s/files/1/0567/9847/8524/files/missingProductImage_240x240.png?v=1665864304" alt="" /> <button type="button" class="collapsible">Tim, Instructor</button>
        <div class="content">
            <p>blahblah</p>
    </div>
    <div class="grid-item">
        <img src="https://cdn.shopify.com/s/files/1/0567/9847/8524/files/missingProductImage_240x240.png?v=1665864304" alt="" /> <button type="button" class="collapsible">Jose, Instructor</button>
        <div class="content">
            <p>blahblah</p>
    </div>
    <div class="grid-item">
        <img src="https://cdn.shopify.com/s/files/1/0567/9847/8524/files/missingProductImage_240x240.png?v=1665864304" alt="" /> <button type="button" class="collapsible">Jason, Course Director</button>
        <div class="content">
            <p>blahblah</p>
    </div>
    <div class="grid-item">
        <img src="https://cdn.shopify.com/s/files/1/0567/9847/8524/files/missingProductImage_240x240.png?v=1665864304" alt="" /> <button type="button" class="collapsible">Amy, Board Member</button>
        <div class="content">
            <p>blahblah</p>
    </div>
    <div class="grid-item">
        <img src="https://cdn.shopify.com/s/files/1/0567/9847/8524/files/missingProductImage_240x240.png?v=1665864304" alt="" /> <button type="button" class="collapsible">Gosia, Instructor</button>
        <div class="content">
            <p>blahblah</p>
    </div>
    <div class="grid-item">
        <img src="https://cdn.shopify.com/s/files/1/0567/9847/8524/files/missingProductImage_240x240.png?v=1665864304" alt="" /> <button type="button" class="collapsible">Alex, Instructor</button>
        <div class="content">
            <p>blahblah</p>
    </div>
</div>
<script>
var coll = document.getElementsByClassName("collapsible");
for (var i = 0; i < coll.length; i++) {
    coll[i].addEventListener("click", function() {
        this.classList.toggle("active");
        var content = this.nextElementSibling;
        content.classList.toggle("active");
    });
}
</script>

How do I actually use a returned array from JavaScript inside Java’s ScriptEngine?

Ok so lets imagine I have some JS that returns an array.
I set up the script engine and give it my script.

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");

        String script = "function getDisplay() {n" +
                "  var contents = [];n" +
                "  contents.push("test");n" +
                "  return contents;n" +
                "}";
        try {
            engine.eval(script);
        } catch (ScriptException e) {
            throw new RuntimeException(e);
        }

        Invocable inv = (Invocable) engine;

        try {
            Object obj = inv.invokeFunction("getDisplay");
            //This is where i am stuck
        } catch (ScriptException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

How do I actually do anything with this object that I get returned?

I tried casting it to different array types, printing it as a string and nothing seems to get me usable data.

The type of the object by the way is “org.mozilla.javascript.NativeArray”

Thanks for the help 🙂

I expected to get a usable array as a return value from

Object obj = inv.invokeFunction("getDisplay");

Nothing I seem to do will make this object usable.

After changing a UseState Hook React component is not re-rendering

I read many topics around these problem but none of them helped to find an answer.

I am using a useEffect to fetch an array of objects “nftRewards”. And it’s working fine cause I can see them on the console. But the part of the render that depends on this hook is not re-render once it was updated. And I don’t understand why.

  const [campaignRewardsJson, setCampaignRewardsJson] = useState<nftReward[]>([]);

  type nftReward = {
    title: string;
    description: string;
    imageURL: string;
    price: number;
    quantity: number;
  };


  useEffect(() => {
    if (rewards) {
      const fetchData = async () => {
        var data = await getRewardObject();

        setCampaignRewardsJson(data);
      };
      // call the function
      fetchData().catch(console.error);
    }
  }, [rewards]);

And At the end of my render , I have this but It’s never render by react:

{campaignRewardsJson.map((reward, index) => (
            <Card direction={{ base: 'column', sm: 'row' }} overflow="hidden" variant="outline">
              <Image objectFit="cover" maxW={{ base: '100%', sm: '200px' }} src={reward.imageURL} alt="Caffe Latte" />

              <Stack>
                <CardBody>
                  <Heading size="md">{reward.title}</Heading>
                  <Text py="2">{reward.description}</Text>
                </CardBody>

                <CardFooter>
                  <Button variant="solid" colorScheme="blue">
                    Mint NFT
                  </Button>
                </CardFooter>
              </Stack>
            </Card>
          ))}

Why is an input box’s value being over-written when a different switch case is chosen?

BACKGROUND:
An array of objects is passed from a grandparent component to a parent component.
The parent component has a filtered list of transportation modes which are passed to a switch statement.
A ‘case’ is chosen which opens up a input box in a grandchild component; the grandparent’s array of objects are also passed.
The user enters a value.
The new object is dynamically created and passed back to the parent component and then back to the array of objects in the grandparent component.

PROBLEM:
The problem is when the user makes another selection, the input box value from the previous choice is over-written. That object’s cost is now an empty string even though the values are still in that input box. * * When I add/remove one character in that value, that object “remembers” all other characters including the new value. * * This input box’s value is now part of that new object.

HOMEWORK:
I’ve tried three different options: 1) The input boxes placed in the parent component with a switch statement that returned the component, 2) a 3-generation configuration that returned the input box value in the JSX and 3) a 3-generation configuration that calls the switch statement from the JSX (present configuration).

Parent Code:

// As needed, retrieve the daily cost from the user
const DailyTransportationCost = ({ dailyTransportationCosts, setDailyTransportationCosts }) => {

   const renderModalOptions = (transportation) => {
     switch(transportation) {
       case 'eScooter':
         return <EscooterInputBox 
                   dailyTransportationCosts={dailyTransportationCosts} 
                   setDailyTransportationCosts={setDailyTransportationCosts} />

        case 'Bus':
          return <BusInputBox 
                    dailyTransportationCosts={dailyTransportationCosts} 
                    setDailyTransportationCosts={setDailyTransportationCosts} />

        default:
      console.log('A problem has occurred with renderModalOptions()...');
     }
   }

   return (
      <div className={`${styles.containerTransportationCost}`}>

         {/* Map the json array to extract <DailyTransportationCost /> text data */}
         {DAILY_TRANSPORTATION_TEXT.map((text, key) => {

            return (
               <div key={key}>

              <label className={`${styles.containerLabel}`}>
             {text.labelDailyTransportationComponent}
          </label>                  

          {dailyTransportationCosts
                     .filter(mode => mode !== 'Vehicle' && mode !== 'Walking')
                     .map((transportationData, index) =>  {
                        return(
                          <div key={index}>
                             <div className={`${styles.dataInputBox}`}> 
                {renderModalOptions(transportationData.mode)}
                             </div>
                          </div>
                        );
                  })}
               </div>
            );
          })}
      </div>
   );   
};

// Export the file
export default DailyTransportationCost;

Grandchild Code:

const EscooterInputBox = ({dailyTransportationCosts, setDailyTransportationCosts}) => {

   // Create a constant eScooter ID
   const ESCOOTER_MODE = '2';

   // Retrieve the eScooter object
   const getEscooterInformation = 
            dailyTransportationCosts.find((dailyCost) => dailyCost.id === ESCOOTER_MODE);

      // Save the user's input box value
      const [newValue, setNewValue] = useState('');


      // Capture the input box data and set/remove the character
      const handleInputChange = e => {
    setNewValue(e.target.value);
      };

      // Replace the old eScooter object
      useEffect( () => {
    const newState = dailyTransportationCosts.map(obj => {

       if(obj.id === ESCOOTER_MODE) {
          return {id: getEscooterInformation.id, mode: getEscooterInformation.mode, cost: newValue}
       } else {
          return obj;
       }
         });

         // Replace the eScooter object
         setDailyTransportationCosts(newState);

      }, [newValue]);

      return(
    <div className={`${styles.containerInputBox}`}>
          placeholder="0.00"
          id='eScooterInputBox'
          type='number'
          value={newValue}
          onChange={handleInputChange}
        </div>
      );
};

// Export the file
export default EscooterInputBox;

CURRENT RESULTS:
All behaviors are the same. I can’t figure out how React is over-writing that object’s cost, but “remembers” that value when only one character is changed.

Is there an easy way to detect the main title and body text of an HTML using NodeJS? [closed]

I want to create a smart parsers for HTML files that can extract the title and main body text from it.

For example in a typical Wikipedia page, there is menu links and photos and similar articles etc. I only want to extract the main title (or titles) and text from the whole article:

enter image description here

Another example is a CNN article for example:

enter image description here

Is there any API that can do this from pure HTML file only? I’m working on a Chrome extension that needs to clean up unnecessary HTML elements for someone trying to read something in peace. All the distractions from an article’s menus, ads and so on can be quite distracting. I’m wondering if there is any smart API or libraries in JS that can help in doing this? Even research papers would be helpful.

How can I create a string to queue hash map in Javascript?

I’m building a server to connect people to chat based on yes or no responses to a question. There are multiple different questions – so my idea is to hash the question string appended with “yes” or “no” and point this to a queue. As people select yes or no for any given question they’ll be matched with people who answered the opposite. But JS doesn’t seem to have any standard Map or Queue libraries that I can use.