Sending a String concatenated with variable raises an error in Minecraft

Okay, so, I’m having trouble sending players strings combined with variables. For example, this line of code:

client.write("chat", { message: ("Username:"+data.data[0]["name"].toString())})

This data variable is a JSON object. Printing out

"Username:"+data.data[0]["name"].toString()

Works without an error, but when I try send it to the client, the client disconnects with this error message:

Internal Exception: io.netty.handler.codec.DecoderException: 
com.google.gson.JsonSyntaxException: 
com.google.gson.stream.MalformedJsonException: Use 
JsonReader.setLenient(true) to accept malformed JSON at line 1 column 10

BTW, I’m using npm minecraft-protocol javascript

JSON object is getting corrupted

I am using a JSON object on a project I am working on. I am doing many updates to this JSON file as it is my primary file to work with. I am using nodejs to handle requests and processes my file.

My JSON data looks something like this:

[
   { field1:123,
    field2:"Test",
    field3:"New",
    field4:"City",
   },
   { field1:"123",
    field2:"Test2",
    field3:"FILE to use",
    field4:"Assignment Token",
   }
]

Throughout its life cycle my files gets corrupted and a it show a similar pattern every time it gets corrupted. I tried to reduce as many number of call it is possible. The pattern it shows is as follows. Any ideas how to avoid this?

[
   { field1:123,
    field2:"Test",
    field3:"New",
    field4:"City",
   },
   { field1:"123",
    field2:"Test2",
    field3:"FILE to use",
    field4:"Assignment Token",
   }
]o use",field4:"Assignment Token",}]

HTML/Javascript: Submit form when the timer is over

I use unipark to collect something for my thesis. There HTML & Javascript can be used. My subjects are supposed to correct a text in a form and a timer is supposed to run down. When this timer is over, the form should be confirmed and continued. Unfortunately, the whole thing does not work with the confirmation. I hope you can help me.

<html>

<head>
    <div style="color: red"><font size="6">You have <span id="time">01:00</span> minutes!</font></div>
</head>

<script>
function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        if (--timer < 0) {
             document.querySelector('#time').textContent = "Expired"
             document.getElementById('submit').submit();
        }
    }, 1000);
}

window.onload = function () {
    var Minutes = 60 * 0.125,
        display = document.querySelector('#time');
    startTimer(Minutes, display);
};

</script>



</br>

<body>
    <style type="text/css">
      textarea.html-text-box {background-color:ffffff;background-repeat:no-repeat;background-attachment:fixed;border-width:1;border-style:solid;border-color:cccccc;font-family:Arial;font-size:8pt;color:000000;}
      input.html-text-box {background-color:ffffff;font-family:Arial;font-size:8pt;color:000000;}
    </style>
    
<form name="Task" id="textform">

<textarea name="comments" cols="150" rows="50" class="html-text-box"> 
Text to correct
</textarea>

</form>
    <form method="post" action="">
        <input name="submit" type="submit" value="submit">
    </form>
</body>
</html>

I hope you can help me out.

Node Js Function Declaration and Expression

I just started to learn Node Js then I got the following code in the tutorial

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

const questions = [
  "What is your name? ",
  "Where do you live? ",
  "What are you going to do with node js? "
];

const collectAnswers = (questions, done) => {
  const answers = [];
  const [firstQuestion] = questions;

  const questionAnswered = answer => {
    answers.push(answer);
    if (answers.length < questions.length) {
      rl.question(questions[answers.length], questionAnswered);
    } else {
      done(answers);
    }
  };

  rl.question(firstQuestion, questionAnswered);
};

collectAnswers(questions, answers => {
  console.log("Thank you for your answers. ");
  console.log(answers);
  process.exit();
});

The code has the following result

What is your name? a
Where do you live? b
What are you going to do with node js? c
Thank you for your answers.
[ 'a', 'b', 'c' ]

As far as I understand that the variable collectAnswer somehow inject the function declared below to the second parameter (done). Can someone explain what is actually happening behind the scene? How can the function declared below injected to the variable with the same name with it? Any term this pattern actually called?

How to import sodium-plus directly into a .js file? “module does not provide an export named ‘default'”

I would like to import sodium-plus to use within a .js file in a Chrome extension. The library’s documentation only shows how to include the extension from an html file with a <script> tag. When I do that I get an error:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'".

I tried to import directly through a .js file:

import SodiumPlus from "./sodium-plus.min.js";
(async function() {
    if (!window.sodium) window.sodium = await SodiumPlus.auto();

    // You can now use the sodium object here.

    // Just some example code to ensure it's running:
    let random = await sodium.randombytes_buf(32);
    let hash = await sodium.crypto_generichash('hello world');
    console.log({
        'random': random.toString('hex'),
        'hash': hash.toString('hex')
    });
})();

But received an error:

Uncaught SyntaxError: The requested module './sodium-plus.min.js' does not provide an export named 'default'

Is there any way to fix that? Alternatively, is there a similar library that would be easier to import into a .js file of a Chrome extension?

Google Maps Api v.3 Add 27,000 points to the map

There is a task to place 27000 points of sale on google maps + clustering + infoWindow. At the moment, this is implemented through a normal loop for(point of poits){…} that adds markers to the map. There is a problem with high memory consumption and high load on the browser. I will be grateful for your help.

Subscribe/Unsubscribe an email in input form REACT

I have a task to

  • Implement the functionality of sending a user’s email to the server when they click on the “Subscribe” button. To do this, make a POST Ajax request using the /subscribe endpoint.
  • Implement the functionality of unsubscribing the user’s email from
    the community list when they click on the “Unsubscribe” button. To do
    this, make a POST Ajax request using the /unsubscribe endpoint.
  • Prevent additional requests if the “Subscribe” and “Unsubscribe”
    buttons are pressed while requests to the /subscribe and /unsubscribe
    endpoints are in progress. Also, disable them (using the disabled
    attribute) and style them using opacity: 0.5. using React.Redux library is prohibited.

So,i have did this task,but the problem is that my form is not doing unsubscribe state,it leaves the email unchanged and the button doesnt change its state from unsubscribe to subscribe,but as a result,when an email is valid,it should give the possibility of sending subscribe fetch request to the server and the button text to change in Unsubscribe and the display of the form to be none,but if the email is not valid,then the button should have the Subscribe text,no fetch request possibilities and the input form to have the display block.Besides this,the value to be stored in local storage and when the page refreshes it leaves the form in the state it was,if was subscribed then all the changes for subscribe are actual and if not than vice-versa.
I have did this task using only javascript and it works as follows:
non-valid email: enter image description here

valid email: enter image description here

So,the question is,what i am doing wrong? Why only subscribe fetch works and how to fix the form to make the requested result,i’m exhausted,three days i try to answer this question and i dont understand anything.. please help,thanks in advance!

JoinUsSection component with the form :

import { useState, useEffect } from "react"
import { sendSubscribe } from "../scripts/subscribeFetch"
import { validateEmail } from "../scripts/email-validator"
import { unsubscribeUser } from "../scripts/unsubscribeFetch"

const JoinUsSection = props => {
  const { placeholder } = props
  //Input div functions

  let isSubscribedd = localStorage.getItem('Email')                          //Function for setting display to none if the form is subscribed and display to block 
  //console.log(validateEmail(isSubscribedd))                                //if form is unsubscribed
  let validatedEmail = validateEmail(isSubscribedd)

  let setDisplay = ''
  if (validatedEmail === true) {
    setDisplay = 'none'
    localStorage.setItem('isSubscribed', 'true')
  } else if (validatedEmail === false) {
    setDisplay = 'block'
    localStorage.setItem('isSubscribed', 'false')
  }
  //-------------------------------------

  //Input type text Functions

  const [email, setEmail] = useState(() => {
    //reading data from localStorage
    const localEmail = localStorage.getItem('Email')
    const initialValue = localEmail
    if (localStorage.getItem('Email') !== null) {
      return initialValue
    } else {
      return placeholder
    }
  })

  useEffect(() => {
    //storing input email in localStorage
    const introducedEmail = email
    //console.log(introducedEmail)
    localStorage.setItem('Email', introducedEmail)
  }, [email])
  //------------------------------------------------------


  //Input type button Functions 

  const [isDisabled, setDisabled] = useState(false)
  const [isSubscribed, setSubscribe] = useState('Subscribe')

  let isFetching = false
  let isUsed = false

  let introducedEmail = email

  const submitClickButton = async () => {
    subscribeEmail(introducedEmail)   //change the button style and set in local storage isSubscribed to true
    sendSubscribe(introducedEmail)  //send subscribe fetch to the server

    // prevent additional requests upon clicking on "Subscribe" and "Unsubscribe".
    if (isFetching) return // do nothing if request already made
    isFetching = true
    disableBtn()
    const response = await fetchMock()  //eslint-disable-line
    isFetching = false
    enableBtn()

    isUsed = true

    if (validateEmail(introducedEmail) == false) {
      isUsed = false
    }
  }

  const fetchMock = () => {
    return new Promise(resolve => setTimeout(() => resolve('hello'), 2000))
  }


  const disableBtn = () => {
    // button.disabled = true
    // button.style.opacity = '0.5'
    setDisabled(true);
  }
  const enableBtn = () => {
    // button.disabled= false
    // button.style.opacity = '1'
    setDisabled(false);
  }

  const opacityValue = props.disabled ? 0.5 : 1;

  const undoClickButton = () => {
    unsubscribeEmail()
    isUsed = false
  }

  const changeButtonState = () => {
    isUsed ? undoClickButton() : submitClickButton()
  }

  const subscribe = () => {
    //  const subscribeBtn = document.getElementById('subscribeButton')
    setSubscribe('Unsubscribe')
    // document.getElementById('emailForm').style.display = 'none'
    localStorage.setItem('isSubscribed', 'true')
    console.log(isUsed)
    //document.getElementById('submit-info').value = ''
    introducedEmail = ''
  }

  const unsubscribe = () => {
    //const subscribeBtn = document.getElementById('subscribeButton')
    setSubscribe('Subscribe')
    //document.getElementById('emailForm').style.display = 'block'
    localStorage.setItem('isSubscribed', 'false')
    console.log(isUsed)
  }

  const subscribeEmail = (email) => {
    const isValidEmail = validateEmail(email)
    if (isValidEmail === true) {
      subscribe()
    } else if (isValidEmail === false) {
      unsubscribe()
    }
  }

  const unsubscribeEmail = () => {
    unsubscribe()
    unsubscribeUser()
    localStorage.removeItem('Email')
  }
  //--------------------------------------

  return (
    <>
      <section className='app-section app-section--image-program' id='programContainer'>
        <h2 className='program-title'>Join Our Program</h2>
        <h3 className='program-subtitle'>Sed do eiusmod tempor incididunt<br />ut labore et dolore magna aliqua</h3>
        <form className='submitFieldWrapper' id='form'>
          <div
            style={{
              display: setDisplay
            }}>
            <input
              className='form-input'
              id='submit-info'
              type='text'
              placeholder='Email'
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
          </div>
          <input
            id='subscribeButton'
            className='app-section__button submit-btn'
            type='button'
            value={isSubscribed}
            style={{
              opacity: opacityValue
            }}
            onClick={() => changeButtonState()}
            disabled={isDisabled} />
        </form>
      </section>
    </>
  )
}

export default JoinUsSection

subscribe fetch request,in different folder and file:

import { validateEmail } from './email-validator.js'

export const sendSubscribe = (emailInput) => {
  const isValidEmail = validateEmail(emailInput)
  if (isValidEmail === true) {
    sendData(emailInput)
  }
}

export const sendHttpRequest = (method, url, data) => {
  return fetch(url, {
    method: method,
    body: JSON.stringify(data),
    headers: data
      ? {
          'Content-Type': 'application/json'
        }
      : {}
  }).then(response => {
    if (response.status >= 400) {
      return response.json().then(errResData => {
        const error = new Error('Something went wrong!')
        error.data = errResData
        throw error
      })
    }
    return response.json()
  })
}

const sendData = (emailInput) => {
  sendHttpRequest('POST', '/subscribe', {
    email: emailInput
  }).then(responseData => {
    return responseData
  }).catch(err => {
    console.log(err, err.data)
    window.alert(err.data.error)
  })
}

email validator ,in different folder and file:

const VALID_EMAIL_ENDINGS = ['gmail.com', 'outlook.com', 'yandex.ru']

export const validateEmail = (email) => !!VALID_EMAIL_ENDINGS.some(v => email.includes(v))

export { VALID_EMAIL_ENDINGS as validEnding }

unsubscribe fetch request,in different folder and file:

export const unsubscribeUser = () => {
  fetch('/unsubscribe', { method: 'POST' }).then(response => { console.log(response.status) })
}

App.js:

import './App.css';
import JoinUsSection from './components/JoinUsSection';

function App() {
  return (
    <JoinUsSection/>
  );
}

export default App;

Javascript: split table rows into 2 equal columns

I have a script that will create some links inside table rows and display them.

$('#links').val('<class="sws_gen_links_table">' + links.join('n'));

$('#linksContainer').show();

What I would like to do before these are displayed is to split them into equal 2 columns and add them into the respective td. Something like this:

<table id="stylewithcss">
<tbody>

<tr>
<td class="This is the header of the table" colspan="2">ADD HEADER HERE</td>
</tr>
<tr>

<td>
Here goes the first part of the links.
</td>

<td>
This goes the second part of the links.
</td>

</tr>
</tbody>
</table>

I found something similar here but to be honest I don’t really know how to apply it in my case (I am a beginner).
convert single column to multiple columns

When I input item, old item not disappeared in array

https://youtu.be/bTx08ox0zA8

In viedo, input item “to Do” again at 3:54, the old “to Do” disappears. But It’s not disappeared in my project

so I looked carefully my code…

const toDoForm = document.querySelector("#todo-form");
const toDoInput = document.querySelector("#todo-form input");
const toDoList = document.querySelector("#todo-list");
const TODOS_KEY = "todos";
const toDos = [];

function saveToDos(){
    localStorage.setItem(TODOS_KEY, JSON.stringify(toDos));
}

function deleteToDo(event){
    const li = event.target.parentElement;
    li.remove();
}

function paintToDo(newToDo){
    const li = document.createElement("li");
    const button = document.createElement("button");
    const span = document.createElement("span");
    span.innerText = newToDo;
    button.innerText = "✔";
    button.addEventListener("click", deleteToDo);
    li.appendChild(span);
    li.appendChild(button);
    toDoList.appendChild(li);
    toDos.push(newToDo);
    saveToDos();
}

function handleToDoSubmit(event){
    event.preventDefault();
    const newToDo = toDoInput.value;
    toDoInput.value="";
    paintToDo(newToDo);
}

toDoForm.addEventListener("submit", handleToDoSubmit);

const saveToDo = localStorage.getItem(TODOS_KEY);

if (saveToDo !== null){
    const parsedToDos = JSON.parse(saveToDo);
    parsedToDos.forEach(paintToDo);
}

then I found that

toDos.push(newToDo);
saveToDos();

they should exist in ‘function paintToDo’ not a ‘function handleToDoSubmit’

In video, input new item in array on web => disappeared old item in array
When I did with my code, old item still exist in array with new item

I want understand why it’s not occur error and how it’s changed result in according to different of video and my code

anyone can help this?
please help meㅠㅠ

Can I use Sass properties as args for my function?

It appears that I’m attempting to use SASS properties as arguments for my function, AND IT’S NOT GOING WELL.

Is there a way in which I can do this, or is there a better alternative to what I’m trying to achieve?

Basically, I want to change the values of variables I send to my function based on my screen width media query.

Currently:

@function myFunc($arg1, $arg2) {
    @debug "arg1 = #{$arg1} / arg2 = #{$arg2}";

    @return #{$arg1} * #{$arg2};
}

.my-class {
    // Mobile first values
    --var1: 10px;
    --var2: 20px;

    @media (--from-tablet-size) {
        --var1: 20px;
        --var2: 40px;
    }

    width: myFunc(--var1, ---var2);
}

The debug output actually shows that the values passed to the function is just the strings --var1 and --var2 rather than their respective property values…

DEBUG: arg1 = --var1 / arg2 = --var2

Is there something that I can do to solve this? Either by passing the properties as I am attempting here, or a better alternative?

Axios call, argument must be array but null given

In my vue component I have a data array

data: {
  categories: [{id:1, title: "category 1"},{id:2, title: "category 2"}]
}

and I’m trying to load this in as a data argument in an axios call

axios({
  method: 'get',
  url: //testURL,
  data: {
    categoryCall: this.categories
  }
}).then(function (response){
  console.log(response);
}).catch(function (error){
  console.log(error.response);
});

but I’m getting a 400 bad request code where it tells me that argument 1 should be an array and null is given.

Am I not properly passing in the already established array in the axios call? Where am I going wrong?

Active class disappears from navigation when switching tabs

I have a simple Bootstrap 3 navigation developed with nested pills.
The problem is that when I switch tabs between Menu A and Menu B, tabs (for example) Tab B stop being active (.active) and their content is not displayed.

I’ve already broken my head looking for the place where I went wrong.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<section>
    <div class="container">
        <div class="row">
  <div class="col-lg-2 col-xs-12">
    <div class="nav flex-column nav-pills vertical-control" id="v-pills-tab" role="tablist" aria-orientation="vertical">
     
      <a class="nav-link nav-link-sidebar active" id="tab-yt" data-toggle="tab" href="#control-yt" role="tab" aria-controls="v-pills-yt" aria-selected="true">
      Menu A</a>
      <a class="nav-link nav-link-sidebar" id="tab-tw" data-toggle="tab" href="#control-tw" role="tab" aria-controls="v-pills-tw" aria-selected="false">Menu B</a>
    </div>
  </div>
  <div class="col-lg-10 col-xs-12">
    <div class="tab-content" id="v-pills-tabContent">
        <div class="tab-pane fade in active" id="control-yt" role="tabpanel" aria-labelledby="tab-yt">

            <div class="row">

                <div class="col-12">
                
                <div class="nav nav-pills nav-pills-items" id="v-pills-tab" role="tablist" aria-orientation="horizontal">
                <a class="nav-link" id="tab-c-a" data-toggle="tab" href="#c-a" role="tab" aria-controls="c-a" aria-selected="true">Tab A</a>
                <a class="nav-link active" id="tab-c-b" data-toggle="tab" href="#c-b" role="tab" aria-controls="c-b" aria-selected="true">Tab B</a>
                
                </div>
                </div>

                <div class="col-12">
                <div class="tab-content sub-tab-content" id="v-pills-tabContent">
                <div class="tab-pane" id="c-a" role="tabpanel" aria-labelledby="tab-c-a">
                    
                    <div class="row">
                        <div class="col-md-12">
                                Content A
                        </div>
                    </div>
                </div>

                  
                <div class="tab-pane fade in active" id="c-b" role="tabpanel" aria-labelledby="tab-c-b">
                    
                    <div class="row">
                        <div class="col-md-12">
                            Content B
                        </div>
                    </div>
                </div>

                </div>
                </div>

            </div>

        </div>
    
        <!-- yt Ends -->
     
        <div class="tab-pane fade in" id="control-tw" role="tabpanel" aria-labelledby="tab-tw">

            <div class="row">

                <div class="col-12">
                
                <div class="nav nav-pills nav-pills-items" id="v-pills-tab" role="tablist" aria-orientation="horizontal">
                <a class="nav-link active" id="tab-tw-1" data-toggle="tab" href="#tw-1" role="tab" aria-controls="tw-1" aria-selected="true">Tab C</a>
                </div>
                </div>

                <div class="col-12">
                <div class="tab-content sub-tab-content" id="v-pills-tabContent">
                <div class="tab-pane fade in active" id="tw-1" role="tabpanel" aria-labelledby="tab-tw-1">
                    
                    <div class="row">
                        <div class="col-md-12">
                                Content C
                        </div>
                    </div>
                </div>

                </div>
                </div>

            </div>

        </div>
        
      
    </div>
  </div>
</div>

    </div>
</section>

NodeJS push() is not modift outside scope [duplicate]

I have script for splitting array into smaller chunks. After split i tried to combine images and push data to another array but push method is not modify array. When i try to log new array’s length it gives me 0 all the time.

test.js

var portfolioMergedImages = [];

    for (let j = 0; j < portfolioArgsWithChunks.length; j++) {

        combineImages(portfolioArgsWithChunks[j])
        .then(img => {
            portfolioMergedImages.push(img);
        })
    }

    console.log(portfolioMergedImages.length); // returns zero