I have a range of numbers as follows:
const a = ["11-50", "2-10", "1", "51-200"]
I would like to sort them properly like
["1", "2-10", "11-50", "51-200"]
I have tried both of these sort methods to no avail:
a.sort((a, b) => a - b)
a.sort()
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
I have a range of numbers as follows:
const a = ["11-50", "2-10", "1", "51-200"]
I would like to sort them properly like
["1", "2-10", "11-50", "51-200"]
I have tried both of these sort methods to no avail:
a.sort((a, b) => a - b)
a.sort()
I have script which creates table of content based on h2, h3 tags. In the code below it searches h2 tags and create links based on that. Problem is when any other tag span inside h2 tag, it does not work. I guess problem lies in the regex /<h([d]).*>s*[d]*s?[.]?s?([^<]+)</h([d])>/gi Since I am not good with regex, couldn’t fix it.
$(document).ready(function() {
var toc = "";
var level = 0;
var maxLevel = 3;
if (document.getElementById("contents") != null) {
document.getElementById("contents").innerHTML =
document.getElementById("contents").innerHTML.replace(
/<h([d]).*>s*[d]*s?[.]?s?([^<]+)</h([d])>/gi,
function(str, openLevel, titleText, closeLevel) {
if (openLevel > maxLevel) {
return str;
}
if (openLevel > level) {
toc += (new Array(2)).join("<ol>");
} else if (openLevel < level) {
toc += (new Array(level - openLevel + 1)).join("</ol>");
}
level = parseInt(openLevel);
var anchor = titleText.replace(/[^a-zA-Z]+/g, "-");
toc += "<li><a href="#" + anchor + "">" + titleText +
"</a></li>";
return "<a name="" + anchor + "">" +
"<h" + openLevel + "">" + str + "</h" + closeLevel + ">" + "</a>";
}
);
if (level) {
toc += (new Array(level + 1)).join("</ol>");
}
document.getElementById("toc").innerHTML += toc;
}
});
.blink {
animation: blinker 1s step-start infinite;
color: #ff0000;
font-weight: bold;
font-size: 0.85em;
}
@keyframes blinker {
50% {
opacity: 0;
}
}
<head>
<script type="text/javascript" src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
</head>
<body>
<div id="toc">
<div id="contents">
<h2>What is JS?</h2>
<h2 style="margin-top:1em;">Python Jobs - <span class="blink">New!</span></h2>
<h2 style="margin-top:1em;">
What is Python?
</h2>
</div>
</div>
</body>
I’m using openCV.js to find contours in an image, after which I apply some filters and simplification to those contours, then draw them as paths in an svg to plot with a pen plotter. I’m having trouble with one filter to remove points from generated points array that fall between the SVG bounds and the margin. I know that a clipping path would do this easily in the final result, but that only solve the problem visually. I need the paths themselves to not include those points so that a pen plotter won’t draw them. The current part of the code that is filtering my data is seen below.
(“margin” that I was talking about is set by a slider earlier in the code, referenced below as marginSlider.value)
// get contour points and push to array
let points = [];
for (let j = 0; j < contours.size(); ++j) {
const ci = contours.get(j);
points[j] = [];
for (let k = 0; k < ci.data32S.length; k += 2) {
let p = [];
p[0] = parseInt(ci.data32S[k]);
p[1] = parseInt(ci.data32S[k + 1]);
points[j].push(p);
}
}
// filter out contours with less than minNumPointsInContour (usually < 4)
let fPoints = points.filter(function (element) {
return element.length >= minNumPointsInContour;
});
// filter out points that fall between margin and SVG edge(THIS IS THE PROBLEM SPOT)
let mFPoints = fPoints.filter(
(element) => element[0] >= marginSlider.value
);
// simplify points before drawing
let sFPoints = [];
mFPoints.forEach((element) => {
let simplifiedPoints = simplify(element, toleranceSlider.value, true);
sFPoints.push(simplifiedPoints);
});
The main problem spot is let mFPoints = fPoints.filter((element) => element[0] >= marginSlider.value);– Currently I’m under the impression that this is only checking the x value of every element in the array and seeing if it is greater than or equal to margin. But i don’t know how to make it check 4 things over 1.
Since fPoints is a nested array containing point data, the array is organized as [[0,0],[10,10],[10,20],etc] (I know, I know, it would be better if they were an object with x and y labels but I have to flatten the thing at the end to parse into an SVG path so, nope).The output at that stage looks like:
[
[
[
860,
296
],
[
855,
301
],
[
854,
301
],
[
853,
302
],
[
852,
302
],
[
851,
303
],
[
850,
303
],
[
849,
304
],
[
848,
304
],
[
846,
306
],
[
846,
307
],
[
882,
307
],
[
883,
306
],
[
886,
306
],
[
887,
305
],
[
887,
302
],
[
882,
297
],
[
880,
297
],
[
879,
296
],
[
875,
296
],
[
874,
297
],
[
863,
297
],
[
862,
296
]
],
[
[
0,
0
],
[
0,
1619
],
[
1079,
1619
],
[
1079,
0
]
],
[
[
149,
146
],
[
150,
145
],
[
659,
145
],
[
660,
146
],
[
671,
146
],
[
672,
145
],
[
673,
146
],
[
685,
146
],
[
686,
145
],
[
689,
145
],
[
690,
146
],
[
696,
146
],
[
697,
145
],
[
755,
145
],
[
756,
146
],
[
761,
146
],
[
762,
145
],
[
928,
145
],
[
929,
146
],
[
930,
146
],
[
933,
149
],
[
933,
151
],
[
934,
152
],
[
934,
180
],
[
933,
181
],
[
933,
194
],
[
934,
195
],
[
934,
306
],
[
933,
307
],
[
933,
321
],
[
932,
322
],
[
932,
331
],
[
933,
332
],
[
933,
335
],
[
934,
336
],
[
934,
348
],
[
933,
349
],
[
933,
359
],
[
934,
360
],
[
934,
362
],
[
933,
363
],
[
933,
368
],
[
934,
369
],
[
934,
481
],
[
933,
482
],
[
933,
483
],
[
934,
484
],
[
934,
645
],
[
933,
646
],
[
933,
652
],
[
934,
653
],
[
934,
685
],
[
933,
686
],
[
933,
695
],
[
934,
696
],
[
934,
732
],
[
933,
733
],
[
933,
755
],
[
934,
756
],
[
934,
797
],
[
933,
798
],
[
933,
839
],
[
934,
840
],
[
934,
863
],
[
933,
864
],
[
933,
903
],
[
934,
904
],
[
934,
1086
],
[
933,
1087
],
[
933,
1090
],
[
934,
1091
],
[
934,
1128
],
[
933,
1129
],
[
933,
1137
],
[
934,
1138
],
[
934,
1150
],
[
933,
1151
],
[
933,
1154
],
[
934,
1155
],
[
934,
1335
],
[
933,
1336
],
[
933,
1349
],
[
932,
1350
],
[
932,
1379
],
[
933,
1380
],
[
933,
1417
],
[
934,
1418
],
[
934,
1419
],
[
933,
1420
],
[
933,
1451
],
[
934,
1452
],
[
934,
1468
],
[
933,
1469
],
[
933,
1470
],
[
930,
1473
],
[
929,
1473
],
[
928,
1474
],
[
865,
1474
],
[
864,
1473
],
[
762,
1473
],
[
761,
1474
],
[
522,
1474
],
[
521,
1473
],
[
519,
1473
],
[
518,
1474
],
[
323,
1474
],
[
322,
1473
],
[
301,
1473
],
[
300,
1474
],
[
254,
1474
],
[
253,
1473
],
[
247,
1473
],
[
246,
1472
],
[
232,
1472
],
[
231,
1473
],
[
219,
1473
],
[
218,
1474
],
[
199,
1474
],
[
198,
1473
],
[
173,
1473
],
[
172,
1474
],
[
151,
1474
],
[
150,
1473
],
[
149,
1473
],
[
146,
1470
],
[
146,
1469
],
[
145,
1468
],
[
145,
1320
],
[
146,
1319
],
[
146,
1296
],
[
145,
1295
],
[
145,
1003
],
[
146,
1002
],
[
146,
987
],
[
147,
986
],
[
147,
982
],
[
146,
981
],
[
146,
978
],
[
145,
977
],
[
145,
599
],
[
146,
598
],
[
146,
588
],
[
145,
587
],
[
145,
150
],
[
146,
149
],
[
146,
148
],
[
148,
146
]
]
]
What I would like to do is filter the fPoints array to only include points that the:
something about needing to check 2 different values in a nested array is really throwing me for a loop.
The full code is here if i didn’t include enough information
I was trying to do a basic date calculation as seen below. I want to find the remaining days in the month given the arguments below.
I thought I determined a solution, but there appears to be an extra 1/4 in the answer.
// returns last day of month
function lastDayOfMonth(date) {
return new Date(date.getFullYear(), date.getMonth() + 1, 0)
}
let day_start = new Date('2018-11-04');
let day_end = new Date('2019-01-10');
let day_last = lastDayOfMonth(day_start);
let total = 0;
if (day_end <= day_last) {
total = day_end - day_start;
} else {
total = day_last - day_start;
}
console.log(total / (1000 * 60 * 60 * 24)); // returns 26.25
This is a widget for a website, and I’m trying to figure out where am I supposed to put the style tags to edit any of the styles within the widget. I can get what I want with Chrome inspector tool, but I’m not sure where I need to add in the css. Thanks!
<script>var fm = "PHP";var to = "USD";var tz = "timezone";var sz = "1x1";var lg = "en";var st = "primary";var lr = "0";var rd = "0";</script><script src="//currencyrate.today/converter"></script><div style="text-align:right"><a href="https://currencyrate.today"></div>
Basically my question is whether there is any runtime difference between the two ways I list below of returning a cleanup function from a useEffect call. Is there a common best practice? I didn’t see anything about it in the reactjs docs so I’m curious if there is any advantage to either practice.
Specifically:
Is the call stack different aside from the extra anonymous function?
Are there circumstances where it might affect the this keyword?
Is one safer than the other?
import React, { useEffect } from 'react';
function aPlainJsFunction() {
console.log("Bar");
}
Example = () => {
useEffect(() => {
console.log("Foo");
return aPlainJsFunction; // **This Line**
}
return <Text>Example</Text>
}
-or-
import React, { useEffect } from 'react';
function aPlainJsFunction() {
console.log("Bar");
}
Example = () => {
useEffect(() => {
console.log("Foo");
return () => { // **These Lines**
aPlainJsFunction(); // **These Lines**
} // **These Lines**
}
return <Text>Example</Text>
}
In JavaScript it’s possible to define a function like this:
function func(a = 10, b)
{
return a + b;
}
How does one call this function by setting only the value for b?
hi as you know public server is down so i tried to host my on peer server
i already had a nodejs/express server up for chat … so i tried to integrate peer server on my chat server
here is simplified version of my code
const env = require('dotenv').config({ path: '.env' })
const express = require('express');
const { ExpressPeerServer } = require('peer');
const fs = require('fs');
const app = express();
const https = require('https');
const http = require('http');
let server ;
if(env.parsed.PROTOCOL === 'https')
{
// server = create https server
}
else
{
server = http.createServer( app);
}
const { Server } = require("socket.io");
const io = new Server(server);
const peerServer = ExpressPeerServer(server, {
debug: true
});
app.use('/peerjs', peerServer);
io.sockets.on('connection', function(socket) {
console.log(`@ connection | socket -> ${socket.id} |`);
});
var PORT = env.parsed.PORT || 8080
server.listen(PORT, () => {
console.log(`listining to port ${PORT} `);
});
the problem is after adding peer server to my code i cant establish any socket.io connection to the server … i get no errors in the server i just get the client side error
WebSocket connection to ‘ws://localhost:8080/socket.io/?EIO=4&transport=websocket’ failed: Invalid frame header
server is up and working , if i type localhost:8080 in the browser i will get the response
if i remove peer server code it would work fine
i can move peer server to separate code and run on a different port but i prefer to keep it in this code
any idea why this happening ?
I am adding MongoDB into my discord bot, I have it set so when something happens it does
await ticketSchema.findOneAndUpdate(
{
$inc: {
ticketNumber: 1
}
}
)
That all works fine, its when I try to find it later that it doesn’t work. I am trying to find the ticketNumber no matter what the number is so if its 16 it will show 16 if its 50 it will show 50 and so on. It would be great if I can store whatever the ticketNumber is when I find it into a variable.
This is what I currently have to try and find it not sure what to do lol im new to mongo and js
let result = ticketSchema.find({
ticketNumber: [42]
})
window.addEventListener("load", () => {
var uploader = new plupload.Uploader({
runtimes: "html5",
browse_button: "upload",
url: "../upload.php",
chunk_size: "10mb", // <<<<<<< Here is my problem
filters: {
max_file_size: "100gb",
.... THIS CODE HERE DOESN'T MATTER .....
});
This is my upload.php
function verbose ($ok=1, $info="") {
if ($ok==0) { http_response_code(400); }
exit(json_encode(["ok"=>$ok, "info"=>$info]));
}
if (empty($_FILES) || $_FILES["file"]["error"]) {
verbose(0, "Failed to move uploaded file.");
}
$filePath = __DIR__ . DIRECTORY_SEPARATOR . "videos";
if (!file_exists($filePath)) { if (!mkdir($filePath, 0777, true)) {
verbose(0, "Failed to create $filePath");
}}
$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : $_FILES["file"]["name"];
$filePath = $filePath . DIRECTORY_SEPARATOR . $fileName;
$dateformat = date("Y-m-d-H:i:s");
$fileSize = $_FILES["file"]["size"]; // <<<<< HERE IS MY PROBLEM
$title = pathinfo($fileName,PATHINFO_FILENAME);
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
$out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
if ($out) {
$in = @fopen($_FILES['file']['tmp_name'], "rb");
if ($in) {
while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}
}else{
echo "err";
}
@fclose($in);
@fclose($out);
@unlink($_FILES['file']['tmp_name']);
}else{
verbose(0, "Failed to open output stream");
}
if (!$chunks || $chunk == $chunks - 1) {
$rename = 'videos/'.generateKey($pdo); // simple function to generate random string ( 123asdjjn124 and so on)
$databaseName = str_replace('videos/','', $rename); // remove videos/ from the string
rename("{$filePath}.part", $rename);
$stmt = $pdo->prepare("INSERT INTO videos(title,size,date,link) VALUES(:title,:size,:date,:link)");
$stmt->bindParam(':title',$title,PDO::PARAM_STR);
$stmt->bindParam(':size',$fileSize,PDO::PARAM_STR); // <<<<< HERE IS MY PROBLEM
$stmt->bindParam(':date',$dateformat,PDO::PARAM_STR);
$stmt->bindParam(':link',$databaseName,PDO::PARAM_STR);
$stmt->execute();
}
verbose(1, "Upload OK");
Now when I upload a file, everything is entered beautifully but the size of the “chunk_size” is always entered instead of the correct size of the file. Does anyone have an idea why this is so? It also makes no difference if I change the file size, it always takes the “chunk_size”.
Any advice is helpful
Here I have another screenshot to illustrate how I mean it. https://prnt.sc/QW-zXtrb6RuY
I have indeed found many questions that sounded similar but none worked in my case.
Fairly new to OOP so please bear with me.
console.log(result) returns object below successfully:
[
{ name: 'horse', lid: 1 },
{ name: 'cat', lid: 2 },
{ name: 'dog', lid: 3 }
]
I’d like the output to be
[
{ name: 'horse' },
{ name: 'cat' },
{ name: 'dog' }
]
I know I can make the query fetch name only but what I am after is having full data set in result then choosing what properties to be displayed and what properties to be skipped for all objects.
My attempts so far
console.log(result[0].name + result[1].name + result[2].name); =>Success but what if I have 1000 objects ?
for (let i = 0; i <= result.length; i++) {console.log(result[i].name);}
=> Failed and returns Cannot read properties of undefined
result.forEach(arr => {
for (const key in arr) {
// console.log(arr[key].name);
console.log(arr[key]['name']);
}
});
Also failed and returns Cannot read properties of undefined
I have a comments block where each comment has a Like/Dislike button with counters.
My goal is update counters when i click at one of button. New data for a counters i got in JSON response. But my problem is i can’t update nearby counter because i don’t have access to it.
For example: if i click on LIKE button, i can update onlu LIKE’s counter.
Thank you
JSON like
{"ok": 200, "likes": 1, "dislikes": 0}
HTML
<span class="vote" data-href="{% url 'comment-vote' comment.pk %}" data-action="1">
<i class="fa-regular fa-thumbs-up"></i>
<span class="likes">
{% if comment.total_likes %}
{{ comment.total_likes }}
{% endif %}
</span>
</span>
<span class="vote" data-href="{% url 'comment-vote' comment.pk %}" data-action="0">
<i class="fa-regular fa-thumbs-down"></i>
<span class="dislikes">
{% if comment.total_dislikes %}
{{ comment.total_dislikes }}
{% endif %}
</span>
</span>
JS
function voteComment() {
var btn = document.querySelectorAll('.vote');
btn.forEach(function(elem) {
elem.addEventListener('click', function (e){
if (!e.target.classList.contains('fa-thumbs-up') &&
!e.target.classList.contains('fa-thumbs-down')) {
return;
}
e.preventDefault();
var action = elem.dataset.action;
var url = elem.dataset.href;
fetch(url,{
method: 'POST',
headers: {'X-CSRFToken': csrftoken,
'content-type': 'application/json'},
body: JSON.stringify({'action': action})
})
.then(response => response.json())
.then(data => {
console.log(data);
var likes = data.likes;
var dislikes = data.dislikes;
this.querySelector('.likes').innerHTML = likes || '';
// document.querySelector('.dislikes').innerHTML = dislikes || '';
})
.catch(error => {
console.log('error', error);
})
});
});
}
Iam so confuse with this task , so The program is when the student enters his code through html, that he must retrieve from the mongo database with his own information from the name of the course and grades, if one help meŘplease
I’ve a Todo list which is an array of objects with properities (id, title, description) Also I want to display title in v-autocomplete but when I do search for word it’s fine, but what I want is Doing search for description or title.
For Example: if I type programming, it will display to me Read books.
Template
<v-autocomplete
v-model="idTodo"
:items="todos"
label="search todo..."
item-value="id"
item-text="title"
/>
Script
visitCategories: [],
todos: [
{ id: 1, title: "Read books", description: "read books related to programming" },
{
id: 2,
title: "watch tutorials",
description: "watch tutorials in many platforms like Youtube, Udemy...",
},
],
idTodo: -1,
I am trying to get a Shopify liquid variable available for use in a javascript:
{% assign gtfs = 39900 | minus: cart.total_price | money %}
Further down in the javascript:
var feedback = '<div class="added-to-cart" id="ajaxify"><p class="ajaxified-cart-feedback ' + success + '">' + html + {{ gtfs | json }} + '</p></div>';
But for some reason it always returns 399,00.
It is like it won’t accept the math done in the top part when assigning gtfs.
I tried inserting cart.total_price instead in the script (just to check if the variable was present) – which returns the cart value as intended.
But I need to deduct the cart value from 399 and show that amount (to show how much up to free shipping) – e.g. “You are only 172 DKK away from free shipping”.