What do I do when git commit returns ‘On branch master nothing to commit, working tree clean’?
I had an existing git repository initialized, I wiped with using rm -rf .git then I type git init.
Could that be the reason why my files would not commit?
Category: javascript
Category Added in a WPeMatico Campaign
Combine an Array of Object to new Array
I have an Array of Objects that looks like this
[
{
"labNumber": 1,
"sampleRepeats": [
{"lab": "CORE","reason": "Equipment failure","count": 1}
]
},
{
"labNumber": 2,
"sampleRepeats": [
{"lab": "CORE","reason": "Tecan150 failed","count": 2}
]
}
]
How would I go about merging it into only one Array that looks like this?
[
{
"labNumber": 1,
"lab": "CORE",
"reason": "Equipment failure",
"count": 1
},
{
"labNumber": 2,
"lab": "CORE",
"reason": "Tecan150 failed",
"count": 2
}
]
Redirecting wss:// using DNS to another IP with an SSL certificate
Context
I’m running a Minecraft server network for my friends, where I host servers for them. They can interact with their server using a control panel in the browser.
I’m attempting to allow the browser to directly connect to my network using WebSockets. The network manager program (aka the bot) is setup to receive connections on port 50000. My website, example.com, redirects mc.example.com to my computer’s ip, using A records. The control panel then connects to mc.example.com:50000. Minecraft servers are on different ports, like mc.example.com:50001.
The Problem
Since https requires wss, I need to setup a trusted certificate on the WebSocket server. My plan was to copy the SSL certificate from the mc.example.com domain to the bot, allowing the connection.
However, AutoSSL will not generate a certificate for mc.example.com, since it is unable to connect to port 80.
Is it possible to allow AutoSSL to run, while still redirecting most ports to my custom ip? Or more broadly, how can I allow the control panel to connect to the bot via wss?
What I’ve tried
- Setting up another subdomain, bot.mc.example.com, that redirects to mc.example.com only for the service “_wss” and “_ws” (using SRV records). This allows AutoSSL to run, but doesn’t appear to properly redirect the WebSocket. (The browser would connect to bot.mc.example.com:50000.)
- Setting up an SRV record for the service “_autossl” or “_ssl” (not sure if these are real) on mc.example.com, to keep only AutoSSL on the normal host server.
- Trying to find a way to redirect a range of ports to another ip (didn’t find anything)
- Some other things I can’t remember
According to this documentation, WebSockets should be redirected with SRV records for _wss and _ws services.
* All of these tests were with ws, as I didn’t have the certificate yet, and it was easier
Other Information
The browser is using the standard JavaScript WebSocket.
The bot is a Java program using a WebSocket library, that is wrapped in a custom packet library.
The port forwarding and related stuff is working; I can get a ws connection to go through.
The website hoster is Bluehost (shared hosting), so I can’t use a standard port forward, website-server-side.
I believe stackoverflow is the correct stack exchange site for this, as I accept and welcome solutions that require programming on either end. (Ex.: a JavaScript variable I can change to check for SRV records.) Please let me know if there is a better one.
How to create a JS alert triggered by a Jinja object/form?
Disclaimer: I am new to this so I do not know how accurately I am asking questions. If you have any critiques about my descriptions I am open to them. Thanks
Stack in question: Python/Flask/Jinja, HTML, Javascript (jQuery)
I created a secure WTF login form in my Flask server. I would like to have an alert pop up if the login info is non-existent/incorrect. Being that I am using Jinja to unpack the Python form in the template (rather than HTML), I do not know how to send the request to my JavaScript (jQuery) function to get it to trigger the pop-up.
I have tried searching for answers and multiple attempts at rerouting in the server and getting JS to “see” the Jinja, but what I feel this is amounting to is that I will have to dismantle my form, which I do not want to do.
——————-Code——————–
#secure login form
class LoginForm(FlaskForm):
username = StringField(validators=[InputRequired(), Length(
min=4, max=20)], render_kw={"placeholder": "Username"})
password = PasswordField(validators=[InputRequired(), Length(
min=4, max=20)], render_kw={"placeholder": "password"})
submit = SubmitField("Login")
#this is the route in my flask server where I pass the python object to my template
@app.route("/login_page")
def show_login_page():
"""Display the login page"""
form = LoginForm()
return render_template("login.html", form=form)
#logic, if the username/pass is wrong/does not exist
#this was my attempt to use JSON to pass to my JS/jQuery to initiate the alert pop up
if user_obj == None:
bad_login_dict = {
"code": "Username or password incorrect"
}
return jsonify(bad_login_dict)
<!-- Jinja object in my template -->
<form action="/login_form" method="POST">
{{ form.hidden_tag() }}
{{ form.username() }}
<br>
{{ form.password() }}
<br>
<button id="login-button" class="btn grnbutton recipe-jump-button">Login</button>
</form>
<br>
<br>
<form action="/register_user">
// this is my last attempt at creating the alert
// this does not work, it just displays the json dictionary in the browser
function alertBadLogin(evt){
evt.preventDefault();
console.log("executing alert for bad login")
$.post('/login_form'), res => {
alert(res.bad_login_msg)}
}
Further note: I understand jQuery is a deprecated library. I do not intend on using it going forward. I was mislead into using it when I first created this project a year ago. Just if I can understand how to get Jinja and JS to talk to each other, that would help me immensely.
Pulling specific information from Google Sheets into different Google Site pages dynamically (not all info needed based on filtering)
Is there a way to pull specific information from a Google sheet into a Google site? I’m using Google sheets as a database and need to pull based on specific sorting fields to create live schedules for individual groups on a website. Alternatively, I could program within Sheets (I think) a page for each user group that is pulling from the master page and then publish/embed each page if that makes sense?
e.g. My sheet contains standard day, start time, end time, location, and details, but there are fields for user groups (i.e. students, staff, property, kitchen, etc.) I want to pull the events only for the tagged group and post them on their group’s website page). Note some events will be pulled for multiple pages.
Thank you!
Sarah
Processing alternative to dataPath() to load txt file
I’m trying to have this processing program work on my website, it works fine in the processing editor but displays this error in the devtools when I try to open the webpage: “processing.min.js:1419 Uncaught Processing.js does not support dataPath().”
I guess it means I need to find an alternative to dataPath(). How can I load my txt file then if not like this:
File file = new File(dataPath("field.txt"));
Full code for reference:
final int STAGE_WIDTH = 1200;
final int STAGE_HEIGHT = 950;
final int NB_PARTICLES = 60000;
final float MAX_PARTICLE_SPEED = 5;
final int MIN_LIFE_TIME = 20;
final int MAX_LIFE_TIME = 80;
final String IMAGE_PATH = "starrynight.jpg";
myVector tabParticles[];
float particleSize = 1.2;
PImage myImage;
int imageW;
int imageH;
color myPixels[];
FlowField ff;
GUI gui;
void setup()
{
size(1200, 950, P3D);
background(0);
initializeImage();
initializeParticles();
ff = new FlowField(5);
gui = new GUI(this);
gui.setup();
}
void initializeImage()
{
myImage = loadImage(IMAGE_PATH);
imageW = myImage.width;
imageH = myImage.height;
myPixels = new color[imageW * imageH];
myImage.loadPixels();
myPixels = myImage.pixels;
image(myImage, 0, 0);
}
void setParticle(int i) {
tabParticles[i] = new myVector((int)random(imageW), (int)random(imageH));
tabParticles[i].prevX = tabParticles[i].x;
tabParticles[i].prevY = tabParticles[i].y;
tabParticles[i].count = (int)random(MIN_LIFE_TIME, MAX_LIFE_TIME);
tabParticles[i].myColor = myPixels[(int)(tabParticles[i].y)*imageW + (int)(tabParticles[i].x)];
}
void initializeParticles()
{
tabParticles = new myVector[NB_PARTICLES];
for (int i = 0; i < NB_PARTICLES; i++)
{
setParticle(i);
}
}
void draw()
{
ff.setRadius(gui.getR());
ff.setForce(gui.getF());
particleSize = gui.getS();
float vx;
float vy;
PVector v;
for (int i = 0; i < NB_PARTICLES; i++)
{
tabParticles[i].prevX = tabParticles[i].x;
tabParticles[i].prevY = tabParticles[i].y;
v = ff.lookup(tabParticles[i].x, tabParticles[i].y);
vx = v.x;
vy = v.y;
vx = constrain(vx, -MAX_PARTICLE_SPEED, MAX_PARTICLE_SPEED);
vy = constrain(vy, -MAX_PARTICLE_SPEED, MAX_PARTICLE_SPEED);
tabParticles[i].x += vx;
tabParticles[i].y += vy;
tabParticles[i].count--;
if ((tabParticles[i].x < 0) || (tabParticles[i].x > imageW-1) ||
(tabParticles[i].y < 0) || (tabParticles[i].y > imageH-1) ||
tabParticles[i].count < 0) {
setParticle(i);
}
strokeWeight(1.5*particleSize);
stroke(tabParticles[i].myColor, 250);
line(tabParticles[i].prevX, tabParticles[i].prevY, tabParticles[i].x, tabParticles[i].y);
}
ff.updateField();
}
void mouseDragged() {
if(mouseX>950 && mouseY>830) return;
ff.onMouseDrag();
}
void keyPressed() {
//if (key =='s' || key == 'S') {
// ff.saveField();
//}
}
class myVector extends PVector
{
myVector (float p_x, float p_y) {
super(p_x, p_y);}
float prevX;
float prevY;
int count;
color myColor;
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
class FlowField {
PVector[][] field;
PVector[][] tempField;
int cols, rows;
int resolution;
int affectRadius;
float force;
File file = new File(dataPath("field.txt"));
FlowField(int r) {
resolution = r;
cols = 1200 / resolution;
rows = 950 / resolution;
field = new PVector[cols][rows];
tempField = new PVector[cols][rows];
init();
affectRadius = 3;
force = 1;
}
void setRadius(int r) {
affectRadius = r;
}
void setForce(float f) {
force = f;
}
void init() {
try {
for (int i=0; i<cols; i++) {
for (int j=0; j<rows; j++) {
tempField[i][j] = new PVector(0, 0);
}
}
readField();
}
catch(Exception e) {
for (int i=0; i<cols; i++) {
for (int j=0; j<rows; j++) {
field[i][j] = new PVector(0, 0);
}
}
}
}
PVector lookup(float x, float y) {
int column = int(constrain(x/resolution, 0, cols-1));
int row = int(constrain(y/resolution, 0, rows-1));
return PVector.add(field[column][row],tempField[column][row]);
}
void drawBrush() {
pushStyle();
noFill();
stroke(255, 255, 255);
ellipse(mouseX, mouseY, affectRadius*10, affectRadius*10);
popStyle();
}
void drawField(float x, float y, PVector v) {
int column = int(constrain(x/resolution, 0, cols-1));
int row = int(constrain(y/resolution, 0, rows-1));
for (int i=-affectRadius; i<=affectRadius; i++) {
for (int j=-affectRadius; j<=affectRadius; j++) {
if (i*i+j*j<affectRadius*affectRadius) {
try {
tempField[column+i][row+j].add(v).mult(0.9);
}
catch(Exception e) {
}
}
}
}
}
void updateField(){
for (int i=0; i<cols; i++) {
for (int j=0; j<rows; j++) {
tempField[i][j].mult(0.992);
}
}
}
void onMouseDrag() {
PVector direc = new PVector(mouseX-pmouseX, mouseY-pmouseY).normalize();
drawField(pmouseX, pmouseY, direc.mult(force));
}
void saveField() {
try {
FileWriter out = new FileWriter(file);
for (int i=0; i<cols; i++) {
for (int j=0; j<rows; j++) {
out.write(field[i][j].x+","+field[i][j].y+"t");
}
out.write("rn");
}
out.close();
}
catch(Exception e) {
}
}
void readField() throws IOException {
try {
BufferedReader example = new BufferedReader(new FileReader(file));
String line;
for (int i = 0; (line = example.readLine()) != null; i++) {
String[] temp = line.split("t");
for (int j=0; j<temp.length; j++) {
String[] xy = temp[j].split(",");
float x = Float.parseFloat(xy[0]);
float y = Float.parseFloat(xy[1]);
field[i][j] = new PVector(x, y);
}
}
example.close();
}
catch(Exception e) {
throw new IOException("no field.txt");
}
}
}
import controlP5.*;
class GUI {
ControlP5 cp5;
Slider sliderR;
Slider sliderF;
Slider sliderS;
GUI(PApplet thePApplet){
cp5 = new ControlP5(thePApplet);
}
void setup(){
cp5.setColorBackground(0x141414);
sliderR = cp5.addSlider("Radius")
.setPosition(980,890)
.setRange(1,20)
.setValue(12).setSize(150,25);
sliderF = cp5.addSlider("Force")
.setPosition(980,918)
.setRange(0.1,0.5)
.setValue(0.3).setSize(150,25);
sliderS = cp5.addSlider("Particle Size")
.setPosition(980,862)
.setRange(0.8,2)
.setValue(1.5).setSize(150,25);
}
int getR(){
return int(sliderR.getValue());
}
float getF(){
return sliderF.getValue();
}
float getS(){
return sliderS.getValue();
}
}
Styling isn’t applying in Javascript
I’m trying to hide the text of a button and show a spinner in its place while processing something. However no styling is applied even though the classes get properly toggled to the right value as I see on the Developer Tools.
function toggleSpinner() {
$('button span').toggleClass('display-none');
$('button .fa-spinner').toggleClass('display-none');
}
function generateGrid(size) {
let arr = getRandomNumbers(size);
toggleSpinner(); // <--- HIDE TEXT SHOW SPINNER
$('.grid').empty();
let html = '';
arr.forEach((element) => {
html += '<div class="box">' + element.toLocaleString() + '</div>';
});
$('.grid').append(html);
toggleSpinner(); // <--- HIDE SPINNER SHOW TEXT
}
Generating the grid sometimes takes like 3 seconds depending on the size of the grid and during that time, I would like to show the spinner on the button instead of the text.
Filter out and count duplicates in array, return object
I have data that looks like this
let countsRaw= [ 7, 8, 7, 6]
I would like the output to look like this
let countsObj = {
6: {count : 1, filterState : false},
7: {count : 2, filterState : false},
8: {count : 1, filterState : false},
}
I have tried numerous different orientations but am not getting the output I expect from the code below, any explanation or direction would be greatly appreciated.
let countsObj = {};
countsRaw.forEach((x) => ({
count: (countsObj[x] = (countsObj[x] || 0) + 1),
}));
the result is
countObj = {6: 1, 7: 2, 8: 1}
I can’t figure out why the nested objects are not being added.
thansk (:
Convert this jQuery code to JavaScript: sorting HTML dropdown
can someone convert this jQuery code to JS? It is to sort the dropdown. A new code will also work.
var sel = $('#id_shipping_address-administrative_area');
var selected = sel.val(); // cache selected value, before reordering
var opts_list = sel.find('option');
opts_list.sort(function(a, b) { return $(a).text() > $(b).text() ? 1 : -1; });
sel.html('').append(opts_list);
sel.val(selected); // set cached selected value
Here is the HTML
<select class="form-field__widget" name="country" aria-describedby="id_country_errors" autocomplete="country" required="" id="id_country">
<option value=""> </option>
<option value="AF">
Afghanistan
</option>
<option value="AX">
Åland-Inseln
</option>
<option value="AL">
Albanien
</option>
<option value="DZ">
Algerien
</option>
<option value="AS">
Amerikanisch-Samoa
</option>
<option value="AD">
Andorra
</option>
<option value="AO">
Angola
</option>
.............
</select>
Thank you in advance.
How do I store the JSON response such that I can use it in other functions (React & JS)?
fetchData.js -> File where we fetch the data. This file is later imported and the functions will be used to display the fetched data.
import { weatherAPIConfig } from "../weatherAPIConfig"
export async function fetchWeatherForecast(cityName) {
let URL = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&units=metric&appid=${weatherAPIConfig.key}`
try {
const fetchWeatherForecast = await fetch(URL)
const weatherForecastJSON = await fetchWeatherForecast.json()
return weatherForecastJSON
}
catch (error) {
console.log("Could not find given city");
return "Could not find given city"
}
}
export function getWeatherDescription(weatherForecastJSON) {
return weatherForecastJSON.weather[0].description;
}
export function getWeatherTemperature(weatherForecastJSON) {
return weatherForecastJSON.main.temp
}
export function getWeatherWindSpeed(weatherForecastJSON) {
return weatherForecastJSON.wind.speed;
}
export function getWeatherHumidity(weatherForecastJSON) {
return weatherForecastJSON.main.humidity
}
Row.js -> The file where the temperature etc. is displayed in div
import React from 'react'
import {getWeatherDescription, getWeatherHumidity, getWeatherTemperature, getWeatherWindSpeed, fetchWeatherForecast} from '../../functions/fetchData'
import { weatherAPIConfig } from '../../weatherAPIConfig';
function Row() {
return (
<div>
<div>API-key: {weatherAPIConfig.key}</div>
<div>Result: {getWeatherDescription(fetchWeatherForecast("London"))}</div>
</div>
)
}
export default Row;
…………………………………………………………………………….
setState in UseEffect doesn’t update state? [duplicate]
So basically I just need to pass id I get in the userId state. Getting the id works fine – the line console.log(id) gives me exactly the result I need, but then I do setState(id) and then console.log(userId) gives me undefined.
Why is it happening and how can I fix it?
const [userId, setUserId] = useState<string>();
useEffect(() => {
if (!isAuthenticated) {
restApiService.keycloak.onAuthSuccess = () => setIsAuthenticated(true);
}
if (isAuthenticated) {
restApiService.getUserRole().then((role) => {
if (role === "member") {
setHasAccess(false);
} else {
setHasAccess(true);
}
});
}
if (!userId) {
restApiService.getLoggedUserId().then((id) => {
console.log(id)
if (id) {
setUserId(id)
console.log(userId)
}
})
}
}, [isAuthenticated])
Why is the style property empty of this HTMLStyleElement?
I have an html string that I getting from a backend server.
I am trying to view css properties and extract the value of a first occurrence of a background-color in a HTMLStyleElement. However the format of the HTMLStyleElement is different than I expected.
How might I find the first occurrence of the property in the css without searching through the string if possible?
React Virtualized List losing focus after arrow key scrolling within container
I’m using react-window library as a way of virtualizing an item list. And while I’m making it accessibility proof by using arrow keys to navigate through the items, I noticed that at some point, the focus on the items would be lost. Falling back to body element.
At first I thought it was something in the app causing it, but when I checked the library demo I noticed it’s replicable there.
The way to test it is just click in the container and start using the arrow keys to navigate/scroll through the list. You will see that eventually the focus on the scrollable container will be lost.
I thought that it could possibly be some rendering time issue on the virtualized items, letting some space or time to render so you would move smoothly without losing focus, especially if you go fast.
So what I attempted is whenever I move to an item up/down, I would scroll the container so that the item is always centered, kind of forcing the list to render more and more items. But unfortunately it didn’t work.
Do you guys know how to achieve this without losing focus? Any ideas? I can’t have an accessibility experience where the person loses focus out of nowhere.
Thanks in advance.
what concepts I should look for create a cellphone app or UWP connected to Netflix? [closed]
I hope you are all well
I would like to know what concepts I should look for create a cellphone app or UWP(I am way more familiar with this last one) connected to Netflix, this App should allow me to search for content within the Netflix library(This search would be through different filters which I will determine later).
My problem is that when I look on Google I only find concepts or information regarding the creation of Netflix clones or movies streaming apps.
As additional information, I’m currently in my first year of Computer Programming diploma, so I know some concepts like working with databases, OOP. But so far, we haven’t created anything connected to a real program(in this case, Netflix) or something where you must get the info in real-time, so I don’t know where to start. I tried to contact my teachers but they are really busy with their current students(I am on my spring break and I will return to classes in September).
Note: Within the tags, I added the languages with which I am familiar.
Thank you very much for your time.
Nicolas.
Chart.js label callbacks are never called
I’m working with Chart.js 3.8.0.
I’m trying to create custom tooltip text.
new Chart($('#truck-dwell'), {
type: 'scatter',
data: {
datasets: [{
label: 'Dwell Time (Minutes)',
data: response,
backgroundColor: Colors.Red,
}],
},
options: {
scales: {
x: {
type: 'linear',
position: 'bottom'
}
},
plugins: {
tooltips: {
callbacks: {
label: function(ctx) {
return 'Hello, World!';
}
}
}
}
}
});
Although I’ve found several sources say this is the newer, version 3 syntax, a breakpoint on my label function shows it is never called.
What am I missing?
