function mapCharAndSum(N,K,str)

Map Characters & Sum Ended
Description

You are given a number stored in a variable with the nameN

You are also, given a string, whose length is stored in a variable with the nameK, and the string is stored in a variable with the namestr

You have to map all lower case English characters, starting from the value stored inN.

For example, if the value stored inN = 30, then the mapping of the characters will be as follows

a-30
b-31
c-32
d-33
e-34
f-35
g-36
h-37
i-38
j-39
k-40
l-41
m-42
n-43
o-44
p-45
q-46
r-47
s-48
t-49
u-50
v-51
w-52
x-53
y-54
z-55
Finally, you have to print the sum of all the characters, present in the stringstr, according to the values mapped above

For example, if the value stored instr = “abc”, then the required output will be

30 + 31 + 32 = 93, which is the required output

Input
The first line of the input contains the value stored inN

The second line of the input contains the value stored inK

The last line of the input contains the value stored in thestr

Output
Print the sum of characters, according to the values mapped, as shown in the problem statement

Sample Input 1

30
3
abc
Sample Output 1

93
Hint

In the sample test case, the value stored inN = 30, then the mapping of the characters will be as follows

a-30
b-31
c-32
d-33
e-34
f-35
g-36
h-37
i-38
j-39
k-40
l-41
m-42
n-43
o-44
p-45
q-46
r-47
s-48
t-49
u-50
v-51
w-52
x-53
y-54
z-55
Finally, you have to print the sum of all the characters, present in the stringstr, according to the values mapped above

For example, if the value stored instr = “abc”, then the required output will be

30 + 31 + 32 = 93, which is the required output

Check whether string contains other than specific word

I need to check whether a string contains other than the specified words/sentence (javascript), it will return true if:

  • it contains an alphabets, except this phrase: ANOTHER CMD
  • it contains other than specified multiple sequence of numbers for example: ["8809 8805", "8806 8807"] (the numbers are examples I should be able to test the string for any array of numbers)

Thank you!

How can I make a div follow my mouse inside of a circle?

What would be the best approach to have this face always point towards my mouse? The tricky part for me has been having it skew and scale as if it’s rotating around a sphere. (I turned it into a CSS animation to show what I would like it to do)

Thank you so much for your help, and I hope that you have a great day!

const head = document.querySelector('.head');
const face = document.querySelector('.face');

addEventListener('mousemove', e => {
  // face follows cursor
  // rotates and scales accordingly
});
*,
*::before,
*::after {
  box-sizing: border-box;
}

@keyframes move {
  0% {
    transform: translateX(0) translateY(0px) rotate3d(0, 0, 0, 45deg) scale(1);
  }
  25% {
    transform: translateX(150px) translateY(0px) rotate3d(0, 10, 0, 45deg) scale(0.9);
  }
  50% {
    transform: translateX(0px) translateY(-150px) rotate3d(10, 0, 0, 45deg) scale(0.9);
  }
  75% {
    transform: translateX(-100px) translateY(100px) rotate3d(10, 10, 0, 45deg) scale(0.9);
  }
}

.head {
  width: 500px;
  height: 500px;
  border-radius: 50%;
  background-image: linear-gradient(120deg, yellow, #c47400);
  box-shadow: inset -5px -5px 20px yellow;
  position: relative;
}

.head::before {
  content: "";
  position: absolute;
  left: 75px;
  top: 75px;
  border-radius: 50%;
  width: 150px;
  height: 150px;
  background-color: white;
  opacity: 0.35;
  filter: blur(45px)
}

.eye {
  width: 65px;
  height: 100px;
  margin: 10px;
  border-radius: 100px;
  display: inline-block;
  background-color: #8a6b0c;
}

.mouth {
  width: 175px;
  height: 50px;
  background-color: #8a6b0c;
  border-radius: 100px;
}

.container {
  width: 500px;
  height: 500px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.face {
  display: inline-block;
  animation: move 4s ease infinite;
}
<div>
  <div class="head">
    <div class="container">
      <div class="face">
        <div class="eye"></div>
        <div class="eye"></div>
        <div class="mouth"></div>
      </div>
    </div>
  </div>
</div>

dispatch function is undefiened while using useContext

I have created a login system in react and to store user info I am using react context API I have an auth context provider file where I have kept all the state and state providers and I have created another file AuthReducer which has the reducer and AuthAction which contains the actions of the reducers.

I have also created a file that has a function named loginCall to call the dispatch function.
and I am using this function in my react component to call the dispatch function but when I call loginCall I am getting dispatch is not function error other values from the context provider are correct just the dispatch function is coming undefined.

please if anyone have any fix let me know

my authContext

import { createContext, useEffect, useReducer } from "react";
import AuthReducer from "./AuthReducer";

const INITIAL_STATE = {
  user: JSON.parse(localStorage.getItem("user")) || null,
  isFetching: false,
  error: false,
};

export const AuthContext = createContext(INITIAL_STATE);
export const AuthContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(AuthReducer, INITIAL_STATE);

  useEffect(() => {
    localStorage.setItem("user", JSON.stringify(state.user));
  }, [state.user]);

  return (
    <AuthContext.Provider
      value={{
        user: state.user,
        isFetching: state.isFetching,
        error: state.error,
        dispatch,
      }}
    >
      {{children}}
    </AuthContext.Provider>
  );
};

my loginCall function is separate file

import axios from "axios";

export const loginCall = async (userCredential, dispatch) => {
  dispatch({ type: "LOGIN_START" });
  try {
    const res = await axios.post("/auth/login", userCredential);
    dispatch({ type: "LOGIN_SUCCESS", payload: res.data });
  } catch (err) {
    dispatch({ type: "LOGIN_FAILURE", payload: err });
  }
};

any the react component where I am using this loginCall and dispatch function

export default function Login() {
  const email = useRef();
  const password = useRef();
  const { user, isFetching, error, dispatch } = useContext(AuthContext);

  const handleClick = (e) => {
    e.preventDefault();
    console.log({ user, isFetching, error, dispatch });
    dispatch({ type: "LOGIN_START" });
    

    e.preventDefault();
    loginCall(
      { email: email.current.value, password: password.current.value },
      dispatch
    );
  };
 return(
            <>
              .....
            //normal component 
            </>
)

when I console log the { user, isFetching, error, dispatch }
I get dispatch: undefined, error: false, isFetching: false, user: null

the other values are correct the dispatch function is coming null.

update database SQL using a form with javascript/html

i am stuck on making a form which updates existing data in a database when submitted. the user presses the button “edit” which will send them to a form that has the current data listed. the user can then change the data and press submit which will update the database to the new data the user inputted.

i have made a form to input the data & the table it lists the data in:

<!doctype html>
<html>
<head>
</head>
<body>
   <form action="/editing" method="POST">
   <label for="deviceName">Name of device:</label>
   <input id="deviceName" type="text" name="deviceName"/>

   <label for="deviceType">Type of device:</label>
   <input id="deviceType" type="text" name="deviceType"/>

   <label for="deviceStatus">Status: On/off:</label>
   <select id="deviceStatus" name="deviceStatus" value="on/off">
     <option value="On">On</option>
     <option value="Off">Off</option>
   </select>
   <input type="submit" value="Submit">
   </form>
</body>
</html>
   <table>
       <thead>
       <th>Device id</th>
       <th>Device Name</th>
       <th>Status</th>
       </thead>
       <tbody>
       <% availableDevices.forEach(function(device){ %>
       <tr>
           <td><%= device.id %></td>
           <td><%=device.deviceName %></td>
           <td><%=device.deviceStatus%></td>
           <td><a href="/edit/<%=device.id%>">Edit</a></td>
           <td><a href="/delete/<%=device.id%>">Delete</a></td>
       </tr>
       <% }) %>
       </tbody>
   </table>

preview looks liek this list page

this is my main.js page where i call get:

       app.get('/edit/:id', function(req, res, next){

           var id = req.params.id;
           var query = `SELECT * FROM devices WHERE id = "${id}"`;
           db.query(query, function(err, data){
       
               res.render("editing.html"); //MOVE TO THE EDIT DEVICE FORM
       
           });
       
       });
           app.post('/edit/:id', function(req, res, next){

           var id = req.params.id;
           var deviceName = req.body.deviceName;
           var deviceType = req.body.deviceType;
           var deviceStatus = req.body.deviceStatus;
           var query =   `
           UPDATE devices
           SET deviceName = "${deviceName}",
           deviceType = "${deviceType}",
           deviceStatus = "${deviceStatus}",
           WHERE id = "${id}"
           ` ;
       
           database.query(query, function(err, data){
       
               if(err)
               {
                   throw err;
               }
               else
               {
                   response.redirect('/list');
               }
       
           });
       
       });

how can i write the code so when i press the edit button on the row of device i want to update (which all have an id) to have the form not be blank and have the existing data shown on the form.

press edit button on id 1 -> redirects to form with existing data filling in the form (isn’t blank)

Typescript overloading an HOC

I’m trying to implement an overloaded HOC, the interface looks like this:

interface FallbackProps {
    error: Error;
    resetErrorBoundary: (...args: Array<unknown>) => void;
}

type Hoc<P> = {
    (fallback: ComponentType<FallbackProps>): (
        WrappedComponent: ComponentType<P>,
    ) => (props: P) => JSX.Element;

    (WrappedComponent: ComponentType<P>): (props: P) => JSX.Element;
};

Which can be called like this:


hoc(Component);
hoc(({ error }) => <div>custom error fallback</div>)(Component);

Uncaught TypeError: data.find is not a function

I am trying to convert the model instances into a JSON object and then according to the value selected in the dropdown menu, I want to assign its amount to the line_one_unit_price text field in the form.

Javascript code:

{{ data|json_script:"hello-data" }}
<script type="text/javascript">
    const data = JSON.parse(document.getElementById('hello-data').textContent);

    document.getElementById('id_line_one').onchange = function(event){
    let elementInData = data.find(() => item.pk == event.target.value);
    document.getElementById('id_line_one_unit_price').value = elementInData && elementInData.amount ? elementInData.amount : 0;
};

</script>

I guess, I am getting the error at data.find because .find is used on an array whereas the constant data is not an array? How do I convert that JSON object into an array? how do I assign the amount of the title selected in the forms to the line_one_unit_price?

ss

When I click some title from the dropdown, I want the amount to be displayed in the Unit Price.

views.py:

def add_invoice(request):
  form = InvoiceForm(request.POST or None)
  data = serializers.serialize("json", Inventory.objects.all())
  total_invoices = Invoice.objects.count()
  queryset = Invoice.objects.order_by('-invoice_date')[:6]

  if form.is_valid():
    form.save()
    messages.success(request, 'Successfully Saved')
    return redirect('/invoice/list_invoice')
  context = {
    "form": form,
    "title": "New Invoice",
    "total_invoices": total_invoices,
    "queryset": queryset,
    "data": data,
  }
  return render(request, "entry.html", context)

models.py:

class Inventory(models.Model):
  product_number = models.IntegerField(primary_key=True)
  product = models.TextField(max_length=3000, default='', blank=True, null=True)
  title = models.CharField('Title', max_length=120, default='', blank=True, unique=True)
  amount = models.IntegerField('Unit Price', default=0, blank=True, null=True)

  def __str__(self):
    return self.title

Thanks.

Are parameters of JavaScript functions declared as var?

Are parameters of JavaScript functions declared as var?

  1. reassignment
    The keywords for declaring JavaScript variables are 1) var, 2) let, 3) const.
    I thought it was var or let because parameters can be reassigned.
function test1(a) {
    a = 3 // reassignment
    console.log('a', a) // 3
}
test1(3)
  1. redeclare – var

If declared with let, redeclaration is not possible.

Since redeclaration is possible inside a function, it is assumed that the parameter is declared as var.

function test1(a) {
    var a = 1 // redeclare
}
test1(3)

How do I save patterns automatically in p5.js?

So, I’ve been playing around with codes to generate patterns. Now I’m getting decent patterns right now but I’d like to save them to compare them with another version. Currently, patterns keep generating themselves when I play it on Processing.

My question is how do I automatically save like x number of patterns in Processing?

Functional way to find item in array from a previous index

I have an array of objects

Something like

const items: item[] = [
    {id: 1, type: 'parent'},
    {id: 2, type: 'parent'},
    {id: 3, type: 'child'},
    {id: 4, type: 'child'},
]

Now I want to make a function that if given an item of type child it returns the first preceding row with type parent.

I want to do this a more functional way for education purposes. I’ve done this imperatively as such (pseudo-code, but should work):

function getParentItem(item: item)
    let startIndex = items.indexOf(item)
    let item = null
    while(!item){
        if(items[startIndex].type == "parent"){
            item = items[startIndex]
        }
        startIndex--
    }
    return item
}
getParentItem({id: 4, type:'child'}) //Should return {id: 2, type: 'parent'}

What would be a good, immutable, functional way to do this?

How to make /(movie) for Netflix type site

I’m making a Netflix type site and for movies I want to make like a system (all html CSS and js) where on the movie select I can add an image name description rating length genre and tags. So what I want is to save time by creating a simple page with placeholder images and text on like web.com/movie name and takes data from the movie select (name description rating genre length and tags) and creates the page for me like for example the movie name is hello then I put on movie select hello, 1hour, romance, description and it just makes the page web.com/movies/hello and all I have to do is create the simple movie select screen. Hopefully not too complicated put shortly: I make details on a /movieselect and it makes a custom page for the movie /movie/hello. Thank you

How to set sensitivity header in eml file for Outlook?

I’m trying to write an email via a dynamically created eml file with JavaScript.

I’ve modified this code to my needs from another SO answer but I’m not sure why Sensitivity and Priority headers are not working when I open the file with Outlook.
In Outlook I see differently named sensitivity levels compared to rfc2156 (company set or Outlook?): “public”, “internal”, “confidential”, and “strictly confidential”. Not sure if that’s important.

I’ve tried all possible combinations, with or without double quotes, etc but so far nothing seems to set either headers. I can see them If I read the eml in text editor but when I open the file in Outlook I just see the default settings being applied.

I’m using Outlook version 2102.

const emailBody = "<html><body><b>hello</b> world</body></html>";

let emlHeader = "data:message/rfc822 eml;charset=utf-8,";
emlHeader += `From: [email protected]`;
emlHeader += `Subject: Sensitive messagen`;
emlHeader += `To: [email protected]`;
emlHeader += `Bcc: [email protected]`;
emlHeader += `Date: Sun, 10 Jul 2022 03:54:14 +0000n`;
emlHeader += "Priority: Urgentn";
emlHeader += "Sensitivity: Privaten";
emlHeader += "X-Unsent: 1n";

const emlString = `${emlHeader}nn${emailBody}`;

const emlContent = encodeURI(emlString); //encode spaces etc like an url
const a = document.createElement("a"); //make a link in document
a.href = emlContent;
a.id = "fileLink";
a.download = "filename.eml";
a.style = "display:none;"; // hidden link
document.body.appendChild(a);
document.getElementById("fileLink").click(); //click the link

Generate Parentheses… Javascript vs Java

I’m solving Generate Parentheses from LeetCode… and I have seen the solution provided wich was implemented on Java… and there is another with Python. I almost copied the code but with Javascript and I don’t understand why it doesn’t work:

  var generateParenthesis = function(n) {
     let sol = []
     generateParenthesisAux(sol, [], 0, 0, n)
     return sol
  };

  var generateParenthesisAux = function(listAnswer, current, open,  close, max) {
     if(current.length == max*2) listAnswer.push(current.join(''))
     else{
        if(open < max){
           current.push("(")
           generateParenthesisAux(listAnswer, current, open + 1, close, max)
           current.pop()
        }
        if(close < max){
           current.push(")")
           generateParenthesisAux(listAnswer, current, open, close + 1, max)
           current.pop()
        }
     }
  };

It’s generating more than the exact number of correct combinations.

This is the code in Java from LeetCode:

class Solution {

   public List<String> generateParenthesis( int n ) {
      List<String> ans = new ArrayList();
      backtrack( ans, new StringBuilder(), 0, 0, n );
      return ans;
   }

   public void backtrack( List<String> ans, StringBuilder cur, int open, int close, int max ) {
      if( cur.length() == max * 2 ) {
         ans.add( cur.toString() );
         return;
      }

      if( open < max ) {
         cur.append( "(" );
         backtrack( ans, cur, open + 1, close, max );
         cur.deleteCharAt( cur.length() - 1 );
      }
      if( close < open ) {
         cur.append( ")" );
         backtrack( ans, cur, open, close + 1, max );
         cur.deleteCharAt( cur.length() - 1 );
      }
   }
}

How do I fix: node command not found? (VSCODE)

I’m trying to load two js files to another js file and I used jquery using CDN.

This is my code for the heading in html:

<script src="https://code.jquery.com/jquery-3.6.0.min.js" 
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>

this is the code for the first js file:

const countries = ["Philippines", "Australia", "Italy", "Norway", "Japan", "Israel"]

this is the code for the second js file:

const webTechs = ['Javascript', 'Python', 'SQL', 'Go', 'Native']

the code in script (I’m loading the country(js) file first):

 $.getScript("country.js", function() {
    console.log(countries)
});

yet when i try to load the two external files, first in tech(j)s file it says:

     const webTechs = ['Javascript', 'Python', 'SQL', 'Go', 'Native']
    /bin/sh: line 1: node: command not found

I’d appreciate your help, thank you.