Scrolling a document to the far right on load

I can’t figure this out, sounds like it should be simple but I tried all kinds of variations of what I found here javascript – How to use window.scroll to automatically scroll on pageload? – Stack Overflow but trying to modify it to scroll horizontally instead… and couldn’t get any of them to work. If I used code to scroll to the bottom, that worked fine.

I’m trying to run the code within

$(function () {
    function Scrolldown() {
        // alert("hi")
       //$("img").scrollIntoView(false);
    //    window.scrollTo({ left: 0, top: document.body.scrollHeight, behavior: "smooth" });
        // window.scrollTo(-5000, 0);
//        $("img").scrollIntoView(false);
   }
   
   window.onload = Scrolldown; 
});

My page simply consists of a bunch of images, all the same width.. which are wider than the view area (or whatever the technical term is) of the browser… i.e. you need to scroll right to see the rest of the image.

I would like on load for the user to see the right end of the image, the left part can be off-screen. As opposed to the default where the left is visible and the right is offscreen.

I’m not averse to animation, but without is preferable. But the important thing is just finding something that works.

Adjusting video src to URL parameter

I’d like to set the src to my video according to the URL parameter (after the ?)
Here’s what I’ve got so far:

<video></video>
<script>
document.getElementsByTagName("video").src="###";

I need help with setting the ### src value to the correct value like so:
realistic example

https://website.com/player?@#$%

src="https://areallylongaddress.com/videosourcefolder/@#$%";

simpler example

https://website.com/player?intro_video

src="https://areallylongaddress.com/videosourcefolder/intro_video";

essentially, a strip of code that sets the video src to a fixed string value (areallylongaddress.com), then adds the url parameter to the end

How to match and extract a regular expression pattern?

I have a string like so – SampleReleaseFY20Q3.STRY0122544.Developer.SDLCRework.6

Now, I would like to extract the pattern STRY******* and store it in a variable. So in this case, I would like to extract STRY0122544 and store it in a variable.

Any help with this is appreciated!

Thanks,
Raskill

Can you tell me why my code for turning an array to a number, adding one, and returning an array only works on some datasets?

I’m trying to solve the following Leetcode problem:

You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0’s.

Increment the large integer by one and return the resulting array of digits.

Example 1:

Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].

Here’s my code :

var plusOne = function(digits) {
    
    let newDigit = digits.join('')
    if (newDigit.length > 15) {
        let digitLength = newDigit.length
        let secondHalf = newDigit.slice(digitLength - 15, digitLength)
        secondHalf = parseInt(secondHalf) + 1
        secondHalf = Array.from(String(secondHalf), Number)
        digits.splice(digitLength - 15, 15)
        return digits.concat(secondHalf)
        
        
    
    }
    let Digit = parseInt(newDigit) + 1
    const answer = Array.from(String(Digit), Number)
    return answer
    
};

Works for many data sets. Get’s the following error on the following set. Why 🙁

enter image description here

Dividing total value by quantity in JS with foreign currency

Have a unique situation and not exactly sure how to handle it properly.

price_per_item = (total / quantity).toFixed(2)

Total is a total value without currency symbol. Quantity is an integer. I am also supplied with an ISO 3 letter currency code. Above is how I would handle things if everything was supplied in USD, but it isn’t, and I don’t think this code would handle other currencies properly. I need this calculation to send ecommerce data from my order processor to Google Analytics.

What is the correct approach to handle this? I’ll have the currency code and just need to get a per item price in whatever currency is supplied.

Javascript – Using UUID indexes instead of classical array

All developers have to face with optimization questions in theirs codebases
Manipulating (find, formatting, sorting, etc.) data is probably one of the most time consuming in every layouts
So from this, I was wondering why people usually use Array instead of Object (aka map) ? Mostly to store (backend/frontend) them, or even to return them from the API

From what I understand, using array is mostly used for those elements with no unique ID and to sort data in a specific order
But I think the role of sorting data must be on the controller side during the page rendering

Articles, opinions, suggestions are warm welcome 🙂

Causing Cannot read properties of undefined

Currently I got error Uncaught TypeError: Cannot read properties of undefined (reading 'split') when I click and it doesn’t show the new window. This error only causing when I started to use our website in Microsoft Edge. Before that we were using in IE11. But currently, IE11 is shutting down so tryna start to use in Edge and causing that error. May I know how to fi it? In previously, it works well in IE11 and causing no error.

var newWindow;
function openBreakdown(x){
    // alert('kpi breakdown is not yet complete.');

    var data = x.split('|');
    var mnth = data[0]; //corresponding month, january starts at 7 onwards...
    var typx = data[1]; //type of report downtime %, mttr, mtbi, longdown etc...
    var rprt = data[2]; //type of report duration (y, q, m, w)...
    
    // alert(typx);
    if(typx == 'tldw'){
        newWindow = window.open("kpi_breakdown.php?month="+mnth+"&type="+typx+"&rprt="+rprt, "_blank", "location=no, toolbar=no, scrollbars=yes, resizable=yes, top=80, left=310, width=450, height=800");
    } else {
        newWindow = window.open("kpi_breakdown.php?month="+mnth+"&type="+typx+"&rprt="+rprt, "_blank", "location=no, toolbar=no, scrollbars=yes, resizable=yes, top=80, left=310, width=900, height=800");
    }

}

Above codes are JavaScript codes. Error is causing in x.split("|") line.

if(($y >= 32 || $y >= $endLast) && $x < $endRowColorCoding){

                        //echo "<td>";
                        //onClick='openBreakdown(this.value);'
                        echo "<td class='bdata$sub' id='trgt$t' value='$year$mnth|$varname[$x]|$rprt' onClick='openBreakdown(this.value);' title='$year$mnth|$varname[$x]|$rprt'>";

echo "<td class='data$sub' id='trgt$t' onClick='openBreakdown(this.value);' value='$year$mnth|$varname[$x]|$rprt' title='$year$mnth|$varname[$x]|$rprt'>";
                        echo $val[$y][$x];                          
                        $csv .= $val[$y][$x].",";
                        // if($y == 0 || $y == 4  || $y == 5 || $y == 9 || $y == 21 || $reportDuration[$y] == 'qtd' || $reportDuration[$y] == 'mtd'){ $csv .= ","; }
                        if($y == 0 || $y == 4  || $y == 5 || $y == 9 || $y == 10 || $y == 14 || $y == 15 || $y == 31 || $y == 19 || $y == 45 || $reportDuration[$y] == 'qtd' || $reportDuration[$y] == 'mtd'){ $csv .= ","; }
                    echo "</td>";

Often Misused: File Upload in UI (Fortify scan)

I try to catch the exception file extensions allow only upload with “.xls,.xlsx”.
When i do scan using fortify i have got vulnerabilities like “Often Misused: File Upload”. Tool warning this line

input type=”file” name=”file” id=”file”

Help me to pass this case.

adding display to react component conditionally?

I am trying to hide the components conditionally

method 1:
to add style = display : none to div

is there a way to dynamically add display to div via state?

since all the components are in Div , how to isolate each rendered component and add display none ?

is there a way to add the state that can trigger css / add css to certain react component?

import React, { Component } from 'react';
import all the component A, B AND C

class App extends Component {
   constructor(props) {
     super(props);
    this.state = {};
  }
  

  render() {
    return (
      <div>
               <Component A/>
               <Component B/>
              <Component C/>

      </div>
    );
  }
}

export default App;

mirror of a reverse numbers to be printed

Write a javascript program to print below pattern having numbers in pyramid form along with its mirror image
already tried
var rows = 7; // Number N

  //Print the pattern
  for ( i = 1; i <= rows; i++)    // outer loop
  {

        for ( j = 1; j < i; j++)    // inner loop 1
        {
                
           document.write("&nbsp;");  
        } 
        for ( j = i; j <= rows; j++)     // inner loop 2
                  {
                
            document.write(j +  " ");
                 
        } 
       document.write("<br>");
        
    }       

Implementing dueling with tensorflow.js

i am trying to implement dueling with tensorflow.js

I currently have this

      const x = tf.input({ shape: [this.state_size] });

      // a series of fully connected layer to estimate V(s)

      const y11 = tf.layers.dense({ units: this.number_nodes, activation: "relu" }).apply(x);
      const y12 = tf.layers.dense({ units: this.number_nodes, activation: "relu" }).apply(y11);
      const y13 = tf.layers.dense({ units: 1, activation: "linear" }).apply(y12);

      // a series of fully connected layer to estimate A(s,a)

      const y21 = tf.layers.dense({ units: this.number_nodes, activation: "relu" }).apply(x);
      const y22 = tf.layers.dense({ units: this.number_nodes, activation: "relu" }).apply(y21);
      const y23 = tf.layers.dense({ units: this.action_size, activation: "linear" }).apply(y22);

And i want to do something like this

const z = y13 + y23 - y23.mean(1, true)

But of course it doesn’t work, however this does work to sum the Symbolic Tensors y13 and y23

tf.layers.add().apply([y13, y23])

But i can’t find a way to substract these symbolic tensors and to get the mean of y23

Could someone explains me how to do that, i would appreciate a lot.
Thanks !

How to array target in a loop

I’ve recently had some help adding randomisation on my practice project app and now I’m trying to add the last functionality on it but I can’t get around.

I have this app that shuffles 7 objects from an array and presents them as a meal of the day for the entire week. For now, I’ve been able to have that same array logged 4 times and each of the 4 instances is shuffled from the other, but I’ve added other 3 arrays for a total of 4, and I’d like to have the app shuffling and logging each of those 4 arrays once.

English is not my primary language hopefully I’ve been clear enough.

const menu = {
    _meal: "",
    _price: 0,
    //Let set the new value of meal only if it's a string.
    set meal(mealToCheck) {
        if (typeof mealToCheck === "string") {
            return (this._meal = mealToCheck);
        }
    },
    //Let set the new value of price only if it's a number.
    set price(priceToCheck) {
        if (typeof priceToCheck === "number") {
            return (this._price = priceToCheck);
        }
    },
    //If both setters are true, then return a message using them, otherwise return message saying the values are wrong.
    get todaysSpecial() {
        if (this._meal && this._price) {
            return `'s Special is ${this._meal}, for just ${this._price}£!!`;
        } else {
            return "Meal and Price wasn't entered correctly!!";
        }
    }
};

//Array for the meal options and respective prices.
let meals = [
    {/*1*/name: "Pizza", price: 9},
    {/*2*/name: "Steak", price: 13},
    {/*3*/name: "Pie", price: 11},
    {/*4*/name: "Roast", price: 14},
    {/*5*/name: "Moussaka", price: 9},
    {/*6*/name: "Lasagne", price: 10},
    {/*7*/name: "Tacos", price: 9}
];
let meals1 = [
    {/*1*/name: "Omelette", price: 9},
    {/*2*/name: "Kebab", price: 13},
    {/*3*/name: "Ratatouille", price: 14},
    {/*4*/name: "Quiche", price: 9},
    {/*5*/name: "Burgers", price: 9},
    {/*6*/name: "Hot-Dogs", price: 10},
    {/*7*/name: "Burritos", price: 9}
];
let meals2 = [
    {/*1*/name: "Bourguignon", price: 10},
    {/*2*/name: "Stew", price: 14},
    {/*3*/name: "Fish&Chips", price: 15},
    {/*4*/name: "Fried Chicken", price: 10},
    {/*5*/name: "Cannelloni", price: 10},
    {/*6*/name: "Crepes", price: 11},
    {/*7*/name: "Gyros", price: 10}
];
let meals3 = [
    {/*1*/name: "Greek Salad", price: 11},
    {/*2*/name: "Seafood", price: 15},
    {/*3*/name: "Falafel", price: 16},
    {/*4*/name: "Wraps", price: 11},
    {/*5*/name: "Souvlaki", price: 11},
    {/*6*/name: "Shawarma", price: 12},
    {/*7*/name: "Quesadilla", price: 11}
]

//Shuffle function, creates two variables.
const shuffle = (array) => {
    let currentIndex = array.length,
        randomIndex;
    //The function starts from the array length and ends when reaches 0
    while (currentIndex !== 0) {
        //Assigns a random number to the variable, and each time it runs, it lowers the max number by 1.
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex--;
        //It swaps the current array element, with the one equivalent to the random number index.
        [array[currentIndex], array[randomIndex]] = [
            array[randomIndex],
            array[currentIndex]
        ];
    }
    return array;
}

let week = ["Week 1", "Week 2", "Week 3", "Week 4"];
const dayOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
// meals = shuffle(meals);

//I've created a for loop to go through the new shuffled array.

for (let w = 0; w < week.length; w++) {
    console.log("n" + week[w])
    meals = shuffle(meals);
    for (let i = 0; i < meals.length; i++) {
        //In here I'm saying that if the number of meals is equal to the week days, the weekly menu will be printed.
        if (meals.length === dayOfTheWeek.length) {
            menu.meal = meals[i].name;
            menu.price = meals[i].price;
            console.log(dayOfTheWeek[i] + menu.todaysSpecial);
            //If the meals are less, it will print how many need to be added.
        } else if (meals.length < dayOfTheWeek.length) {
            console.log(`You need to add ${Math.abs(meals.length - dayOfTheWeek.length)} meal(s) to the list!!!`)
            break;
            //If the meals are more, than it will print how many need to be removed.
        } else if (meals.length > dayOfTheWeek.length) {
            console.log(`You need to remove ${Math.abs(meals.length - dayOfTheWeek.length)} meal(s) from the list!!!`)
            break;
        }
    }
}

React Native: How to properly disable touchable feedback when performing swiping gestures?

Swiping gestures i.e. scrolling, pull to refresh, etc.

I’m pulling my hair out trying to make this work, I don’t understand how apps like Facebook accomplish this so well. It seems like such a simple thing to implement but I cannot for the life of me figure it out.

FYI: I’m using a FlatList with Touchable components inside. I’ve been messing around with the FlatList props (on scroll, on scroll begin drag, on scroll end drag, etc) as well as the Touchable props (on press, on press in, on press delay in, etc).

What I want: On the Facebook app, the MOMENT I begin scrolling or pulling to refresh, tap feedback is disabled so it doesn’t look like I clicked on a post. But at the same time the MOMENT I tap on a post, the tap feedback is super responsive. How is this done?

What I get: The moment I begin scrolling or pulling to refresh, the tap feedback is played even though I wanted to scroll/refresh. To fix this, I tried putting a pressDelayIn of 50ms. But now, quickly tapping on a post doesn’t play the feedback.

App.js

export default function App() {
  const [refreshing, setRefreshing] = useState(false);
  const [posts, setPosts] = useState([
    {
      id: 1,
      username: '@somedude',
      body: 'This is the best app ever, wow.',
    },
    {
      id: 2,
      username: '@doggo',
      body: 'Woof woof. Woof woof woof! Woof... Woof woof? Woof!',
    },
  ]);

  const onRefresh = () => {
    setRefreshing(true);
    setTimeout(() => setRefreshing(false), 1000);
  }

  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={posts}
        renderItem={({ item }) => <Post post={item} />}
        keyExtractor={item => item.id}
        refreshing={refreshing}
        onRefresh={onRefresh}
      />
    </SafeAreaView>
  );
}

Post.js

export const Post = ({ post }) => {
  return (
  <TouchableOpacity
    activeOpacity={0.5}
    onPress={() => console.log(`Press id ${post.id}`)}
  >
    <View style={styles.postPontainer}>
      <View style={{ marginBottom: 5 }}>
        <Text>{post.username}</Text>
      </View>
      <View style={styles.textContainer}>
        <Text>{post.body}</Text>
      </View>
    </View>
  </TouchableOpacity>
  );
}

Error message in console related to Mapbox api

I’m doing a project, using react js with tyscript
I’m facing an error after deploying the application on netlify, with the MapBox api, which when running returns the following message on the console, as described below and making it impossible to search for locations on the api map.:

“Failed to load resource: the server responded with a status of 401 (Unauthorized)”
// 20220606202752
// https://api.mapbox.com/geocoding/v5/mapbox.places/t.json?access_token=undefined

{
“message”: “Not Authorized – Invalid Token”
}

I use an environment variable for my Mapbox token and a variable for local access:

REACT_APP_ACESS_TOKEN_MAP_BOX=pk.
REACT_APP_API_URL=http://localhost:

Below is my tyscript code to access the environment variables and to access the Token MapBox.
One information is that the application to search for locations on maps locally is working, only when I deploy via netlify, it displays the message described above from “message”: “Not Authorized – Invalid Token”

import axios from "axios";
import { OrderPayload } from "./Orders/types";

const API_URL = process.env.REACT_APP_API_URL;
const mapboxToken = process.env.REACT_APP_ACESS_TOKEN_MAP_BOX;

export function fetchProducts (){
    return axios(`${API_URL}/products`)
}

export function fetchLocalMapBox(local: string){
    return axios (`https://api.mapbox.com/geocoding/v5/mapbox.places/${local}.json?access_token=${mapboxToken}`)
}

export function saveOrder(payload: OrderPayload) {
    return axios.post(`${API_URL}/orders`, payload);
}