This is a simple JavaScript code of print even number, but I want the output result as a array : [4 8 2]
var arr = [4, 8, 5, 9, 3, 7, 2]
for(var i =0; i<arr.length; i++){
if(arr[i]%2==0){
console.log(arr[i])
}
}
Output:
4
8
2
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
This is a simple JavaScript code of print even number, but I want the output result as a array : [4 8 2]
var arr = [4, 8, 5, 9, 3, 7, 2]
for(var i =0; i<arr.length; i++){
if(arr[i]%2==0){
console.log(arr[i])
}
}
Output:
4
8
2
I’m still learning in the world of web development and would like to alter the WebUI of stable diffusion: https://github.com/AUTOMATIC1111/stable-diffusion-webui
I know it should be possible to change around or delete buttons etc, but I don’t know where to start. Where is the HTML code located in this project? I can’t seem to find it.
I appreciate any help!
I want get value from .env file on reactjs 18.2.
REACT_APP_API_URL = localhost:4000
My code is on app.js 9-line => console.log(process.env.REACT_APP_API_URL);
import "./App.css";
import { BrowserRouter as Router } from "react-router-dom";
import Routers from "./Router";
function App() {
console.log("======================");
console.log(process.env.REACT_APP_API_URL);
console.log("======================");
return (
<Router>
<Routers />
</Router>
);
}
export default App;
But browser return me on console Undefined
having this go function
func WasmCount(this js.Value, args []js.Value) interface {} {
const firstParam = args[0].ArrayOfString() // <-- I want to achieve this
return firstParam.Length
}
and I will call it from js like this
WasmCount(["a", "b"]) // it should return 2
I can pass String and Int but didn’t find a way to pass an Array of <T>
I want to add height and width to each image in a page. I am using the JS code below. It is adding height and width (which can be seen on console) but PageSpeed Insights keep on showing this error – “Image elements do not have explicit width and height”.
I am using lazysizes JS as well for that I need to replace src with data-src and add lazyload class. It seems to be adding height and width to an image does not work with lazy loaded images. Because when I removed lazyload class, it works.. Any solution to set width and height to an image along with lazy load functionality. I can’t do it manually as I have many images in a lot of articles.
function addLazyloadClassToImages() {
var images = document.querySelectorAll('img');
for (var i = 0; i < images.length; i++) {
var image = images[i];
if (!image.hasAttribute('height') && !image.hasAttribute('width')) {
if (image.complete) {
image.setAttribute('width', image.naturalWidth);
image.setAttribute('height', image.naturalHeight);
} else {
image.addEventListener('load', function() {
this.setAttribute('width', this.naturalWidth);
this.setAttribute('height', this.naturalHeight);
});
}
}
image.setAttribute('data-src', image.getAttribute('src'));
image.removeAttribute('src');
image.classList.add('lazyload');
}
}
document.addEventListener('DOMContentLoaded', addLazyloadClassToImages);
<img alt="Sample Image" border="0" title="" src="https://img.freepik.com/free-vector/hello-wording-comic-speech-bubble-pop-art-style_1150-39959.jpg">
In the picture I have tabs
with responsive query nav tabs scroll for see other navs
I want show active tab when reload page in responsive mode but now show first of the nav tab
<div class="nav tabs-list" id="trips-tab" role="tablist">
<a id="pills-home-1" data-toggle="pill" href="#home1" role="tab" aria-controls="home1" aria-selected="false">پیمایشی</a>
<a id="pills-home-2" data-toggle="pill" href="#home2" role="tab" aria-controls="home2" aria-selected="false">طبیعت گردی</a>
<a id="pills-home-3" data-toggle="pill" href="#home3" role="tab" aria-controls="home3" aria-selected="false">ماجراجویی</a>
<a class="active" id="pills-home-4" data-toggle="pill" href="#home4" role="tab" aria-controls="home4" aria-selected="true">
<img src="assets/img/campground.svg">
کمپینگ
</a>
<a class="" id="pills-home-5" data-toggle="pill" href="#home5" role="tab" aria-controls="home5" aria-selected="false">کوهنوردی</a>
<a class="" id="pills-home-6" data-toggle="pill" href="#home6" role="tab" aria-controls="home6" aria-selected="false">دوچرخه</a>
<a class="" id="pills-home-7" data-toggle="pill" href="#home7" role="tab" aria-controls="home7" aria-selected="false">تور کودک</a>
</div>
I want show active tab when open the page in mobile like the second picture
I need to draw multiple circles placed on parabola.
Currently I come with a naive solution
const numberOfCircles = 20 const curve = 30 const circleRadius = 10 const spaceBetween = 5 const width = (numberOfCircles - 1) * (2 * circleRadius + spaceBetween) const a = curve / ((width / 2) * (width / 2)) const points = [] for (let i = 0; i < numberOfCircles; i++) { const x = i * (2 * circleRadius + spaceBetween) const y = a * (x - width / 2) * (x - width / 2) points.push({ x: x, y: y }) }
with the following result
However I need circles to be placed on the equal distances on the curve (see picture below).
Is there some not too complicated way to approach this?
I have a JavaScript code that includes a feature that relies on 2 HTML elements to function properly. However, there are scenarios where these elements may not be present in the HTML file, depending on the context or use case.
I would like to modify my JavaScript code to conditionally execute the feature based on the presence of the required HTML elements. If the elements are not present, I want to skip the feature to prevent errors and improve the efficiency of the program.
Here is what I came up with:
const elementA = document.getElementById("element-a");
const elementB = document.getElementById("element-b");
function executeFeature() {
// Check if required HTML elements are present
if (!elementA || !elementB) {
return; // Skip feature execution if elements are not present
}
// Rest of the feature code...
}
executeFeature();
However I am confused if the above code snippet really checks in the HTML that elements are present, or if it just checks that elements are declared in the JS file.
const elementA = document.getElementById("element-a");
const elementB = document.getElementById("element-b");
The whole point of this question is to improve the code performance so that the code is not executed where it is not required.
Thanks!
I am trying to recreate minesweeper in html,css and javascript and I got to the part where I need to check the neighboring cells to see if it is a bomb and count it, but it doesn`t seem to check the right cells. I am using a cell class with an x, y, isBomb, isChecked and a number for how many of its neighbors is a bomb, also I am using a 1D array to store the grid of cells
So my question is if it is something wrong with this function or should I just rewrite the code using a 2D array insted
function checkN(x, y){
let count = 0
if(cells[x+y*coll].isBomb == true){
return
}
cells[x+y*coll].isChecked = true
for(let i = -1; i<=1; i++)
for(let j = -1; j<=1; j++){
if(
(x+i >= 0 && x+i < coll) &&
(y+j >= 0 && y+j < rows) &&
(i != 0 || j != 0)
){
if(cells[x+i + (y+j)*rows].isBomb == true)
count++
}
}
if(count != 0)
cells[x + y*coll].number = count
}
result of using the checkN function for every cell
I have tried changing the values a bit, like add an -1 there add an +1 there, but still it doesn`t count right
How to implement a slider with automatic infinite scrolling in pure js without using css animation?
Example:
https://margelo.io/
On this site, where is the block with logos, if they do not fit in the viewport -> this animation is performed
I have a project where I need to get a bunch of item data via an API for an online game’s marketplace. The way their system works plus the amount of calls I’d need to make means that doing it all from within my application isn’t possible.
I was using Google Sheets with a script + timer, but it’s long past time I migrated to an actual database system for better support, ability to optimize, and of course, to learn and grow.
So, I’m using and learning MongoDB and am working to write a Trigger function(s) to auto-update these documents every x amount of time. This means using passing the itemId for each doc (item) into an async function that fires an HTTP Request out to an endpoint and using that value to set a field.
What I have tried currently looks like:
exports = async function()
{
var coll = context.services.get("myCluster").db("myDB").collection("myColl");
items.updateMany(
{},
[{ $set: { lastUpdate: new Date(), itemPrice: await getPrice($"itemId") } }])
.then(result =>
{
// some logging
})
.catch block to log errors
};
async function getPrice(itemId)
{
// do an await context.http.get() with the url + itemId
// parse out the JSON and return the data I want
}
I know I can use a field to set another field and have had no trouble with that. I could replace the await getPrice with "$itemId" and it would copy the value from the one field to the other.
If I place the field string into a function, however, it seems to resolve the function and just send the string literal instead of evaluating the field for the result first. So, I’m guessing this is some issue with how/when prvalues (or Mongo/Atlas/JS’s version of them) are evaluated?
It feels like using the Aggregation Pipeline is the right move here considering what the documentation says about it, but I can’t find anything talking about calling functions using field values as parameters.
So I encountered a problem with Next.js / React and mutating an array that is saved in state. I can’t really wrap my head around it and figure out why it happens and how to fix it.
I tried Google search and stackoverflow but to be honest this didn’t help much and I am unsure what the exact problem is and what to do about it.
So here is what I was trying to achieve when the problem occurred.
I built a simple Chatbot / ChatGPT implementation with Next.js that allows me to input a question or request, and send it to my API / Backend which would then query ChatGPT itself and return the result.
For details of the implementation see the code below.
Here is a breakdown of how it should work:
What actually happens is that first I can see the input message, but after the fetch has completed it gets overwritten by the result message and I don’t see both.
I am not completely sure why this happens. I know that React doesn’t change the state immediately, but it happens asnyc. This could be one reason.
But I suspect the main reason is the closure that is formed to update the state. It uses the spread syntax to add the new message to the already existing array of messages. And in both cases when I update the array with the input and the result message, the closure does not have the updated state (array of messages), but it referes to an empty array. This is probably why the mutation of the array twice is not working and are overwriting each other, correct?
So is there an actual way to fix this?
Chatbot.tsx:
import {useState} from "react";
export default function Chatbot() {
const [inputMessage, setInputMessage] = useState('');
const [messages, setMessages] = useState([]);
/**
* Push a new message to array of messages
* @param {string} text
*/
const addMessage = (text) => {
setMessages([
...messages,
text,
])
}
const queryChatbot = () => {
// Add input message / question as new message
addMessage(inputMessage);
fetch('/api/chatbot', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
inputMessage,
}),
})
.then(response => response.json())
.then(data => {
if (data.response) {
// For successful response: Add response as new message
addMessage(data.response.output.response);
} else {
// Otherwise add error as new message
addMessage('Sorry, no response possible.');
}
})
.catch(error => {
// In error case we add a new message with an error
addMessage('Sorry, an error ocurred.');
});
}
return <>
<input type="text" placeholder="Send a message" onChange={(event) => setInputMessage(event.target.value)} />
<button onClick={queryChatbot}>Send message</button>
{messages.map(message => (
<p>{ message }</p>
))}
</>
}
I’m in my first year of compsci and i have to make a website. I want to make it more unique by giving it a secret feature where if my lecturer opens the page, keeps it open, doesnt touch it, comes back like 5 mins later and its a completely different and unique page. Is there a js or html script that can do this? Any help is much appreciated
I’ve tried to search it up but perhaps what I want is too specific? cause i cant find anything
I practiced a debounce on bigfrontend, there is an example in the stem of the question, each dash represents the waiting time, the question is about the following
The question is https://bigfrontend.dev/problem/implement-basic-debounce
My understanding is that each time the event timer is executed will be retimed, then for the E event, why the F event is not executed, while the G event is executed, is my understanding of the problem is wrong?
I want to know if my understanding is wrong.
What I’m trying to do is create a User object first and then another Team Leader object in which the user attribute is linked to the same User object created. However, what happens is the Create Team Leader is being called BEFORE the Create User is done processing.
Here is the Team Leader Model:
class TeamLeader(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
id = models.AutoField(primary_key=True)
firstName = models.CharField(max_length=100,blank=True)
lastName = models.CharField(max_length=100,blank=True)
email = models.CharField(max_length=100,blank=True)
username = models.CharField(max_length=100,blank=True)
employeeRole = models.CharField(max_length=100,blank=True)
bio = models.TextField(blank=True)
profileimg = models.ImageField(upload_to='profile_images', default='blankprofile.png')
location = models.CharField(max_length=100,blank=True)
def __str__(self):
return self.user.username
I’m sending two post requests to my APIs using fetch in Javascript. Below is my code for the post requests. The first one creates the User object first, then the next one for the Team Leader object.
let userUrl = homeUrl + 'api/createuser/'
fetch(userUrl,{
method:'POST',
headers:{
'Content-type':'application/json',
'X-CSRFToken':csrftoken,
},
body:JSON.stringify({"username": username,
"first_name": firstname,
"last_name": lastname,
"email": email,
"password": password1,
"employeeRole": employeeRole,
"teamLeader": teamLeader,
}),
}
)
if (employeeRole == 'Member') {
var regisUrl = homeUrl + 'api/createMember/';
} else {
var regisUrl = homeUrl + 'api/createTeamLeader/';
}
fetch(regisUrl,{
method:'POST',
headers:{
'Content-type':'application/json',
'X-CSRFToken':csrftoken,
},
body:JSON.stringify({"username": username,
"first_name": firstname,
"last_name": lastname,
"email": email,
"password": password1,
"employeeRole": employeeRole,
"teamLeader": teamLeader,
}),
}
)
Here are my api endpoints for the /createuser and /createTeamLeader. I’ve added print statements just to see which lines of codes are being processed.
@api_view(['POST'])
def createUser(request):
serializerUser = UserSerializer(data=request.data)
print('OUTSIDE SERIALIZER VALID')
serializerUser.is_valid()
print(serializerUser.errors)
if serializerUser.is_valid():
print('INSIDE SERIALIZER VALID')
username = serializerUser.validated_data['username']
password = serializerUser.validated_data['password']
email = serializerUser.validated_data['email']
user = User.objects.create_user(username, email, password)
user.first_name = serializerUser.validated_data['first_name']
user.last_name = serializerUser.validated_data['last_name']
user.save()
print('success creating user')
return Response(serializerUser.data)
@api_view(['POST'])
def createTeamLeader(request):
serializer = TeamLeaderSerializer(data=request.data)
print('CREATING TEAM LEADER')
if serializer.is_valid():
username = serializer.validated_data['username']
email = serializer.validated_data['email']
employeeRole = serializer.validated_data['employeeRole']
newAddedUser = User.objects.get(username = username)
teamleader = TeamLeader.objects.create(user=newAddedUser,firstName=newAddedUser.first_name,lastName = newAddedUser.last_name, email=email,username=username, employeeRole = employeeRole)
teamleader.save()
return Response(serializer.data)
Here is the output from the terminal. The “Create Team Leader” is called before the User object is done creating.
System check identified no issues (0 silenced).
July 08, 2023 - 17:31:28
Django version 4.2.2, using settings 'officeIS.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
OUTSIDE SERIALIZER VALID
{}
[08/Jul/2023 17:31:31] CREATING TEAM LEADER"GET /api/allTeamLeaders/ HTTP/1.1" 200 2
INSIDE SERIALIZER VALID
[08/Jul/2023 17:31:31] "GET /api/allUserLogins/ HTTP/1.1" 200 2367
[08/Jul/2023 17:31:31] "GET /api/allUserLogins/ HTTP/1.1" 200 2367
Internal Server Error: /api/createTeamLeader/
Traceback (most recent call last):
File "C:Usersuseranaconda3libsite-packagesdjangocorehandlersexception.py", line 55, in inner
response = get_response(request)
File "C:Usersuseranaconda3libsite-packagesdjangocorehandlersbase.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:Usersuseranaconda3libsite-packagesdjangoviewsdecoratorscsrf.py", line 56, in wrapper_view
return view_func(*args, **kwargs)
File "C:Usersuseranaconda3libsite-packagesdjangoviewsgenericbase.py", line 104, in view
return self.dispatch(request, *args, **kwargs)
File "C:Usersuseranaconda3libsite-packagesrest_frameworkviews.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:Usersuseranaconda3libsite-packagesrest_frameworkviews.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:Usersuseranaconda3libsite-packagesrest_frameworkviews.py", line 480, in raise_uncaught_exception
raise exc
File "C:Usersuseranaconda3libsite-packagesrest_frameworkviews.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "C:Usersuseranaconda3libsite-packagesrest_frameworkdecorators.py", line 50, in handler
return func(*args, **kwargs)
File "C:UsersuserDesktopWORKProgramming CareerofficeISOfficeIScoreviews.py", line 131, in createTeamLeader
newAddedUser = User.objects.get(username = username)
File "C:Usersuseranaconda3libsite-packagesdjangodbmodelsmanager.py", line 87, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:Usersuseranaconda3libsite-packagesdjangodbmodelsquery.py", line 637, in get
raise self.model.DoesNotExist(
django.contrib.auth.models.User.DoesNotExist: User matching query does not exist.
[08/Jul/2023 17:31:31] "POST /api/createTeamLeader/ HTTP/1.1" 500 106888
success creating user
[08/Jul/2023 17:31:31] "POST /api/createuser/ HTTP/1.1" 200 111
I’m really not sure if my interpretation for the output in the terminal is correct. If it is, how do I fix this? Any suggestions on how to design the backend better but still using DRF?
Tried excluding the createTeamLeader post request and just leave the createuser post request, and it works just fine.