create canvas and msg.content in an outside function (discord.js/nodejs)

this has been bugging me for a while, I’ve created a pipboy like interface to display the condition of the character and built it into a solo functions but now i want to incorporate it into other display cards. The problem is every time i try to take the content out and put them in an external file the “canvas” or “msg” become undefined. This seems like a no brainer to off load to a function but I’m not sure how. i know i also have to pass “paperDollXoffset, paperDollXoffsetShort, paperDollYoffset, paperDollwidth, paperDollwidthShort”, and “paperDollheight” as their configured for the stand alone canvas and would need adjusting on merged canvases.

code follows

        var CanvasW = 625;
        var CanvasH = 500;
        const paperDollXoffset = 0;
        const paperDollXoffsetShort = 187.5;
        const paperDollYoffset = 0;
        const paperDollwidth = 625;
        const paperDollwidthShort = 250;
        const paperDollheight = 500;
        canvas = Canvas.createCanvas(CanvasW, CanvasH);
        context = canvas.getContext('2d');
        background = await Canvas.loadImage('./images/photo-1538370965046-79c0d6907d47.jpg');
        var useShortValuesArms = 0;
        var useShortValuesLegs = 0;
        var useShortValuesBody = 0;
        var useShortValuesHead = 0;
        context.drawImage(background, 0, 0, CanvasW, CanvasH);
        context.strokeStyle = '#0099ff';
        context.strokeRect(0, 0, CanvasW, CanvasH);
        var basePic1URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Base/NekollxComm_BaseV2ArmS1_White.png';
        var basePic2URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Base/NekollxComm_BaseV2ArmS2_White.png';
        var basePic3URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Base/NekollxComm_BaseV2Head_White.png';
        var basePic4URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Base/NekollxComm_BaseV2Torso_White.png';
        var basePic5URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Base/NekollxComm_BaseV2LegS1_White.png';
        var basePic6URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Base/NekollxComm_BaseV2LegS2_White.png';
        var basePic7URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/CatPeople/NekollxComm2_CatTail_F_White.png';
        var basePic8URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/DragonPeople/NekollxComm2_DragonWingS1_F_White.png';
        var basePic9URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/DragonPeople/NekollxComm2_DragonWingS2_F_White.png';

      
        if (msg.content.toLocaleLowerCase().includes('!tail')){
          basePic3URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/CatPeople/NekollxComm2_CatHead_F_White.png';
          basePic7URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/CatPeople/NekollxComm2_CatTail_F_White.png';
        };//tail default to cat
        if (msg.content.toLocaleLowerCase().includes('!wing')){
            basePic3URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/DragonPeople/NekollxComm2_DragonHead_F_White.png';
            basePic7URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/DragonPeople/NekollxComm2_DragonTail_F_White.png';
            basePic8URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/DragonPeople/NekollxComm2_DragonWingS1_F_White.png';
            basePic9URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/DragonPeople/NekollxComm2_DragonWingS2_F_White.png';
        };//wing default to dragon girl
        if (msg.content.toLocaleLowerCase().includes('!noarm')){
            basePic3URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/BatPeople/NekollxComm2_BatHead_F_White.png';
            basePic7URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/BatPeople/NekollxComm2_BatTail_F_White.png';
            basePic8URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/BatPeople/NekollxComm2_BatWingS1_F_White.png';
            basePic9URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/BatPeople/NekollxComm2_BatWingS2_F_White.png';
        }//noarms and wing default to bat
        if (msg.content.toLocaleLowerCase().includes('!noleg')){
          basePic1URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/MerPeople/NekollxComm2_MerArmS1_F_White.png';
          basePic2URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/MerPeople/NekollxComm2_MerArmS2_F_White.png';
          basePic3URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/MerPeople/NekollxComm2_MerHead_F_White.png';
          basePic4URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/MerPeople/NekollxComm2_MerTorso_F_White.png';
          basePic7URL = 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/MerPeople/NekollxComm2_MerTail_F_White.png';
      };//no leg and tail default to mermaid

      //add/get art for (tail, no arm, no leg) Serpent [Torso, tail, head]
      //add/get art for (tail, arm, no leg, wing) Wyrm [Torso, tail, head, arm, wing]
      //add/get art for (tail, no arm, no leg, wing) feathered serpent [Torso, tail, head, wing]
      //add/get art for (no arm, optional tail) undertale/monster kid [Torso, tail, head, legs]
      //add/get art for (no leg, optional tail) arm monster, tail is a full serpent [Torso, tail, head, arm]
      //add/get art for (no leg, no arm, wing, optional tail) arm monster, tail is a full serpent, arms are wings [Torso, tail, head, wing]

      if (basePic1URL == 'https://maskedriders.info/Mee6RP/PaperDoll/White_Base/NekollxComm_BaseV2ArmS1_White.png'){
        useShortValuesArms = 1;
      }
      if ((basePic3URL == 'https://maskedriders.info/Mee6RP/PaperDoll/White_Base/NekollxComm_BaseV2Head_White.png') || (basePic3URL == 'https://maskedriders.info/Mee6RP/PaperDoll/White_Adjustments/CatPeople/NekollxComm2_CatHead_F_White.png')){
        useShortValuesHead = 1;
      }
      if (basePic4URL == 'https://maskedriders.info/Mee6RP/PaperDoll/White_Base/NekollxComm_BaseV2Torso_White.png'){
        useShortValuesBody = 1;
      }
      if (basePic5URL == 'https://maskedriders.info/Mee6RP/PaperDoll/White_Base/NekollxComm_BaseV2LegS1_White.png'){
        useShortValuesLegs = 1;
      }

        var conditionpic1 = await Canvas.loadImage(basePic1URL);
        var conditionpic2 = await Canvas.loadImage(basePic2URL);
        var conditionpic3 = await Canvas.loadImage(basePic3URL);
        var conditionpic4 = await Canvas.loadImage(basePic4URL);
        var conditionpic5 = await Canvas.loadImage(basePic5URL);
        var conditionpic6 = await Canvas.loadImage(basePic6URL);
        var conditionpic7 = await Canvas.loadImage(basePic7URL);
        var conditionpic8 = await Canvas.loadImage(basePic8URL);
        var conditionpic9 = await Canvas.loadImage(basePic9URL);
        var variableX = paperDollXoffset;
        var variableW = paperDollwidth;

        if (!msg.content.toLocaleLowerCase().includes('!noarm')){
          if (useShortValuesArms == 1){
            variableX = paperDollXoffsetShort;
            variableW = paperDollwidthShort;
          }
          context.drawImage(conditionpic1, variableX, paperDollYoffset, variableW, paperDollheight);
          context.drawImage(conditionpic2, variableX, paperDollYoffset, variableW, paperDollheight);
        }//noarms
        variableX = paperDollXoffset;
        variableW = paperDollwidth;

        if (useShortValuesHead == 1){
          variableX = paperDollXoffsetShort;
          variableW = paperDollwidthShort;
        }
        context.drawImage(conditionpic3, variableX, paperDollYoffset, variableW, paperDollheight);
        variableX = paperDollXoffset;
        variableW = paperDollwidth;

        if (useShortValuesBody == 1){
          variableX = paperDollXoffsetShort;
          variableW = paperDollwidthShort;
        }
        context.drawImage(conditionpic4, variableX, paperDollYoffset, variableW, paperDollheight);
        variableX = paperDollXoffset;
        variableW = paperDollwidth;

        if (!msg.content.toLocaleLowerCase().includes('!noleg')){
          if (useShortValuesLegs == 1){
            variableX = paperDollXoffsetShort;
            variableW = paperDollwidthShort;
          }
          context.drawImage(conditionpic5, variableX, paperDollYoffset, variableW, paperDollheight);
          context.drawImage(conditionpic6, variableX, paperDollYoffset, variableW, paperDollheight);
        }//nolegs

        variableX = paperDollXoffset;
        variableW = paperDollwidth;
        if (msg.content.toLocaleLowerCase().includes('!wing')){
          context.drawImage(conditionpic8, variableX, paperDollYoffset, variableW, paperDollheight);
          context.drawImage(conditionpic9, variableX, paperDollYoffset, variableW, paperDollheight);
        }//wings
        if (msg.content.toLocaleLowerCase().includes('!tail')){
          if (useShortValuesHead == 1){
            variableX = paperDollXoffsetShort;
            variableW = paperDollwidthShort;
          }
          context.drawImage(conditionpic7, variableX, paperDollYoffset, variableW, paperDollheight);
        }//tail

Regex: Anything that’s found with “700” should be found with “ddd” right?

I am experiencing an issue that I think is a regex bug. Before I submit to Google (chrome), can you just verify that if I do regex.test with:

/ddd/gim 

it should be true in every case where

/700/gim 

is true, correct?

(The source HTML file that I am running this on is too large to post)

  var regex = /ddd/gim;
  var obj = $();
  var elems = $("Section P, section LI, section TD, section H1");
  var num = 0;
  elems.each(function() {
    if (regex.test(this.innerText)) {
      obj = obj.add(this);
      num++;
    }
  }); 
  console.log("num: " + num);

when I do this with /700/gim, it is matching text that /ddd/ isn’t

How to move a button from one div to another when clicked in reactjs?

I’ve placed the following buttons within a div

const [state, setstate] = useState([]);
const arr = [1,2,3,4,5];
  
    return arr.map((num) => {
      return (
        <button
          key={num}
          className="buttons"
          onClick={(e) => {
            state.push(num);
          }}
        >
          {num}
        </button>
      );

When those buttons are clicked, I want them to move to another div. And when the button is clicked on the other div, the button has to come back to the original div.I found a solution but it involves document.getElementById(). But I believe that it is not a good thing to do in reactjs. Any ideas?

Django Ajax jquery 404 (Not Found)

could someone help me find a way to make my ajax request work?
I found some of the same questions on this site but didn’t solve them.
I want to Ajax the process to show modal

I’m using the latest Django version. I have never used ajax, so I don’t really know what I’m doing. Please help
What should I specify for the url?
Url to display Ajax?
Url to process Ajax?

app.urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('test/', include('test.urls')),    
]
test/urls.py

urlpatterns = [
    path('rex/', IndexView.as_view(), name='rex_index'),
]
    
test/templates/test/rex.html

{% extends 'main/layout.html' %}

{% block content %}
{% load crispy_forms_tags %}

<!--modal-->
<script>

$(function(){
$('#edit_foo').on('click', function () {
    console.log("test")
    $.ajax({
        type: 'POST',
        url: '/rex_index/',
        data: {
            html: '<form id="form_foo"><textarea></textarea><input type="submit"></input></form>',
            delay: 1,
        },
        success: function (data, textStatus, jqXHR) {
            $('#foo_modal').find('.modal-body').html(data);
            $('#foo_modal').modal('show');
        },
    });
});
});

// Handle submit.  Here we return an error regardless of the
// input given:
$("#foo_modal").on('submit', '#form_foo', function (e) {
    $.ajax({
        type: 'POST',
        url: '/rex_index/',
        data: {
            html: '<form id="form_foo_2"><span class="error">You must write something silly here:</span><textarea></textarea><input type="submit"></input></form>',
            delay: 0,
        },
        success: function (data, textStatus, jqXHR) {
            $('#foo_modal').find('.modal-body').html(data);
        },
    });
    e.preventDefault();
    return false;
});

// Handle second submit.  Here we close the modal.
// In a real application you can use the status to determine
// which action to take (success or redisplay the form).
$("#foo_modal").on('submit', '#form_foo_2', function (e) {
    alert('Thanks for writing something silly.  Closing modal');
    $('#foo_modal').modal('hide');
    e.preventDefault();
    return false;
});

</script>

<button type='button' id='edit_foo' class='buttons'>push me</button>

<div class="modal fade" id="foo_modal" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">Server Side Modal Popup Demo</div>
            <div class="modal-body"></div>
            <div class="modal-footer"></div>
        </div>
    </div>
</div>


{% endblock %}

views.py
***There is no description related to modal in view**


class IndexView(LoginRequiredMixin,FilterView):
    model = Order
    filterset_class = OrderFilter
    template_name = 'test/rex.html'
    
    queryset = Order.objects.all()     

    strict = False

    paginate_by = 10

    def get(self, request, **kwargs):        
        if request.GET:
            print("実行")
            request.session['query'] = request.GET
            print("query",request.session['query'])
        else:
            request.GET = request.GET.copy()
            if 'query' in request.session.keys():
                for key in request.session['query'].keys():
                    request.GET[key] = request.session['query'][key]

        return super().get(request, **kwargs)

Move next sibling element into previous sibling

I have a poorly formatted sidebar (aside) which I have no control over the structure.

But I want to make it the correct html structure by moving the elements which are supposed to be children into their parent elements.

I want to end up with something that is html valid:

<aside class="sidebar">
 <div class="sidebar-nav">
  <ul>
  <li><a>Title 1</a>
   <ul>
    <li><a>Title 2</a>
    <ul>
     <li><a>Title 3</a>
     ...
     ...
  </ul>
 </div>
</aside>

At the moment this is the html structure I’m working with, and the javascript I’ve got to. I realise at this point the looping of the function is causing it to recursively append the next element into the previous.

However, this means that I end up with so many more iterations.

// -- get the sidebar list
const sidebarList = document.querySelector('div.sidebar-nav > ul');

const reorder = ((list) => {
    const listItems = list.querySelectorAll(':scope li');
    listItems.forEach((element) => {

    // -- last h6 wont have a next sibling
    if (element.nextElementSibling === null) return;

    // -- if it is a second sub heading skip
    if (element.nextElementSibling.tagName !== 'UL') return;

    // -- add into the next element
    element.innerHTML = element.innerHTML + element.nextElementSibling.innerHTML
    });
})(sidebarList);
<aside class="sidebar">
  <div class="sidebar-nav">
    <ul>
      <li><a>Heading level 1</a></li>
      <ul>
        <li><a>Heading level 2</a></li>
        <ul>
          <li><a>Heading level 3</a></li>
          <ul>
            <li><a>Heading Level 4 - 1</a></li>
            <li><a>Heading Level 4 - 2</a></li>
            <ul>
              <li><a>Heading Level 5</a></li>
              <ul>
                <li><a>Heading level 6</a></li>
              </ul>
            </ul>
          </ul>
        </ul>
      </ul>
      <li><a>Heading level 1</a></li>
      <ul>
        <li><a>Heading level 2</a></li>
        <ul>
          <li><a>Heading level 3</a></li>
          <ul>
            <li><a>Heading Level 4 - 1</a></li>
            <li><a>Heading Level 4 - 2</a></li>
            <ul>
              <li><a>Heading Level 5</a></li>
              <ul>
                <li><a>Heading level 6</a></li>
              </ul>
            </ul>
          </ul>
        </ul>
      </ul>
    </ul>
  </div>
</aside>

How to test existing JavaScript functions with mocha

I’m new to the mocha framework, I’m not completely getting out of it, I have set up my machine with that framework in visual studio 2017. I have below a sample piece of code however I’m not getting how to test the existing javascript code that is in .cshtml page that has page elements as well in it, please help.

   ///////////////////////////////////////////////
    //  SAmple Code of mocha
        var assert = require('assert');
        
        describe('Test Suite 1', function () {
            it('Test 1', function () {
                assert.ok(true, "This shouldn't fail");
            });
        
            it('Test 2', function () {
                assert.ok(1 === 1, "This shouldn't fail");
                assert.ok(false, "This should fail");
            });
        });
    ///////////////////////////////////////////////////////////////

// Our code inside .cshtml

function SerChr(val) {
var f = parseFloat(result1) + parseFloat(document.getElementById("body_SerPerInst").value)
document.getElementById("body_TotAmtPerInst").value = Math.floor(f);
totreturnamount = (parseFloat(num3) + (parseFloat(document.getElementById("body_TotAmtPerInst").value) * parseFloat(document.getElementById("body_TotInst").value)));
document.getElementById("body_TotRetAmt").value = totreturnamount;
var h = parseFloat(num2) + parseFloat(document.getElementById("body_SerPerInst").value);
document.getElementById("body_inst1").value = Math.floor(h);
}

2nd example

$("#form2").submit(function(e){
  e.preventDefault();
  if(validate()){

    var formData = new FormData($(this)[0]);
    $.ajax({
      url: "addv.php",
      type: 'POST',
      data: formData,
      success: function (data) {
        $('.fv').html(data).hide().fadeIn(500).delay(1000).fadeOut(500);
      },
      contentType: false,
      processData: false
    });     
  } else {
   alert('error');
  }
});

// Another example

function validate()
{
    var m=document.getElementById("mat").value;
    var c=document.getElementById("kilo").value;
    var v=true;
    if(!isNaN(m))
        {
          alert("matricule  doit etre une chaine !");
          document.getElementById("mat").value=null;
          v=false;
        }
    if(isNaN(c))
        {
          alert("kilométrage doit etre un entier !");
          document.getElementById("kilo").value=null;  
          v=false;
        }
       return v;
}

trying to adjust a state object in redux but i can’t change the value of one property in the object

Ok so i have this very basic example of redux state

const initialState = {
  good: 0,
  ok: 0,
  bad: 0,
};

const counterReducer = (state = initialState, action) => {
  console.log(action);
  console.log(state);
  console.log(initialState);
  console.log(state.good);

  switch (action.type) {
    case "GOOD":
      return { ...state, good: good + 1 };
    case "OK":
      return { ...state, ok: ok + 1 };
    case "BAD":
      return { ...state, bad: bad + 1 };

    case "ZERO":
      return state;
    default:
      return state;
  }
};

export default counterReducer;

i’m trying to change only one property of the state object on an onclick function named like this

const store = createStore(reducer);

const App = () => {
  const addGood = () => {
    store.dispatch({
      type: "GOOD",
    });
  };
  const addBad = () => {
    store.dispatch({ type: "BAD" });
  };
  const addOk = () => {
    store.dispatch({ type: "OK" });
  };

  return (
    <div>
      <button onClick={addGood}>good</button>
      <button onClick={addOk}>ok</button>
      <button onClick={addBad}>bad</button>
      <button>reset stats</button>
      <div>good {store.getState().good}</div>
      <div>ok {store.getState().ok}</div>
      <div>bad{store.getState().bad}</div>
    </div>
  );
};

const renderApp = () => {
  ReactDOM.render(<App />, document.getElementById("root"));
};

renderApp();
store.subscribe(renderApp);

but when i try to change the value of any of the properties it doesn’t work , for example good , ok , bad but it crashes my app if i do so with good is not defined error

How to link JavaScript and HTML5 pages without tag?

I am trying to make a button for my webpage that changes the ENTIRE colour palette of the page with Code.org AppLab. The only problem is, code.org doesn’t allow the use of the <script> tag for “security reasons”. As far as I know the only way I can turn on CSS settings with a button is with getElementById(). If anyone knows how to activate CSS settings when a button is clicked without JS, how to link external JS files to an html file, or use inline JS all WITHOUT the use of the <script> tag please show me how. Any help would be greatly appreciated.

I’m begging someone to help me PLEASE.

if statement with multiple or conditions returning wrong value

I am pretty sure I am missing something basic here but I am having trouble with using multiple or or || operators with my if statement.

For some reason the if statement is not catching the name variable:

testword = "billy"

if ((testword != "billy") ||
    (testword != "tom") ||
    (testword != "sara") ||
    (testword != "michael")) {
console.log("none of the names match")
} else {
console.log("name found!")
}

When I try this I get none of the names match when I should get name found!

How to extract the data behind the interactive map/figure

There is an interactive map on website like this:
https://www.bostonglobe.com/2021/12/15/nation/these-are-all-massachusetts-towns-that-have-indoor-mask-mandates/#bgmp-comments

Where when the mouse hovers on it, it will highlight that area and show info for that certain area. How to get the data behind these and exact all the data to excel etc.? Is it written in Javascript?

example figure

Cannot read .length property of undefined (sometimes)

I’m trying to get checkbox values as an array, so later I can use them as part of a GET request.

Checkboxes are like this:

<input type="checkbox" name="diet" value="gluten"/>
<input type="checkbox" name="diet" value="vegetarian"/>
<input type="checkbox" name="diet" value="vegan"/>

I’ve (almost) catch them with this:

function getCheckboxValues(form){
    var values= [];
    var diet = form.diet;

    for (let i = 0; i <diet.length; i++) {
        if (diet[i].checked) {
            values.push(diet[i].value);
        }
    }
    return values;
}

Then I want to get them into:

var reqDiet = []; //global

So I can merge it into my get params

document.getElementById("submit-btn").addEventListener("click", function (){
    reqParams = "&diet="+reqDiet+",
    getRecipe(ASK_RECIPE, reqParams)
})
async function getRecipe(reqRecipe, reqParameters){
    let response = await fetch(reqRecipe+API_KEY+reqParameters);
    recipe = await response.json();

    let recipeStored = JSON.stringify(recipe);
    sessionStorage.setItem("recipe",recipeStored);
};

The problem is, if i run the getCheckboxValues("form_id") in console, it returns the correct array with items, but if i do something like

reqDiet = getCheckboxValues("form_id");

Console says :

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘length’)
at getCheckboxValues

What I can understund from this is that my program is not recognizing “diet.length” as an array when I do the last one, but do recognize it when i run the function by itself.
I prefer to do this in vanilla JS since I’m new here and trying to do this small projects.

P.S. any feedback in the post is apreciated since is my first one and i think is pretty large :/ sorry about that