Paypal Rest Api returns 401 Unauthorized when i try to get OAuth2 token using php file_get_contents() in localhost with sandbox , but works in ajax

Paypal Rest Api returns 401 Unauthorized when i try to get OAuth2 token using php file_get_contents() in localhost with sandbox

    $client_id = env('PAYBAL_CLIENT');
    $client_secret = env('PAYPAL_SECRET');

    $opts = array('http' =>
        array(
            'method' => 'POST',
            "headers" => [
                "Content-Type" => "application/x-www-form-urlencoded",
                "Authorization" => "Basic " . base64_encode("$client_id:$client_secret")
            ],
            'body' => "{'grant_type' : 'client_credentials'}"
        )
    );

    $context = stream_context_create($opts);

    $url = "https://api-m.sandbox.paypal.com/v1/oauth2/token";

    $result = file_get_contents($url, false, $context);

the same requeste worked fine with me in ajax

$.ajax(
{
    url: "https://api-m.sandbox.paypal.com/v1/oauth2/token",
    type:"post",
    headers:{
        "Authorization": "Basic 'XXXbase64_encodedXXX'"
        "Content-Type": "application/x-www-form-urlencoded"
    },
    data:{
        "grant_type":"client_credentials"
    },
    success:function (data){
        console.log(data);
    },
    complete:function (data,status){
        console.log(status);
    }
}

);

Setting the minimum and maximum value and creating an array with a sequence of X values between them

Using interactive calculation (circular reference) in Google Sheets configs to be able to generate a sequence of 100 numbers that follow a pattern of growth defining the minimum value and the maximum value, I do it like this:

B1 → 0.01

B2 → =ARRAYFORMULA(VALUE(TEXT(INDIRECT("B"&
 MAX(IF(B3:B<>"", ROW(B3:B), )))+SORT(ROW(INDIRECT("B1:B"&
 MAX(IF(B3:B<>"", ROW(B3:B), ))-2)), 1, 0)*(B1-INDIRECT("B"&
 MAX(IF(B3:B<>"", ROW(B3:B), ))))/(
 MAX(IF(B3:B<>"", ROW(B3:B), ))-1),"0.00")))

B100 → 35.70

To remove these calculations from the spreadsheet, I’m trying to convert the idea in Google Apps Script in order to send the values to the spreadsheet.

Sp I’m trying to generate an array with that same idea → a total of 100 numbers where the minimum and maximum are defined by me and the other 98 numbers must be between the minimum and the maximum keeping a growing pattern:

[[0.01],
[...],
[...],
[...],
[35.70]]

In my attempts I tried to generate like this:

function between() {
  const min = 0.01;
  const max = 35.70;
  const total = 100;
  const seq = (min + max) / total;
  const lst = [[min]];
  let i = 1;
  while (i <= 98) {
    lst.push([(seq*i).toFixed(2)])
    i++
  }
  lst.push([max])
  SpreadsheetApp.getActive().getSheetByName('data').getRange('A1:A100').setValues(lst);
}

But mathematically it doesn’t have an exact pattern of the expected values, what should I adjust to get the correct result?

Parsed JSON data appearing as undefined in the console? [duplicate]

I used the fetch api to take the json data from the api that I linked in the code. I then tried to parse the data and log the quote from the parsed data in the console.

fetch("https://api.breakingbadquotes.xyz/v1/quotes")
.then(data => data.json())
.then(data => {
    console.log(JSON.parse(data.quote));
});

This came up with the error “unexpected token o in JSON at position 1” in the console, meaning that the data is already parsed. So, logically, I removed the JSON.parse method from line 4 expecting the issue to be resolved.

fetch("https://api.breakingbadquotes.xyz/v1/quotes")
.then(data => data.json())
.then(data => {
    console.log(data.quote);
});

However, this simply appeared as undefined in the console, meaning that data has not been parsed. Can anyone explain what the issue here is exactly? I apologize in advance if I am missing something obvious, I am still a beginner to javascript and programming as a whole. Thank you!

Possible to use an object property as a method’s argument stackoverflow

Basically I am trying to create an object property that will dynamically create an array based on the constructor. The following works if I remove the constructor and simply set testArray.length to some integer. But stops working when I try setting length with a constructor.

class TestArray {
  constructor(length) {
    this.length = length;
  }

  buildArray = function(length) {
    let array = [];
    for (let i = length; i > 0; i--) {
      array.push("_");
    }
    return array;
  }

  array = this.buildArray(this.length);
}

let testArray = new TestArray(2);
console.log(testArray.array);


let testArray2 = new TestArray(2);
console.log(testArray2.array);

//[] is logged. Desired out put is ['_', '_']

Do I have syntax issue or a logic issue? Is there a plain better way to do this?

Django Forms and Mapbox how to save data when page is refreshed

I have been struggling with this problem for a long time now and I cannot seem to find any problem similar to it with a solution. Basically the project that I am working on involves use of the Mapbox framework which displays a map of Yellowstone national park. The user is then able to click on an upload picture button which sets a boolean value either “true” or “false” for if they want to upload a picture based where on the map they click next. If this value was true and the user clicks on a spot on the map, the coordinates of the cursor is then used to place a marker with a popup containing a Django form. This form model can then be filled out the user can press submit.

default map img

filling out post on map img

Ideally I would like the submit button to just place to filled out form within the popup and also keep the marker there. Right now whenever I hit submit, the whole page gets refreshed and the map get re-loaded and all modifications made simply disappear. The filled out form that was submitted does get added to my database though.

Home page view code

def homePage(request):
posts = Post.objects.all()
form = PostForm()
if request.method == 'POST':
    form = PostForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect('home')

context = {'posts': posts, 'form': form}
return render(request, 'home.html', context)

Post model code

from django.forms import ModelForm
from .models import Post 

class PostForm(ModelForm):
    class Meta:
        model = Post
        fields = '__all__'

Form model code

class Post(models.Model):
    animal = models.CharField(max_length=32, choices=ANIMALS, default=BISON)
    description = models.TextField(null=True, blank=True)

    def __str__(self):
        return self.animal

Mapbox map.on(‘click’, (event) code

if (boolVal == true){
                var result = window.confirm("Do you want to make a post here? " + lt + ", " + lg)
                if (result === true){

                    new mapboxgl.Marker({
                    color: "#FF447",
                    //draggable: true
                    }).setLngLat([lt, lg])
                    .addTo(map);

                    const postpopup = new mapboxgl.Popup({ offset: [0, -15] })
                    .setLngLat([lt, lg])
                    .setHTML(
                    `<h1>Yellowmap :) Post Forum</h1>
                        <div style="margin-left: 40px;">
                            <form method="POST" action="">
                                {% csrf_token %}
                                {{form.as_p}}
                                <input type="submit" value"submit"/>
                            </form>
                            <p></p>
                        </div>`
                    )
                    .addTo(map);
                } 
            }

Anybody have any advice or tips for me to fix this issue? I am not the most experienced with Django so any help is much appreciated!

.value in javascript not workin, how do i fix it [duplicate]

I am struggling to display the output in the console using .value input in javascript

let userName;
document.getElementById('button1').onclick = function() {
  userName = document.getElementById('name').value;
  console.log(userName);
}
<label>Enter your name: </label><br>
<input type="text" id="name"><br>
<button type="button" id="button1">Submit</button>

Print function in JavaScript is not working in asp.net

Print function is not working and throwing error.

Cannot read properties of undefined (reading ‘print’)

function PrintPage() {
    var label = FindParent(document.getElementById("Label"), 'sectionHeader');
    var STable = document.getElementById('STable');

    var bodyHtml = document.body.innerHTML;
    document.body.innerHTML = label.innerHTML + "<br/>" + STable.parentNode.innerHTML;
    document.parentWindow.print();
    document.body.innerHTML = bodyHtml;
}

add mailto: before every email

hey so I have a html table with a bunch of people and email addresses. I want to add mailto: before every email. is there anyway to do this using javascript, or preferably a find/replace function in vscode?

  <tr>
    <td>Mrs. john doe</td>
    <td></td>
    <td>[email protected]</td>
    <td>Principal</td>
</tr>
<tr>
    <td>Mr. jerremy fields</td>
    <td></td>
    <td>[email protected]</td>
    <td>Deputy</td>
</tr>
<tr>
    <td>Mrs. rebecca statin</td>
    <td></td>
    <td>[email protected]</td>
    <td>Deputy</td>
</tr>

ive tried using a vscode find/replace like this:

Find: [email protected]
Replace: <td>mailto:[email protected]

The find works, yet when I try and replace the actual ‘.?’ is being replaced instead of the previous wildcard expression

thanks in advance

Parsing Json data from a file

I am building a Node JS application that reads file that contains array of Json objects, and displays it on a table. I need to parse the JSON data array.
sample json data:

[{"name":"Ken", "Age":"25"},{"name":"Pulsar", "Age":30}]

I have used the following to read from file and pass it into another json object:

const fileRead = fs.readFileSync("/Users/mken/Desktop/Node JS/DATA-TABLE/public/files/data.json", (err, data)=>{
console.log(JSON.parse(data))
return JSON.parse(data);

});

console.log(fileRead)

The expected output is array of JSON objects. However, when I console.log the fileRead, I do not get intended output:output

I further intend to iterate through the data read above and pass it to a JSON object:

const data = {headers:["Name", "Age"], rows: fileRead.foreach((row)=>{return row.name, row.age];})}

Please check and advise.

How to reveal data of blocks

So, there is this game that is a block of mine’s and diamonds. When you press the block, it reveals if it’s a gem or a mine. Is there a way to reveal which one it is before pressing the block?

CSS/Javascript Double Cascading Menus not Working

I have a double cascading menu that’s not working. The first cascade works but the second does not at all.

Here’s a screenshot of the activity:

Initial Cascading Menu

Second Level Cascading Menu

Here’s the CSS that controls the menus cascading qualities:

        div.indiv_publication{

            padding-left: 76px;
            padding-top: 20px;
            padding-bottom: 20px;
            font-size: 32px;
            font-weight: 700;
            border-top-width: 1px;
            border-top-color: lightgrey;
            border-top-style: solid;
            color: black;
            background-color: white;
            text-align: left;
            border-bottom-width: 0px;
            border-right-width: 0px;
            border-left-width: 0px;
            display: flex;
            flex-direction: column;


            &:hover{

                color: lightgrey;
                transition: 0.4s;
                -webkit-transition: 0.4s;

            }

            .active{

                color: lightgrey;
                transition: 0.4s;
                -webkit-transition: 0.4s;
                

            }

            div.panel{

                  padding: 0 18px;
                  background-color: white;
                  max-height: 0;
                  overflow: hidden;
                  transition: max-height 0.2s ease-out;       
            }

            // }

            div.panel_2{

                  padding: 0 18px;
                  background-color: white;
                  max-height: 0;
                  overflow: hidden;
                  transition: max-height 0.2s ease-out;
            }

Here’s the Javascript that controls the transition:

(Please note the “*_date_button” are not actually buttons but divs. (They started as buttons but were changed.)

                    indiv_date_button.addEventListener("click", function(e) 
                    {
                        
                        console.log("click on indiv_date_button happened");
                        indiv_date_button.classList.toggle("active");
                        // div_obj.style.flexDirection = "column";
                        let panel_2 = indiv_date_button.children[0];
                        console.log(panel_2);
                        if (panel_2.style.maxHeight) {
                            panel_2.style.maxHeight = null;
                        } 
                        else 
                        {
                            panel_2.style.maxHeight = panel_2.scrollHeight + "px";
                            // panel_2.style.maxHeight =  "1000px";
                        }
                        // if (!e) let e = window.event;
                        
                        // if (e.stopPropogation) 
                        e.stopPropagation();

                    });

                }

                div_obj.addEventListener("click", function() 
                {
                    console.log("click on indiv_publication happened");
                    div_obj.classList.toggle("active");
                    // div_obj.style.flexDirection = "column";
                    let panel = div_obj.children[0];
                    console.log(panel);
                    if (panel.style.maxHeight) {
                        panel.style.maxHeight = null;
                    } 
                    else 
                    {
                        panel.style.maxHeight = panel.scrollHeight + "px";
                    }
                });


When I click on the publication names everything works fine but when I click on the dates nothing happens. These are the messages in the Firefox JS Console:

click on indiv_publication happened script.js:233:14
<div class="panel">
script.js:237:17
click on indiv_date_button happened script.js:209:15
<div class="panel_2">
script.js:213:18
click on indiv_date_button happened script.js:209:15
<div class="panel_2" style="max-height: 1000px;">
script.js:213:18
click on indiv_publication happened script.js:233:14
<div class="panel" style="max-height: 413px;">
script.js:237:17
click on indiv_publication happened script.js:233:14
<div class="panel" style="">script.js:237:17

Here’s the Inner HTML:

<div class="indiv_publication">
+ COMPLEX
     <div class="panel">
+     Sat Jul 16 2022
       <div class="panel_2">
          <div class="indiv_article">
             <div class="date">7.16.2022</div>
             <div class="article_link">
                <a class="article_link" href="https://www.complex.com/music/ellie-goulding-new-video-easy-lover-feat-big-sean">Big Sean Appears in the Video for Ellie Goulding’s New Song “Easy Lover”</a>
            <div class="author_list"></div>
            </div>
            <div class="save_delete"></div>
          </div>
          <div class="indiv_article">
            <div class="date">7.16.2022</div>
            <div class="article_link">
               <a class="article_link" href="https://www.complex.com/pop-culture/sami-charlie-sheen-doesnt-support-onlyfans-account">Sami Says Charlie Sheen Still Hasn’t Come Around to Supporting Her OnlyFans Account</a>
               <div class="author_list"></div>
            </div>
            <div class="save_delete"></div>
          </div>
<!-- etc -->

Re-render a component from sibling component in React

I am currently learning react and I am trying to make a ToDo App. Now I am having a problem when I add a new task in the list. I can successfully add an item in the list when I click the add button, the json file where I store each todo is also update, but the problem is the text wont show.

enter image description here

This is what it looks like. The text will only show if I refresh the page.

Here is my <Home/> component

import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import AddTask from "./AddTask";
import TaskList from "./TaskList";
import useFetch from "./useFetch";

const Home = () => {
  const {
    data: todo,
    setData: setTodo,
    isPending,
    error,
  } = useFetch("http://localhost:8000/tasks");
  useEffect(() => {
    if (todo) setTodo(todo);
  }, [todo]);

  return (
    <div className="home">
      <AddTask setTodo={setTodo} />
      {error && <div>Failed to fetch data.</div>}
      {isPending && <div>Loading...</div>}
      {todo && <TaskList todo={todo} setTodo={setTodo} />}
      <Link to="/trashbin" className="history">
        View History
      </Link>
    </div>
  );
};

export default Home;

Here is my <AddTask/> component.

import { useState } from "react";

const AddTask = ({ setTodo }) => {
  const [task, setTask] = useState("");
  const [isPending, setIsPending] = useState(false);

  const handleClick = (e) => {
    e.preventDefault();
    setIsPending(true);
    const todo = { task };

    fetch("http://localhost:8000/tasks", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(todo),
    }).then(() => {
      setIsPending(false);
      setTodo((prev) => [...prev, task]);
    });
    setTask("");
  };

  return (
    <form className="new-task" onSubmit={handleClick}>
      <input
        className="input"
        type="text"
        required
        placeholder="Add new task..."
        value={task}
        onChange={(e) => setTask(e.target.value)}
      />
      <button className="add-task">
        <i className="fa-solid fa-plus fa-2x"></i>
      </button>
    </form>
  );
};

export default AddTask;

And here is my <Tasklist/> component which will display the task list.

import $ from "jquery";
import { useEffect, useState } from "react";

const TaskList = ({ todo, setTodo }) => {
  const [todos, setTodos] = useState("");

  return (
    <div className="tasks">
      <ul>
        {todo.map((todo) => (
          <li className="task" id={todo.id} key={todo.id}>
            <input type="checkbox" className="checkbox" />

            <p className="task-name paragraph">{todo.task}</p>

            <input
              type="text"
              className="task-name edit-task"
              value={todos}
              onChange={(e) => setTodos(e.target.value)}
            />

            <button className="edit button">
              <i className="fa-solid fa-edit"></i>
            </button>

            <button
              onClick={() => handleDelete(todo.id, todo.task)}
              className="delete button"
            >
              <i className="fa-solid fa-trash-can"></i>
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default TaskList;

How to fix missing HTML tags in Node.js [closed]

I am working with HTML fragments that are not well-formed. Some examples can be:

</p></p><p> ...text....</p> -->[I want]--> <p> ...text</p>
<p><p><p> ...text</p> -->[I want] --> <p> ...text</p>

Is there any library or regexp that can help me to repair the HTML by removing the elements that do not match with a closing or opening tag?

Thank you.

How to hide a Login Form after validation and then send to a Layout Form (main form) React 18.0 and Material-ui V.5.0

I did not find a simple code here, to hide (or close like in desktop app. C#) a Login form after I have made an authentication, and then send me to the Layout form, which is the main form for the app. My code is straightforward, and I’m not doing backend authentication yet, it will be the next step. Here follow my Login form. All help will be very appreciated. Yup is commented but I’ll use it later.

import React, { useEffect, useState, useContext } from 'react';
import CashFlowContext from '../context/Context';
import Avatar from '@mui/material/Avatar';
import Button from '@mui/material/Button';
import CssBaseline from '@mui/material/CssBaseline';
import TextField from '@mui/material/TextField';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import Link from '@mui/material/Link';
import Grid from '@mui/material/Grid';
import Box from '@mui/material/Box';
import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
import Typography from '@mui/material/Typography';
import Container from '@mui/material/Container';
import { useHistory } from 'react-router-dom';
// import * as yup from 'yup';



function CheckLogin(props) {
  return (
    <Typography variant="body2" color="text.secondary" align="center" {...props}>
      {'Copyright © '}
      <Link color="inherit" href="https://mui.com/">
        CashFlowBR
      </Link>{' '}
      {new Date().getFullYear()}
      {'.'}
    </Typography>
  );
}

// interface IformLogin{
//   userName: string;
//   userEmail: string;
//   password: string;
// }


// const formValidationSchema: yup.SchemaOf<IformLogin> = yup.object().shape({
//   userName: yup.string().required().min(3),
//   userEmail: yup.string().required().email(),
//   password: yup.string().required().password(),

// });

export default function SignIn() {

  const { userEmail, setUserEmail } = useContext(CashFlowContext);
  const { userName, setUserName }= useContext(CashFlowContext)
  const [ isLoading, setIsLoading] = useState(false);
  const [password, setPassword] = useState({ password: '' });
  const [enterBtn, setEnterBtn] = useState({ enterBtn: true });
  const [loginForm, setLoginForm] = useState(false);  // trying to hide login Form
  const history = useHistory();



  window.addEventListener("beforeunload", function(e){
    localStorage.clear();  // clear local storage before unload - working fine.
 }, false);

  const handleChange = ({ target }) => {
    const { name, value } = target;
    if (name === 'userEmail') setUserEmail(value);
    if (name === 'password') setPassword({ password: value });
  };

  const validateEmail = (input) => {
    const result = /^[^s@]+@[^s@]+.com/;
    return result.test(input);
  };

  useEffect(() => {
    const MIN_LENGTH = 5;
    if (validateEmail(userEmail) && password.password.length > MIN_LENGTH) {
      setEnterBtn({ enterBtn: false });
    } else setEnterBtn({ enterBtn: true });
  }, [userEmail, password]);

  const handleClick = () => {
    localStorage.setItem('userEmail', JSON.stringify({ userEmail }));
    history.push('/Layout');  // desired route after login is pushing correctly.

 
    // how to hide this loginform after the router above. ????
  
  };

  return (
   
      <Container component="main" maxWidth="xs">
        <CssBaseline />
        <Box
          sx={{
            marginTop: 8,
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
          }}
        >
          <Avatar sx={{ m: 1, bgcolor: 'secondary.main' }}>
            <LockOutlinedIcon />
          </Avatar>
          <Typography component="h1" variant="h5">
            Entrar
          </Typography>
          <Box component="form"  noValidate sx={{ mt: 1 }}>
            <TextField
              margin="normal"
              required
              fullWidth
              type="email"
              id="userEmail"
              label="Type your Email"
              name="userEmail"
              autoComplete="off"
              autoFocus
              value={ userEmail }
              onChange={ handleChange }
            />
            <TextField
              margin="normal"
              required
              fullWidth
              name="password"
              label="Type your Password"
              type="password"
              id="password"
              autoComplete="current-password"
              value={ password.password }
              onChange={ handleChange }
            />
            <FormControlLabel
              control={<Checkbox value="remember" color="primary" />}
              label="Lembrar senha"
            />
            <Button
              type="button"
              fullWidth
              variant="contained"
              sx={{ mt: 3, mb: 2 }}
              disabled={ enterBtn.enterBtn }
              onClick={ () => handleClick() }
            >
              Entrar
            </Button>
            <Grid container>
              <Grid item xs>
                <Link href="#" variant="body2">
                  Esqueceu a senha?
                </Link>
              </Grid>
              <Grid item>
                <Link href="#" variant="body2">
                  {"Don't have an account? Sign Up"}
                </Link>
              </Grid>
            </Grid>
          </Box>
        </Box>
        <CheckLogin sx={{ mt: 1, mb: 6 }} />
      </Container>
  );
}

and suggestions will be very appreciated.