“404 NOT FOUND” when passing parameters in url – Flask / Jinja

I am trying to pass some parameters through the url so my RestAPI can pass them to a function.

google-results.html (Code shortened for clarity)

<script>

query = "{{ query }}"
max_lead_amount = "{{ max_lead_amount }}"

api_url = `/api-v1/scrape/google-maps/?q=${query}&max=${max_lead_amount}`;

const response = await fetch(api_url);
const data = await response.json();

</script>

api_views.py (Code shortened for clarity)

@app.route('/api-v1/scrape/google-maps/?q=<query>&max=<int:max_lead_amount>')
def scrapeGoogle(query, max_lead_amount):
    return scrapeGoogleMaps(driver, query, max_lead_amount)

This is what Google Chrome returns on the console:

GET http://127.0.0.1:5000/api-v1/scrape/google-maps/?q=estsetse&max=7

Status 404 NOT FOUND

Adobe JavaScript – Summing two values with a comma

This is my code so far:

this.getField("price_config").setAction("onBlur", "calcSumElementprice()");
this.getField("amount").setAction("Keystroke", "calcSumElementprice()");

function calcSumElementprice(){

var priceConfig = this.getField("price_config").value;
app.alert("type priceConfig "  + typeof priceConfig + " Number " + priceConfig);

var amount = this.getField("amount").value;
app.alert("type amount "  + typeof amount + " Number " + amount);

var totalElementPrice = priceConfig * amount;    
var totalElementPriceValue = totalElementPrice ? parseFloat(totalElementPrice) : 0;
var totalPrice = totalElementPriceValue;

this.getField("Elementprice").value = totalPrice.toFixed(2).replace(".", ",");

Either I select amount or enter something in price_config, then the calcSumElementprice function is called.

For example, if I enter 200 for price_config, the calculation works perfectly. price_config and amount are then of type number. It also works with numbers that contain a point, e.g. 200.99 .

But if I enter 200.99, then priceConfig becomes a string. And the whole calculation no longer works, of course.

hat do I have to change so that both number variants (200 = whole numbers; 200,99 = numbers with commata) work?

How does the -1 filter method works [duplicate]

As pratice im doing a React search filter, i was able to complete it but a doubt remain:

const list = [
    "Banana",
    "Apple",
    "Orange",
    "Mango",
    "Pineapple",
    "Watermelon",
  ];
const filteredValues = list.filter((item) => {
      console.log(item.toLowerCase().e.target.value.toLowerCase());
      return item.toLowerCase().indexOf(e.target.value.toLowerCase()) !== -1;
    });

This is the logic for the filter, my question is: what does the “-1” means, i coundt find it online, sorry if my question is in the wrong format or inappropriate, im new here

Tried searching it online, but couldnt find

API response is not parsed by Axios after version update

I was using axios version 0.18.0:

const axiosInstance = axios.create({
  responseType: 'json',
  baseURL: `api/v1/example`,
  headers: {
    'Content-Type': 'application/vnd.api+json',
    Accept: 'application/vnd.api+json',
  },
});

axiosInstance.interceptors.response.use((response) => {
  console.log(response);
  return response;
}, callback);

log: 
{
  "data": { foo: "bar" }, <---- this is typeof Array (JSON is parsed automatically)
  "status": 200,
  "statusText": "",
  "headers": {},
  "config": {
  "transformRequest": {},
  ...and more
}

But after update to newest version, 1.6.2 and my app crashes because the JSON is not parsed properly anymore.

axiosInstance.interceptors.response.use((response) => {
  console.log(response);
  return response;
}, callback);

log: 
{
  "data": "{"foo":"bar"}" <---- typeof string (JSON, its not parsed automatically)
  "status": 200,
  "statusText": "",
  "headers": {},
  "config": {
  "transformRequest": {},
  ...and more
}

Why is my response is not parsed properly anymore? The response content type is:

application/vnd.api+json; charset=utf-8

Slack SDK `client.conversations.open()` returning User Not Found error

I’m using the Slack node SDK to try to send private messages from a bot based on a user ID:

const client = new WebClient(process.env.SLACK_TOKEN);

const privateMessage = async (userId) => {
  try {
    await client.conversations.open({
      users: [userId],
      text: 'Hi there.....',
    });
  } catch (error) {
    console.log(error);
  }
};

privateMessage('USERIDXXXXXX');

When I do so, I get the following error:

Error: An API error occurred: user_not_found
    at platformErrorFromResult (/Users/mej/Documents/test_repo/node_modules/.pnpm/@[email protected]/node_modules/@slack/web-api/dist/errors.js:62:33)
    at WebClient.apiCall (/Users/mej/Documents/test_repo/node_modules/.pnpm/@[email protected]/node_modules/@slack/web-api/dist/WebClient.js:181:56)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async privateMessage (/Users/mej/Documents/test_repo/apps/reports/bot/test_bot.ts:22:5) {
  code: 'slack_webapi_platform_error',
  data: {
    ok: false,
    error: 'user_not_found',
    response_metadata: { scopes: [Array], acceptedScopes: [Array] }
  }
}

This error is confusing because the user IDs I’ve tried were all returned by another call to the API (client.users.list()) with the same client / Bot User OAuth token. I know those users exist. I can see my own user ID in my Slack account settings, as well, and it also returns the user_not_found error.

The Slack app has the following permissions: channels:manage, channels:read, chat:write, groups:write, im:write, mpim:write, users:read, users:read.email.

React App Stops Working after sometime open in the editor(VS code)

So I set up a new React project with Vite using the terminal in vs code. It launches and seems like everything is working fine, I am able to edit the code and see those changes applied in the browser as well as the preview mode. After sometime, while its till open in Vs code, and I refresh, the preview just shows a blank page and the app also doesn’t show in the browser and says the site refused to connect

I’ve tried deleting the entire app folder and starting all over again multiple times. Every time it works just fine for a while but then the same problem arises

Barba JS and Lenis Scroll conflict

I’m using Lenis scroll for smooth scrolling and Barba.js for page transitions, they work together except if a page transition is triggered whilst lenis is still handling the scroll. For example user scrolls down, clicks link while scroll is gradually slowing down.

The bug means that the new page loads at the same scroll position as the page it left on, the window.scrollTo(); seems to work only when Lenis isn’t still handling the scroll.

I have tried to stop Lenis using Scroll.stop(); or scrollInstance.stop(); in the beforeLeave part of Barba.js but this causes the initial page to hard reload instead of the desired page transition.

I have been trying to resolve this for days now and I’ve gone blind to it, I must be missing something obvious so any help would be greatly appreciated.

Here is the code which has the bug:

<!--Lenis / Barba Scroll & Animations-->
<script>
const Scroll = {
  constructor(options) {
    // Create a new Lenis instance
    this.lenis = new Lenis({
      force: true, // This forces Lenis to scroll even when the cursor is over a WebGL element
      ...options
    });

    // Initialize the Scroll class
    this.time = 0;
    this.isActive = true;
    this.init();
  },

  init() {
    // Call the Lenis config method
    this.lenis.config();

    // Render the scroll
    this.render();

    // Handle the editor view
    this.handleEditorView();
  },

  render() {
    // Call the Lenis raf method
    this.lenis.raf(() => {
      // Update the time
      this.time += 10;

      // Render the next frame
      window.requestAnimationFrame(this.render.bind(this));
    });
  },

  // ... Other methods ...

  config() {
    // allow scrolling on overflow elements
    const overscroll = [
      ...document.querySelectorAll('[data-scroll="overscroll"]')
    ];

    if (overscroll.length > 0) {
      overscroll.forEach((item) =>
        item.setAttribute("onwheel", "event.stopPropagation()")
      );
    }

    // stop and start scroll btns
    const stop = [...document.querySelectorAll('[data-scroll="stop"]')];
    if (stop.length > 0) {
      stop.forEach((item) => {
        item.onclick = () => {
          this.stop();
          this.isActive = false;
        };
      });
    }

    const start = [...document.querySelectorAll('[data-scroll="start"]')];
    if (start.length > 0) {
      start.forEach((item) => {
        item.onclick = () => {
          this.start();
          this.isActive = true;
        };
      });
    }

    // toggle page scrolling
    const toggle = [...document.querySelectorAll('[data-scroll="toggle"]')];
    if (toggle.length > 0) {
      toggle.forEach((item) => {
        item.onclick = () => {
          if (this.isActive) {
            this.stop();
            this.isActive = false;
          } else {
            this.start();
            this.isActive = true;
          }
        };
      });
    }

    // anchor links
    const anchor = [...document.querySelectorAll("[data-scrolllink]")];
    if (anchor.length > 0) {
      anchor.forEach((item) => {
        const id = parseFloat(item.dataset.scrolllink);
        const target = document.querySelector(`[data-scrolltarget="${id}"]`);
        if (target) {
          //console.log(id, target);
          item.onclick = () => this.scrollTo(target);
        }
      });
    }
  },

  handleEditorView() {
    const html = document.documentElement;
    const config = { attributes: true, childList: false, subtree: false };

    const callback = (mutationList, observer) => {
      for (const mutation of mutationList) {
        if (mutation.type === "attributes") {
          const btn = document.querySelector(".w-editor-bem-EditSiteButton");
          const bar = document.querySelector(".w-editor-bem-EditorMainMenu");
          const addTrig = (target) =>
            target.addEventListener("click", () => this.destroy());

          if (btn) addTrig(btn);
          if (bar) addTrig(bar);
        }
      }
    };

    const observer = new MutationObserver(callback);
    observer.observe(html, config);
  }
};

// Create a new Scroll instance and assign it to a variable
const scrollInstance = scroll();

// Barba JS
var pageID;
var introOverlay = document.querySelector('.intro-overlay');
  
barba.init({
    transitions: [{
        sync: true,
        beforeLeave: function(data) {
            let end = data.next.html.indexOf(' data-wf-site="');
            let start = data.next.html.indexOf('data-wf-page="');
            let string = data.next.html.slice(start, end);
            let arr = string.split('"');
            pageID = arr[1];
          
            const done = this.async();
              gsap.to(data.current.container, {
              opacity: 0,
              duration: 0.5,
              onComplete: done,
            });
        },
        leave: function(data) {
            const done = this.async();
            done();
        },
        beforeEnter: function(data) {
            $('html').attr('data-wf-page', pageID);
          
            window.Webflow && window.Webflow.destroy();
            window.Webflow && window.Webflow.ready();
            window.Webflow && window.Webflow.require('ix2').init();
            window.Webflow && window.Webflow.require('lottie').lottie;

            if (introOverlay) {
              introOverlay.style.display = 'none';
            }
          
            window.scrollTo(0, 1);
            window.scrollTo(0, 0);
          
            $("[js-line-animation-delayed]").each(function() {
              $(this).removeAttr("js-line-animation-delayed");
              $(this).attr("js-line-animation", true);
            });
        },
        afterEnter: function(data) {
            setTimeout(() => {
                $("[js-line-animation]").each(function(index) {
                    gsap.set($(this), {
                        autoAlpha: 1
                    });
                    let textEl = $(this);
                    let textContent = $(this).text();
                    let tl;

                    function splitText() {
                        new SplitType(textEl, {
                            types: "lines",
                            tagName: "span"
                        });
                        textEl.find(".line").each(function(index) {
                            let lineContent = $(this).html();
                            $(this).html("");
                            $(this).append(`<span class="line-inner" style="display: block;">${lineContent}</span>`);
                        });
                        tl = gsap.timeline({
                            scrollTrigger: {
                                trigger: textEl,
                                start: "top bottom",
                                end: "bottom bottom",
                                toggleActions: "none play none reset"
                            }
                        });
                        tl.fromTo(textEl.find(".line-inner"), {
                            yPercent: 100
                        }, {
                            yPercent: 0,
                            duration: 0.6,
                            stagger: {
                                amount: 0.4,
                                ease: "power1.out"
                            }
                        });
                    }
                    splitText();

                    let windowWidth = window.innerWidth;
                    window.addEventListener("resize", function() {
                        if (windowWidth !== window.innerWidth) {
                            windowWidth = window.innerWidth;
                            tl.kill();
                            textEl.text(textContent);
                            splitText();
                        }
                    });
                });
                barbaHeroHome();
            }, 100);
        }
    }]
});
</script>

Sorting an arr by its content contents [duplicate]

So I have a massive arr which contains objects like these:

    {
      "age": 0,
      "id": "motorola-xoom-with-wi-fi",
      "imageUrl": "img/phones/motorola-xoom-with-wi-fi.0.jpg",
      "name": "Motorola XOOMu2122 with Wi-Fi",
      "snippet": "The Next, Next GenerationrnrnExperience the future with Motorola XOOM with Wi-Fi, the world's first tablet powered by Android 3.0 (Honeycomb)."
    },
    {
      "age": 1,
      "id": "motorola-xoom",
      "imageUrl": "img/phones/motorola-xoom.0.jpg",
      "name": "MOTOROLA XOOMu2122",
      "snippet": "The Next, Next GenerationnnExperience the future with MOTOROLA XOOM, the world's first tablet powered by Android 3.0 (Honeycomb)."
    },
    {
      "age": 2,
      "carrier": "AT&amp;T",
      "id": "motorola-atrix-4g",
      "imageUrl": "img/phones/motorola-atrix-4g.0.jpg",
      "name": "MOTOROLA ATRIXu2122 4G",
      "snippet": "MOTOROLA ATRIX 4G the world's most powerful smartphone."
    },

and I am making a website that will allow a user to search and filter through these objects. I have made a function that takes in this array and adds a html element (for each of the objects) containing the name and image of that particular phone. Now I am trying to make a filter that will sort the objects alphabetically (using the names of the phones). This is where I am stuck. My current result is this:

    function sortBy(by, phones_list) {
        switch(by) {
            case 'alphabet':
                new_phones = [];
                phone_names = [];
                phones_list.forEach(element => {
                    phone_names.push(element.name);
                });
                phone_names.sort();
                phone_names.forEach(name => {
                    phones_list.forEach(element => {
                        if (element.name.includes(name)) {
                            new_phones.push(element);
                        } else {
                            // pass
                        }
                    });
                });

                initPhones(new_phones);

                break;
            case 'newest':
                initPhones(phones_list);
            case 'relevance':
                initPhones(phones_list);
        }
    }
  

(initPhones is what creates the elements on the webpage)

It does not work, though (it just returns the phones list it had before). I am still learning the switch operator, so please bear with me. Could somebody please provide a solution? Thanks in advance.

How do I use custom edit components with material-react-table

I am following the official material-react-table docs on how to create a CRUD table. Reference link here https://www.material-react-table.com/docs/examples/editing-crud. However I am running into an issue when trying to use my own custom modal components for the “create new” functionality instead of the internalEditComponents provided from the library. Basically I have a custom dialog see below. When I view the values in the handle create function the values are empty unless I use the internalEditComponents. How do I populate the values props in the handle create function without creating a bunch of custom logic?

// handle create function

  const handleCreate: MRT_TableOptions<any>['onCreatingRowSave'] = props => {
    const { values, table, row } = props;

    console.log('handleDomainCorrectionCreate', values); // this is empty

  };

// custom dialog

   renderCreateRowDialogContent: props => {
       const { table, row, internalEditComponents } = props;
      <DialogTitle>Add correction entry</DialogTitle>
          <DialogContent>
            <Box sx={{ my: 2 }}>
              <DialogContentText variant="subtitle2">From</DialogContentText>
              <TextField
                autoFocus
                id="error_name"
                label="Error Name"
                type="text"
                fullWidth
                variant="standard"
                name="error_name"
                onChange={event => setErrorName(event.target.value)}
                value={errorName}
              />
            </Box>
            <Box sx={{ my: 2 }}>
              <DialogContentText variant="subtitle2">To</DialogContentText>
              <TextField
                id="corrected_name"
                label="Corrected Name"
                type="text"
                fullWidth
                variant="standard"
                name="corrected_name"
                onChange={event => setCorrectedName(event.target.value)}
                value={correctedName}
              />
            </Box>
          </DialogContent>
          <DialogActions>
            <MRT_EditActionButtons variant="text" table={table} row={row} />
          </DialogActions>
}

Progress bar with localstorage (js)

I’m using countdown with progress bar like this https://codepen.io/Rudchyk/pen/qNOEGj but I can’t figure out how do I save the progress when I reload the page?

<div id="progressBar">
                <div class="bar"></div>
            </div>
            <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
            <script>
                var seconds = {$timer_limited->sec}; // 10000
                $(document).ready(function () {
                    function progress(timeleft, timetotal, $element) {
                        
                        var progressBarWidth = timeleft * $element.width() / timetotal;
                       
                        $element.find('div').animate({ width: progressBarWidth }, 500);
                        if(timeleft > 0) {
                            setTimeout(function() {
                                progress(timeleft - 1, timetotal, $element);
                            }, 1000);
                        }
                    };

                    progress(seconds, seconds, $('#progressBar'));
                });
            </script>
            <style>
                #progressBar {
                    width: 100%;
                    height: 4px;
                    background-color: #DDDFE2;
                }
                #progressBar div {
                    height: 100%;
                    line-height: 22px;
                    width: 0;
                    background-color: #D03637;
                }
            </style>

how do I save the progress when I reload the page?

access value of the two input outside the event

i want to access value of the two input to make calculation immediately they put in a value

<script>
//i want to access value of the two input to make calculation immediately they put in a value
const heightInputEl = document.querySelector('.height-input');
const weightInputEl = document.querySelector('.weight-input');
  heightInputEl.addEventListener('input', function (e) {
  const height = Number(e.target.value);
  const mtrsqr = Math.abs(Math.pow(height / 100, 2));
});

weightInputEl.addEventListener('input', function (e) {
  const weight = Number(e.target.value);
});

</script>


How can i improve this encapsulated javascript code using imutable method?

I have this code, but I need to return pure functions instead the mutating functions.

Is it possible? Perhaps using OOP? I don’t know how to improve it.

I tried to return the values in each function, but I haven’t had success.

import { AssetStatusType } from '@domain/interfaces/common'

import {
  BothComponentType,
  ComponentsType,
  GroupFiltersType,
  OperationType,
  OverviewModelType,
  PendenciesOverviewType,
  PendenciesType,
  StructurePendenciesCount,
  StructureStatusCount
} from '../../types'

const updateStatusCount = (
  statusCount: StructureStatusCount,
  status: AssetStatusType
) => {
  statusCount[status] = (statusCount[status] || 0) + 1
}

const updatePendenciesCount = (
  pendenciesCount: StructurePendenciesCount,
  key: AssetStatusType,
  subKey: OperationType | PendenciesOverviewType
) => {
  pendenciesCount[key] = pendenciesCount[key] ?? {}
  pendenciesCount[key][subKey] = (pendenciesCount[key]?.[subKey] || 0) + 1
}

const processOverviewPendencies = (
  pendencies: PendenciesType[] | null | undefined,
  pendenciesCount: StructurePendenciesCount,
  countedIds: Set<string>,
  id: string
) => {
  if (pendencies?.length) {
    for (const { state, pendencyType } of pendencies) {
      const uniqueId = `${state}-${pendencyType}-${id}`
      if (!countedIds.has(uniqueId)) {
        updatePendenciesCount(pendenciesCount, state, pendencyType)
        countedIds.add(uniqueId)
        return {state, pendencyType}
      }
    }
  }
}

const processOverviewComponents = (
  components: ComponentsType[],
  isGroupByTree: boolean,
  statusCount: StructureStatusCount,
  pendenciesCount: StructurePendenciesCount,
  countedIds: Set<string>,
  id: string,
  type: BothComponentType
) => {
  for (const { pendencies, status, operationType } of components) {
    if (isGroupByTree && type === 'location') {
      updateStatusCount(statusCount, status)

      if (operationType) {
        updatePendenciesCount(pendenciesCount, status, operationType)
      }
    }
    processOverviewPendencies(pendencies, pendenciesCount, countedIds, id)
  }
}

const processOverviewData = (
  data: OverviewModelType[],
  groupBy: GroupFiltersType,
  statusCount: StructureStatusCount,
  pendenciesCount: StructurePendenciesCount,
  countedIds: Set<string>
) => {
  const isGroupByTree = groupBy === 'tree'
  const isGroupByAsset = groupBy === 'asset'

  for (const { id, status, components, operationType, type } of data) {
    if (isGroupByAsset || type === 'asset') {
      updateStatusCount(statusCount, status)
      if (operationType) {
        updatePendenciesCount(pendenciesCount, status, operationType)
      }
    }

    processOverviewComponents(
      components,
      isGroupByTree,
      statusCount,
      pendenciesCount,
      countedIds,
      id,
      type
    )
  }
}

export const calculateOverviewCounts = (
  data: OverviewModelType[],
  groupBy: GroupFiltersType
) => {
  const statusCount: StructureStatusCount = {} as StructureStatusCount
  const pendenciesCount: StructurePendenciesCount =
    {} as StructurePendenciesCount

  const countedIds = new Set<string>()

  const {} = processOverviewData(data, groupBy, statusCount, pendenciesCount, countedIds)

  // statusCount[status] = (statusCount[status] || 0) + 1

  return { ...statusCount, pendencies: pendenciesCount }
}

Is there a cleaner and more elegant way to do this? I need to return an object like this:

// calculateOverviewCounts return this

{
    pendencies: StructurePendenciesCount;
    working: number;
    inAlert: number;
    warning: number;
    stopped: number;
    off: number;
}

StructurePendenciesCount is:

enter image description here

Thank you in advance

JS input events executed in wrong order

I am investigating an issue in our web app, where a date change is not registered. Basically the user selects a date and then clicks on a ‘save’ button. I tried to reproduce the issue and get some weird results. I basically have two input controls: a date picker and a button:

<input type="date" onchange="dateChange(event)"/>
<button onclick="save(event)">Save</button>

I simply select a date in the date picker and immediately click on the save button afterwards. This usually works correctly. Therefore my guess was that the issue only occurs on slow machines.

So I throttle the CPU by the factor 6 (I am using Chrome debugger on Windows for this) and set logpoints in both events. If I’m fast enough I get an output like the following:

button 1673970.2000000477
date   1674030.3000000715

Here the button event is fired before the date event. And even the event timestamps are in the wrong order. How is this possible?

Note: I can only reproduce this on sites with quite some elements on it. A test page with only the described two controls is too fast and always works correctly.

Vue router is missing params that I’m pushing to it

I have a button that switches the page, when a user clicks the button it calls my method like this. I have an interesting circumstance where I need to load data within the same route, however I need to update the actual route at the same time. Here is how my method is setup:

async switchPage(pageNumber) {
  this.$router.push({
    name: this.$route.name,
    params: {
      foodId: articleIdForPageSelection,
      categoryId: this.issue.id,
      pageNumber: pageNumber,
    },
  });

  await this.loadFoodByPage(pageNumber);
}

After this fires the url should update and nothing else should happen because this push is using the same route via this.$route.name.

The reason this is necessary is because the URL must change so that way when a user presses the browsers back/forward button the URL will change and then in the main wrapper of the application I have a watch setup on the $route like this:

 watch: {
    $route(to) {
      if (
        to.name === 'Food' &&
        !to.params.categoryId &&
        !to.params.pageNumber
      ) {
        this.loadNewFood(this.$route.params.foodId);
      }
    },
  }

The thought here is that I will only call this route change if the category and page number do NOT exist on the to.params because they will not exist on a back button press or a page refresh, for example. In those cases we want to load the page again as if it’s a new food.

The problem is that whenever I do the $router.push in the switchPage function the to.params in the watch are never updated. The to remains the same value as it was on the initial page load, NOT the updated values that I have just pushed.

Also I realize this architecture sucks and I’m up for suggestions there too, but that’s too broad for SO.