using modules in typescript to push into array (please)

I need to retrieve a random number and store it in a variable, on .ts I have this:

import random from 'random'

export function rollDice(min:number, max:number) { 
let rollD = random.int((min = 1), (max = 6))
return rollD;

}

export function flipCoin(min:number, max:number) {
    let flipVal = random.int((min = 0), (max = 1))

if(flipVal == 0){
    console.log('heads')
}else{
    console.log('tails');
    }
return flipVal

}

console.log(rollDice(1,6))
console.log(flipCoin(0,1))

in the next .ts file I have this:

import {rollDice, flipCoin} from './index'

function flipResults(min: number, max: number) {
    var arr = [];
    for (var i=0, t=50; i<t; i++) {
        arr.push(Math.round(Math.random() * t))
    return `${arr}`;
    }
}

class flip{
    min: number;
    //max: number;
    results: number[] = [];

    constructor(min: number){
        this.min = min;
        //this.max = max;
    }

    flipCoin(...num: number[]){
        this.results.push(...num);
    }

    printArray(){
        console.log(`${this.results}`)
    }
}

var test = flipResults(0,50)

I need to print in the console 50 times the words, it prints but just the random numbers one at a time (3,45,33, etc).

Any help!?

Dynamically Loading Data Into Django Modal

I’ve been trying to implement a way to dynamically load information into a modal in order to do a quick preview for my ecommerce site. Any help would be appreciated, I’m not sure which direction I should head in. I tried to play with Javascript and creating an onclick function to refresh the div, but I have had no success so far. Please comment if any part of my question is unclear.

attached is a screenshot as to what is rendering on my end to get an idea of what I am trying to do.

https://gyazo.com/e0168c6d41a19071a95e8cecf84e37a9

store.html

    {% extends 'main.html' %}
    {% load static %}
    <!DOCTYPE html>
    <head>
        <link rel="stylesheet" href="{% static 'css/store.css' %}">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    </head>
    <body>
    {% block content %}
    <div class="p-5 text-center bg-image mt-4 mb-4" style="
    background-image: url('{% static 'images/ship.jpg' %}');
    background-size: auto;
    height: 400px;
    box-shadow: 1px 2px 2px;
    ">
    <div class="mask" style="background-color: rgba(0, 0, 0, 0.6);">
        <div class="d-flex justify-content-center align-items-center h-100">
            <div class="text-white">
                <h1 class="font-weight-bold mb-3" style="color: white;">Store</h1>
                <h2 class="font-weight-bold mb-3" style="color: white;">
                Welcome to our online shop, where our shipping quotes are listed below</h1>
                <h3 class="mb-3" style="color: white;">
                We ship a variety of items to fit your needs including cars, car parts, heavy duty boxes, clothes, canned goods and food, furniture, household items, freight containers and more.</h4>
                <a class= "btn btn-success mb-4" href="{% url 'about' %}" role="button">Click here to learn more</a>
            </div>
        </div>
    </div>
    </div>
    <div class="row mt-4 mb-4">
        {% for product in products %}
        <div class="col-lg-4">
            <img class="thumbnail" src="{{product.imageURL}}">
            <div class="box-element product">
                <h6><strong>{{product.name}}</strong></h6>
                <hr>
                <button type="button" class="btn btn-outline-success" data-toggle="modal" data-target="#myModal">View Details</button>

                <!-- Modal -->
                <div class="modal fade" id="myModal" role="dialog">
                    <div class="modal-dialog">
                    
                    <!-- Modal content-->
                    <div class="modal-content">
                        <div class="modal-header">
                            <h4 class="modal-title" id="modal-title">{{product.name}}</h4>
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        </div>
                        <div class="modal-body">
                            <img class="thumbnail" src="{{product.imageURL}}">
                        </div>
                        <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                    
                    </div>
                </div>
                {% if user.is_authenticated %}
                {% if product.specialObject == 0 %}
                <button  data-product={{product.id}} data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button>
                <h4 style="display: inline-block; float: right"><strong>${{product.price|floatformat:2}}</strong></h4>
                {% endif %}
                {% endif %}
            </div>
        </div>
        {% endfor %}
    </div>
    {% endblock content %}
    </body>
    </html>

models.py

class Product(models.Model):
    name = models.CharField(max_length=150, null=True)
    price = models.FloatField()
    image = models.ImageField(null=True, blank=True)
    specialObject = models.BooleanField(default=False)
    
    def __str__(self):
        return self.name

    @property
    def imageURL(self):
        try:
            url = self.image.url
        except:
            url = ''
        return url

How To Create An Employee Schedule Form With AngularJS 1.5.11

Summary

I’m having a hard time developing what I believe is a simple form using angularjs 1.5.11. It is supposed to be a multiple form single page UI which manages work schedules.

The final result should be the following:

  1. The first form asks if the user is creating a new work schedule or update an existing work schedule.
    1. If “new” is selected then a table form with all the days of the week is provided with a submit/reset button.
    2. If “update” is selected then the table form is prefilled with the current schedule data, but it can be edited.
  2. If submit is selected the table form fields can no longer be edited and the last form will appear which prompts the user to select the employees to associate with the schedule.
  3. There’s a final submit button which performs a POST call.

I am not experiencing any bugs or error messages. However, I am having a tough time digging through the angularjs documentation and I feel uncomfortable piecing this together. After completing a few courses through codeacademy, udemy, and following the angularjs tutorial on the official site, I still don’t feel that I am following best practices and rather than developing a bad solution I am seeking to see what the HTML and JS code should ultimately look like.

What I Tried

I provided a snippet below of what I currently have in place. I started off by completing #1 via using two radio buttons and addressed #2.1 via a table with time inputs.

The Code

var app = angular.module('myApp', []);

app.controller('MainController', ['$scope', function ($scope) {
    $scope.days = [
        'Monday',
        'Tuesday',
        'Wednesday',
        'Thursday',
        'Friday',
        'Saturday',
        'Sunday'
    ];
}]);
.schedRadio,
.period {
  list-style-type: none;
}

.h1,
.h3 {
  text-align: center;
}
<!doctype html>
<html ng-app="myApp">
<head>
   <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" />
   <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
</head>

<body ng-controller="MainController">
   <div class="container">
      <div class="row justify-content-center">
         <div class="col-8 justify-content-center">
            <h1>Employee Scheduler</h1>

            <form>
               <ul class="schedRadio">
                  <li>
                     <input type="radio" id="createSched" name="sched-radio" value="create"
                        ng-click="create_ = true; list_ = false;" />
                     <label for="createSched">Create a work schedule.</label>
                  </li>
                  <li>
                     <input type="radio" id="listSched" name="sched-radio" value="list"
                        ng-click="list_ = true; create_ = false;" />
                     <label for="listSched">Update an existing work schedule.</label>
                  </li>
               </ul>
            </form>
         </div>
      </div>
   </div>

   <div class="newSched container" ng-show="create_">
      <div class="row justify-content-center">
         <div class="col-8 justify-content-center">
            <h3>Create A New Work Schedule</h3>

            <table class="table">
               <thead>
                  <tr class="row">
                     <th></th>
                     <th>Start Time</th>
                     <th>End Time</th>
                  </tr>
               </thead>
               <tbody ng-repeat="day in days">
                  <tr class="row">
                     <th>{{ day }}</th>
                     <td>
                        <input type="time" id="{{ day | lowercase }}startTime" step="3600" />
                     </td>
                     <td>
                        <input type="time" id="{{ day | lowercase }}endTime" step="3600" />
                     </td>
                  </tr>
               </tbody>
            </table>
         </div>
      </div>
   </div>

   <div class="listSched" ng-show="list_">
      <h3>Listing all work schedules.</h3>
   </div>
</body>
</html>

Render update profile info from one page to another with javascript

I was writing a code to make profile updates and get the updated information from one page to another, using javascript but it did not work and I can’t figure out the reason
tried to make them both as a form but styling the first page became wired
any ideas?

the page I want to render to :

 <div class="col-lg-9 pt-4 pt-lg-0 content">
            <h3>Profile Information</h3>
            <div class="text-secondary">
              <h6 class="mb-0">Username</h6>
              <p id="username">Mohammed-Ismail</p>

              <h6 class="mb-0">Name</h6>
              <p id="name">Mohammed Ismail</p>

              <h6 class="mb-0">Email</h6>
              <p id="email">[email protected]</p>

              <h6 class="mb-0">Phone</h6>
              <p id="phone">(+249) 99 754 3333</p>

              <h6 class="mb-0">Location</h6>
              <p id="location">Khartoum</p>
            </div>

the page I want to render updated data from:

<form action="./about.html" method="post" class="update-form">
                        <!-- Form Group (username)-->
                        <div class="mb-3">
                            <label class="mb-1" for="inputUsername">Username (how your name will appear to other users on the site)</label>
                            <input class="form-control" id="inputUsername" type="text" placeholder="Enter your username" value="username">
                        </div>
                        <!-- Form Row-->
                        <div class="row gx-3 mb-3">
                            <!-- Form Group (first name)-->
                            <div class="col-md-6">
                                <label class="mb-1" for="inputFirstName">First name</label>
                                <input class="form-control" id="inputFirstName" type="text" placeholder="Enter your first name" value="Mohammed">
                            </div>
                            <!-- Form Group (last name)-->
                            <div class="col-md-6">
                                <label class="mb-1" for="inputLastName">Last name</label>
                                <input class="form-control" id="inputLastName" type="text" placeholder="Enter your last name" value="Ismail">
                            </div>
                        </div>
                        <!-- Form Row  -->
                        <div class="row gx-3 mb-3">
                            <div class="col-md-6">
                                <label class="mb-1" for="inputPhone">Phone number</label>
                                <input class="form-control" id="inputPhone" type="tel" placeholder="Enter your phone number" value="(+249) 99 754 3333">
                            </div>
                            <!-- Form Group (location)-->
                            <div class="col-md-6">
                                <label class="mb-1" for="inputLocation">Location</label>
                                <input class="form-control" id="inputLocation" type="text" placeholder="Enter your location" value="Khartoum">
                            </div>
                        </div>
                        <!-- Form Group (email address)-->
                        <div class="mb-3">
                            <label class="mb-1" for="inputEmailAddress">Email address</label>
                            <input class="form-control" id="inputEmailAddress" type="email" placeholder="Enter your email address" value="[email protected]">
                        </div>
                       
                       
                        <!-- Save changes button-->
                        <button class="get-started-btn mt-3 mb-3" type="button" id="changes-btn">Save changes</button>
                    </form>

Javascript code:

 /* render profile changes to profile page */
    document.getElementById("changes-btn").onclick = function () {
      
      window.addEventListener("load", () => {
        const params = (new URL(document.location)).searchParams;
        const username = params.get('inputUsername');
        const first = params.get('inputFirstName');
        const last = params.get('inputLastName');
        const phone = params.get('inputPhone');
        const email = params.get('inputEmailAddress');
        const location = params.get('inputLocation');
  
        document.getElementById('username').innerHTML = username;
        document.getElementById('name').innerHTML = first;
        document.getElementById('name').innerHTML = last;
        document.getElementById('Email').innerHTML = email;
        document.getElementById('phone').innerHTML = phone;
        document.getElementById('location').innerHTML =location;
        
      })
    }

vuejs push checkbox values to URL

I am building a filter with vue js3. I want to push the user selected values to URL and I am watching changes in watch

My checkbox are not working, I have an array and I want to loop all course and make dynamic filter and push its value to URL.
My select options are working and it push values to Url, My Url is like this:
http://localhost:8080/filter?sort=latest when i choose latest from Url

I have few courses in array. I want to loop it and make a dynamic checkbox
and when user checks it, i want to push it value to URL.
I need this type of URL:
http://localhost:8080/filter?sort=latest&course=php&course=js when user select latest, php and js options

So far I have done

    <h3>Choose multiple</h3>
        <div v-for="(name,index) in courses" :key="index">
            <input type="checkbox" v-model="filter.course" >{{name}}
       
       </div>

        <select  v-model="filter.sort">
            <option value="">Sort by</option>
            <option value="latest">Latest</option>
            <option value="popular">Popular</option>
        </select>
  
    </form>
</template>

<script>
export default {
    data(){
        return{

            courses:['PHP','Python','JS'],

            filter: {
                sort:this.$route.query.sort,
                course:''
    
           }
        }
    },

    watch:{
        filter:{
            handler(){
            this.$router.push({
                query:this.filter
            })
            },
            deep:true
        }
    }
   
}
</script>

Only the problem here is i am not able to push checkbox values in the URL

webkitSpeechRecognition aborting and not listening to anything unless I restart Chrome

I’ve started to make a little speech recognition app

let loading = document.getElementById('loading')
let main = document.getElementById('main')
let speech = new webkitSpeechRecognition();

let isLoading = true

speech.addEventListener('error',(e)=>{
  switch(e.error){
    case 'not-allowed':
      // Visual code here left out
      break;
    default:
      console.error(e)
      break;
  }
})

speech.addEventListener('end',()=>{
  speech.start();
})

function parseResult(result){
  if(result.type == 'result'){
    let text = result.results[result.resultIndex][0].transcript
    
     // Visual code here left out
    
  }
}

speech.onresult = parseResult;
speech.continuous = true;
speech.start();

And it works well once, then once I refresh it throws this every 5 seconds or so:

This is fixed by going to chrome://restart, but I would like it if users didn’t have to restart their entire browser every time they went to the app.

Any idea of what’s happening?

What is the easiest way to create an editable string, store in a variable, and re-display in multiple places using a MDX based static site generator?

Problem Statement:
I want to create a website with beginner friendly guides of how to do some basic bash and Kubernetes automation. (Beginner friendly as in Explanations + copy paste-able code snippets).

I currently use logic like this, when I write how to guides:

set +o history #turn off shell history
export REGISTRY_USERNAME=<REPLACE_ME>
export REGISTRY_PASSWORD=<REPLACE_ME>
echo $REGISTRY_PASSWORD | docker login myregistry.local --username $REGISTRY_USERNAME --password-stdin
set -o history #turn on shell history

The problem with this approach is it falls victim to the universal truth of “Humans don’t read they skim,” and when I watch users follow my how to guides I find the approach is surprising prone to human error, especially to new users that are sometimes new to even terminal basics, and don’t realize things like KEY=VALUE without spaces is important.

Desired State:
One day I discovered this page and was like OMG that’s an amazing User Experience! https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity#verify_the_setup

In case the webpage changes in the future this is what it looks like:
screen snippet

This functionality is such a good user experience!

  1. It’s dead obvious that a user can edit that variable. (friendly to humans who skim instead of read)
  2. When you edit it on one spot on the page, it updates it in multiple locations on the page.
  3. You can even switch kubectl to yaml and it generates a yaml via KISS string variable substitution.
  4. Best part is the copy paste-able command loads the copy paste-able hard coded values, which is extremely user friendly, because it’s mistake proof. (with my method best case scenario someone copy pastes into a document, edits it, then re-copy/pastes into terminal.)

I want to reproduce this functionality so I can make mistake proof how to guides.

Constraints by which I wish to achieve desired state:
I’ve been able to successfully use Docusarus, a static site generator, to make a secure website that I can host for free using serverless hosting solutions like Cloudflare’s pages.dev or a CDN. Currently I’m planning to generate the majority of webpages from markdown files, like how_to_x.md. The thing is Docusarus supports MDX, an it’s possible to create a file called how_to_x.mdx, my understanding is I can write in 95% markdown, and then mix a minimum amount of JavaScript, and it’ll convert it to JSX, which is some kind of javascript standard, which should make it plausible for me to implement functionality similar to what exists on google cloud’s docs.

Note: I’ve done basic Java, Python, and Bash programming before. I’ve also been able to use npm to install Docusaurus plugins. But Javascript and frontend development is a different beast, and I’d rather not learn it, because it’s a rabbit hole, and I don’t want that rabbit hole to distract me from continuing to explore the depths of the rabbit hole that is Kubernetes and push button end to end automated infrastructure as code. So I’m looking for someone whose familiar with the Javascript ecosystem to point me in the direction of a KISS solution that works with a static hosting solution.

Things I’ve looked into so far:

  • I’ve read all of Docusaurus’ docs and saw that rehype and remark MDX plugins exist, but none of them looked that useful.
  • I’ve tried to view the page source of the google doc, but couldn’t figure out how the magic was working.
  • I don’t think google’s documentation website’s source code is public like Rancher’s is, I found this page while trying o see if something existed https://developers.google.com/style/placeholders, but it seems to be specific to contributors of their website and I suspect their website has some magic sauce that makes this work because when I copy paste the examples into HTML Javascript playground / fast feedback loop websites like these:

It doesn’t work the same.

Note: When answering if possible, I would appreciate if someone could give a KISS short self contained example that works using a playground site like jsfiddle. Pointers in the right direction of libraries that can make this easy and work within constraints would also be welcome (Javascript is a stupidly large ecosystem.)

modifying html with user script to modify a input form’s max value [duplicate]

i want to make a user script that changes the max value of
a input form

<div>
      <label>Time limit (in minutes, max 120)</label>
      <input type="number" name="max_time" value="60" min="1" max="120" required="">
    </div>

the value im after is 120
and the userscript should only be able to modify that value

the question When to use setAttribute vs .attribute= in JavaScript?
is not useful here since my question is about modifying html with user scripts

Line 23:22: ‘FacebookOutlineed’ is not defined react/jsx-no-undef

import react from ‘react’
import {googleOuutlineed, FacebookOutlined } from ‘@ant-design/icons’

const Login =() => {
return (

welcome to messengers

            <div
            className="login-button google"

            >
                <googleOutlineed /> sign in with gooogle
            </div>

            <br /> <br /> 

            <div
            className="login-button facebook"

            >
                <FacebookOutlineed /> sign in with facebook
            </div>
        </div>
    </div>

);

}

export default Login;

How to render function from string in vue directive?

I’m trying to take a function from an object array and run it in a @click event on a DOM element. The only way I found to do this was by saving the function as a string inside the object, and render it with new Function:

const func = 'editor.chain().focus().toggleBold().run()'

const renderFunction = new Function('return ' + '(func) => { return func }')()

console.log(renderFunction(func))

Output:

editor.chain().focus().toggleBold().run()

This seems to return func correctly inside the script setup tags, which is the function I want to run inside the @click directive but it doesn’t seem to work inside the directive. When I click on this icon:

<fa class="icon" 
v-for="(button, key) in tool.buttons" 
:key="key" 
type="button" 
:icon="[ 'fas', button.icon ]" 
:title="button.text" 
@click="renderFunction('editor.chain().focus().toggleBold().run()')"
></fa>

Nothing happens and no error is shown. This function should actually set the font inside tiptap rich text editor to bold. Adding console.log to renderFunction:

const renderFunction = new Function('return ' + '(func) => { return console.log(func) }')()

returns func as a string upon click so at least the string value seems to be sent to the function correctly, but why is the function not run inside the directive?

How can I create a space line (like a br) when user clicks on button?

I need a javascript function or really anything so when the user put names in the input type text, it puts the text on a paragraph below #final and so on continuosly adding a space whenever the user clicks the button.

        <p>Nombre</p>
        <input type="text" id="nombre">
        <br>
        <p>Monto</p>
        <input type="number" id="monto">
        <br>
        <button onclick="ir()">Enviar</button>
        <br>
        <p>Total: <span id="final"></span> </p>
        <div id="total">
        </div>
        <p>A cada uno le toca aportar: <span id="aporte"></span></p>
     </div>
    </html>
    
    
    function ir() {
        let nombre = document.getElementById("nombre").value;
        let monto = document.getElementById("monto").value;
        let total = document.getElementById("total");
        let final = document.getElementById("final");
        let aporte = document.getElementById("aporte");
    
        for (i = 0; i < monto; i++) {
            total.innerText = ` ${nombre} : ${monto}`; 
        };
    
        if (total > 0) {
            monto + monto
        }
    
        final.innerHTML = `${monto}`;
        aporte.innerHTML = `${monto}`;
    };

How can I do it?

Does the parent useEffect trigger if the parent’s state is changed in the child component? [duplicate]

I’m trying to pass the setter of the parent component to the child component but when I invoked the setter it didn’t trigger the parent’s useEffect.

const Product = ({ product }) => {
return (
    <div className="border border-black rounded border-2 p-5 flex m-5">
        <div className="w-1/3">
          <p>Name: <span>{product.name}</span></p>
        </div>
        <div className="">
          <p>Price: <span>{product.price}</span></p>
        </div>
    </div>
 )
}

const CreateForm = ({addProduct}) => {
     //renders a POST form for adding product when submit is clicked it triggers 
     //addProduct
}

const Main () => {
   const [products, setProducts] = useState([])
   const fetchData () => {
      fetch("get/products")
      .then(response => response.json())
      .then(data => setProducts(data))

   }

   useEffect(() => {
      console.log("useEffect triggered!")
      fetchData();
   }, [])
   
   const addProduct = (product) => {
      const updatedProducts = [...products, product]
      setProducts(updatedProducts)
   }

   const data = products.map(product => <Product product={product}/>)

   return (
    <div className="m-10">
      <CreateForm addProduct={addProduct}/>

      {data}
    </div>
    )
}

When the submit button is clicked it performs a POST requests creating a product and the addProduct is invoked