jeudi 31 décembre 2020

How to sync my local database of my web app to database of my deployed web app?

So my project is a school distributed system based on django web framework. My web app will be deployed in every school on their local computers. And all of the data on those computer will by synced with a main server on my side. What I want is how to implement a solution that would help me sync files/data with my server such that if some file/data is changed on a local computer it'll replicate itself in our server and if I change some file/data on my server, it'll update on those local computers whenever they get an internet connection.




Django Product object has no attribute author

hi i am not new to django but i can not find the error . may be a new pair of eyes can saw that i just import usertestmixin and wrote the function test_func() but it is not working i do not know why it gave me the error 'Product' object has no attribute 'author'

my models for product is:

class Product(models.Model):
title = models.CharField(max_length=110)
slug = models.SlugField(blank=True, unique=True)
price = models.DecimalField(decimal_places=2, max_digits=6)
discount_price=models.FloatField(blank=True, null=True)
size = models.CharField(choices=SIZE_CHOICES, max_length=20)
color = models.CharField(max_length=20, blank=True, null=True)
image = models.ImageField(upload_to=upload_image_path)
description = models.CharField(max_length=1000)
featured = models.BooleanField(default=False)
time_stamp = models.DateTimeField(auto_now_add=True)

and my models.py for user is:

class User(AbstractBaseUser):
email = models.EmailField(max_length=255 ,unique=True)
full_name = models.CharField(max_length=255, blank=True, null=True)
active = models.BooleanField(default=True)  #can login
staff = models.BooleanField(default=False)  #staff user non super user
admin = models.BooleanField(default=False)  #superuser
time_stamp = models.DateTimeField(auto_now_add=True)

and my views.py is:

class ProductUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Product
template_name = 'product-form.html'
fields = ['title', 'price' , 'size' , 'color', 'image' , 'description']
def form_valid(self, form):
    form.instance.author = self.request.user
    return super().form_valid(form)

def test_func(self):
    self.object = self.get_object()
    return self.request.user == self.object.author

it gave me the error:enter image description here




Recommendations for backend [closed]

I'm just starting to do some backend as hobby, but I have a big question,

Would it be better to learn a server-side language like NodeJS or PHP or try to have a website in HTML, CSS and Vanilla JS and run my Python scripts from there?

I have been using Python for a year and a half and I'm new in the web development and I haven't learn PHP or NodeJS so I would like your recommendations on this




Modeling relational database tables for tracking status of stages and tasks within stages

I'm trying to model a relational database for a web-based, project tracking app. In the interface, I want to display all of the stages of the project and all the tasks within those stages - for example:

Stage 1: Planning do these things
  Task 1: do this planning activity first
  Task 2: do this planning activity second
Stage 2: Start coding based on requirements
  Task 1: do this coding requirement first
  Task 2: do this coding requirement second

At the end of each task I would have a drop-down for users to select the status of each task (Not-Started, In-Progress, Blocked, Completed)

For tables to model the stages and tasks that will populate the interface, I'm thinking something like these:

tbl_stages
  id
  stage

tbl_tasks
  id
  stage_id
  task

The tables for storing projects and statuses would look something like this:

    tbl_projects
      Project_ID
      Project_Name
      Status_ID

    tbl_statuses
      id:
      s1_t1
      s1_t2
      s1_t3
      s2_t1
      s2_t2 

So tbl_projects is the primary table and it would have a 1-to-1 relationship with tbl_statuses. The part I'm not sure of is how or do I even need to relate tbl_statuses to tbl_stages and tbl_tasks. I believe that the relationship between tbl_statuses and tbl_stages would be many-to-many. But maybe I just need to track tasks in tbl_statuses because the tbl_stages values can be calculated based on the state of their child tasks. I'm thinking I need some other relational tables just to track many-to-many relationships also.

Hope someone can provide guidance, I'm feeling out of my league at this point.

Here is visio diagram of what I'm thinking so far:

enter image description here




Is my AJAX Call function correct for Removal of Table Row?

I'm having trouble figuring out why my "Remove" button is not working as intended. I'm working on a webpage. Long story short, the main page contains a table whose rows are added via user input, some SQL database queries, and Flask. I want to be able to remove rows w/o refreshing the page, so I got some help constructing an AJAX call to do just that. This is the portion meant to handle that action:

$("#button").clicked(function() {
var rowsToRemove = [];
$(".checkitem:checked").each(function() {
  var rowIndex = $(this).parent("tr").index(this);
  rowsToRemove.push(rowIndex+1);
});

delete_ajax = $.ajax({
        type : 'POST',
        method: 'POST',
        url : "/home",
        data : JSON.stringify({rowsToRemove:rowsToRemove, typeofpost: 'delete'}),
        dataType: "json",
        contentType: "application/json"
});

delete_ajax.done(function(responseObject, textStatus, jqXHR) {
    if(responseObject.status == 200) {
      reloadTable();
    }
});

delete_ajax.error(function() {
  alert("Unable to delete row(s). Please try again.");
});

});

And here is the portion that I was assisted with from the Flask side that would distinguish between delete calls and posted data:

if request.json.get('type') == 'add':
        if not request.form.get("password"):
            return apology("'Password' field required. Please enter a symbol.", 403)
        if not request.form.get("website"):
            return apology("'Website' field required. Please enter a share.", 403)

        password=request.form.get("password")

        db.execute("INSERT INTO passwords (user_id, password, cipher, website) VALUES (:userID, :password, :cipher, :website)",
                    userID=session["user_id"],
                    password=password,
                    cipher=encrypt(password),
                    website=request.form.get("website"))

        length = db.execute("SELECT COUNT(password) FROM passwords WHERE user_id = :userID", userID=session["user_id"])#.fetchone()[0]

        db.execute("UPDATE passwords SET row_id = :rowID WHERE user_id = :userID AND password = :pw",
                    rowID=length[0]["COUNT(password)"],
                    userID=session["user_id"],
                    pw=password)

        #return redirect("/home")
        return {"status":200}

    # from delete
    if request.json.get('type') == 'delete':
        length = db.execute("SELECT COUNT(password) FROM passwords WHERE user_id=:userID", userID=session["user_id"]).fetchone()[0]

        index = list(range(1, length+1))

        data_to_delete = request.json.get("data")

        rowsToRemove = db.execute("DELETE FROM passwords WHERE row_id IN :data AND user_id:=userID", data=data_to_delete, userID=session["user_id"])

        db.execute("UPDATE passwords SET row_id=:rowID WHERE user_id=:userID", rowID=index, userID=session["user_id"])

        return {"status":200}

Just in case I need to fix something I overlooked on the HTML side, I'll that as well:

<div class="form-group container">
    <table class="table table-hover thead-dark">
        <thead>
            <th><div class="checkbox">
                    <label><input type="checkbox" class="checkbox" id="checkall" name="checkall"> Select/Deselect All</label>
                </div></th>
            <th>Row</th>
            <th>Password</th>
            <th>Cipher</th>
            <th>Website</th>
        </thead>
        <tbody>
            
        </tbody>
    </table>
    <div class="form-group form-inline container center row">
        <form  action="/home" method="/post">
            <input class="form-control" autocomplete="off" name="password" placeholder="Password" type="text" required>
            <input autocomplete="off" class="form-control" name="website" placeholder="Website" type="text" required>
            <input class="btn btn-primary" type="submit" id="encrypt" value="Encrypt">
        </form>
        <button type="button" class="btn btn-outline-danger" style="margin: auto" id="button">Remove</button>
    </div>

I have a habit of overlooking things, so if there's something I'm missing, please let me know a.s.a.p.




Heroku crashes while it works on my local server

I'm trying to run a little HTTPS server with Heroku, but it's just giving me this error: at=error code=H13 desc="Connection closed without response" method=GET path="/" host=###.herokuapp.com request_id=### fwd="###" dyno=web.1 connect=0ms service=6ms status=503 bytes=0 protocol=https

My server looks like this:

let https = require("https");
let port = process.env.PORT;
if (port == null || port == "") {
    console.log("Using port 80");
    port = 8000;
} else {
    console.log("Using port supplied by Heroku");
    port = Number(port);
}

console.log(`Listening on port ${port}`);
const options = {
    key: [my key],
    cert: [my cert]
};
 
https.createServer(options, (request, response) => {
    console.log("Request recieved")
    response.writeHead(200);
    response.write("<!DOCTYPE html><head></head><body>hello world</body>")
    response.end();
}).listen(port);

I dont have any problems running it locally with heroku local web. Why does this happen and how can I fix this?

EDIT: Turns out that you have to pay Heroku 25 bucks a month to get HTTPS. See this answer.




Uncaught TypeError: postData.likes is undefined in express

Hello everyone im experiencing a type error when trying to console.log the amount of likes on a post . I get postData.likes is undefined in the web dev console. Ive checked my code maybe 100 times by now and cant find a error. I checked my models and I made sure thing were properly populated and cant figure out what the issue is. Im trying to a PUT request in jquery. When I like a post in the Users mongo db document the likes array is coming up exactly as it should. Then it should also be doing the same thing in the post document but it is not. The users collection is called users and the posts collection is called posts. Im thinking the issue has to do with me using .populate I just cant figure out the problem so im hoping someone here can help.

commen.js file

$("#postTextarea").keyup((event) => {
  const textbox = $(event.target);
  const value = textbox.val().trim();

  const submitButton = $("#submitPostButton");

  if (submitButton.length == 0) return alert("No submit button found");

  if (value == "") {
    submitButton.prop("disabled", true);
    return;
  }

  submitButton.prop("disabled", false);
});

$("#submitPostButton").click(() => {
  const button = $(event.target);
  const textbox = $("#postTextarea");

  const data = {
    content: textbox.val(),
  };

  $.post("/api/posts", data, (postData) => {
    const html = createPostHtml(postData);
    $(".postsContainer").prepend(html);
    textbox.val("");
    button.prop("disabled", true);
  });
});

$(document).on("click", ".likeButton", (event) => {
  const button = $(event.target);
  const postId = getPostIdFromElement(button);

  if (postId === undefined) return;

  $.ajax({
    url: `/api/posts/${postId}/like`,
    type: "PUT",
    success: (postData) => {
      console.log(postData.likes.length);
    },
  });
});

function getPostIdFromElement(element) {
  const isRoot = element.hasClass("post");
  const rootElement = isRoot == true ? element : element.closest(".post");
  const postId = rootElement.data().id;

  if (postId === undefined) return alert("Post id undefined");

  return postId;
}

function createPostHtml(postData) {
  const postedBy = postData.postedBy;

  if (postedBy._id === undefined) {
    return console.log("User object not populated");
  }

  const displayName = postedBy.firstName + " " + postedBy.lastName;
  const timestamp = timeDifference(new Date(), new Date(postData.createdAt));

  return `<div class='post' data-id='${postData._id}'>

              <div class='mainContentContainer'>
                  <div class='userImageContainer'>
                      <img src='${postedBy.profilePic}'>
                  </div>
                  <div class='postContentContainer'>
                      <div class='header'>
                          <a href='/profile/${postedBy.username}' class='displayName'>${displayName}</a>
                          <span class='username'>@${postedBy.username}</span>
                          <span class='date'>${timestamp}</span>
                      </div>
                      <div class='postBody'>
                          <span>${postData.content}</span>
                      </div>
                      <div class='postFooter'>
                          <div class='postButtonContainer'>
                              <button>
                                  <i class='far fa-comment'></i>
                              </button>
                          </div>
                          <div class='postButtonContainer'>
                              <button>
                                  <i class='fas fa-retweet'></i>
                              </button>
                          </div>
                          <div class='postButtonContainer'>
                              <button class='likeButton'>
                                  <i class='far fa-heart'></i>
                              </button>
                          </div>
                      </div>
                  </div>
              </div>
          </div>`;
}

function timeDifference(current, previous) {
  var msPerMinute = 60 * 1000;
  var msPerHour = msPerMinute * 60;
  var msPerDay = msPerHour * 24;
  var msPerMonth = msPerDay * 30;
  var msPerYear = msPerDay * 365;

  var elapsed = current - previous;

  if (elapsed < msPerMinute) {
    if (elapsed / 1000 < 30) return "Just now";

    return Math.round(elapsed / 1000) + " seconds ago";
  } else if (elapsed < msPerHour) {
    return Math.round(elapsed / msPerMinute) + " minutes ago";
  } else if (elapsed < msPerDay) {
    return Math.round(elapsed / msPerHour) + " hours ago";
  } else if (elapsed < msPerMonth) {
    return Math.round(elapsed / msPerDay) + " days ago";
  } else if (elapsed < msPerYear) {
    return Math.round(elapsed / msPerMonth) + " months ago";
  } else {
    return Math.round(elapsed / msPerYear) + " years ago";
  }
}

Models/Posts.js

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const PostSchema = new Schema(
  {
    content: {
      type: String,
      trim: true,
    },
    postedBy: {
      type: Schema.Types.ObjectId,
      ref: "users",
      pinned: Boolean,
      likes: [{ type: Schema.Types.ObjectId, ref: "users" }],
    },
  },
  { timestamps: true }
);

const Post = mongoose.model("posts", PostSchema);
module.exports = Post;

models/User.js

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const UserSchema = new Schema(
  {
    firstName: {
      type: String,
      required: true,
      trim: true,
    },
    lastName: {
      type: String,
      required: true,
      trim: true,
    },
    username: {
      type: String,
      required: true,
      trim: true,
      unique: true,
    },
    email: {
      type: String,
      required: true,
      trim: true,
      unique: true,
    },

    password: {
      type: String,
      required: true,
    },

    profilePic: {
      type: String,
      default: "/images/default.jpeg",
    },
    likes: [{ type: Schema.Types.ObjectId, ref: "posts" }],
  },
  { timestamps: true }
);

const User = mongoose.model("users", UserSchema);
module.exports = User;

postController.js

const express = require("express");
const User = require("../../models/User");
const Post = require("../../models/Posts");

exports.handlePostRequest = async (req, res, next) => {
  if (!req.body.content) {
    console.log("content param not sent");
    return res.sendStatus(400);
  }

  const postData = {
    content: req.body.content,
    postedBy: req.session.user,
  };

  Post.create(postData)
    .then(async (newPost) => {
      newPost = await User.populate(newPost, { path: "postedBy" });

      res.status(201).send(newPost);
    })
    .catch((error) => {
      console.log(error);
      res.sendStatus(400);
    });
};

exports.handleGetRequest = async (req, res, next) => {
  await Post.find()
    .populate("postedBy")
    .sort({ createdAt: -1 }) //Shows posts by newest first
    .then((results) => {
      res.status(200).send(results);
    })
    .catch((error) => {
      console.log(error);
      res.sendStatus(400);
    });
};

exports.handlePutRequest = async (req, res, next) => {
  const postId = req.params.id;
  const userId = req.session.user._id;

  const isLiked =
    req.session.user.likes && req.session.user.likes.includes(postId);

  const option = isLiked ? "$pull" : "$addToSet";

  // Insert user like
  req.session.user = await User.findByIdAndUpdate(
    userId,
    { [option]: { likes: postId } },
    { new: true }
  ).catch((error) => {
    console.log(error);
    res.sendStatus(400);
  });

  // Insert post like
  const post = await Post.findByIdAndUpdate(
    postId,
    { [option]: { likes: userId } },
    { new: true }
  ).catch((error) => {
    console.log(error);
    res.sendStatus(400);
  });

  res.status(200).send(post);
};




unexpected token < in javascript to publish a new windows in my web

<a href="https://ift.tt/3nc8K4V" target="_blank">Chipsypc

<a href="https://ift.tt/3nc8K4V" target="_blank">Chipsypc <a href="https://ift.tt/3nc8K4V" target="_blank">Chipsypc




How to get a words from a website in lua?

So I have this code but I want to get the word from the website

I want to use this to protect my project from leakers.

This is what I have

str = 'word'
if string.find(str, "word") then
end

So I want to get the word from a website.txt

So if I want to remove access I edit the file

I was thinking about

str = 'website'
if string.find(str, "word") then
end
But I don't think this will work...



disable default Scroll to top in web application

I'm new to React and Web. I am trying to load some chats data, whenever I add some chats to the top of the chat list, automatically chats container scrolled to the top of chats, I mean first chat in term of creating time. how to disable this scrolling behavior? I also tried a library called reverse-infinite-search.




How to disable browser CPU throttling on SetTimeout?

When the browser is minimized or the tab is on the background they set setTimeout to a minimum of 1 second example code:

const wait = ms => new Promise(r => setTimeout(r, ms))

async function doStuff() {
    let p0 = performance.now();
    await wait(100);
    let p1 = performance.now();
    console.log('time',(p1-p0));
    await doStuff();
}

When the tab or the browser is on focus the console.log prints 100, when it's minimized 1000 how I can disable/bypass it?




List gets longer depending on message input - React

I have a chatApp that i am currently working on. It is mostly complete but it has one last bug where when you type a long message then the <li> elements duplicates even more. The longer the message, the more clones of the <li> element. APP.JS:

import React from 'react'
import './App.css';
import firebase from 'firebase'

const firebaseConfig = {
  apiKey: "AIzaSyBTwRj0vzQn4v-IRvRQ7UQSPMnBNT0Gi0A",
  authDomain: "whatapp-02.firebaseapp.com",
  databaseURL: "https://whatapp-02-default-rtdb.firebaseio.com",
  projectId: "whatapp-02",
  storageBucket: "whatapp-02.appspot.com",
  messagingSenderId: "1085780260212",
  appId: "1:1085780260212:web:540d871a14bb7536b4e821"
};

firebase.initializeApp(firebaseConfig)

class App extends React.Component {
  
  constructor(props){
    super(props);
    this.state = {
      name: ' ',
      partner: ' ',
      key: ' ',
      partnerkey: ' ',
      allkey: ' ',
      message: ' ',
      prevmessage: ' ',
      chatpartner: ' ',
    };
  }

  login=()=>{
    var key = Math.random().toString().substring(2, 8);
    this.setState({key: key,});
    firebase.database().ref('USER-'+key).set({
      key: key,
      partner: ' ',
    });
    document.getElementsByClassName("logindiv")[0].style.display = "none";
    document.getElementsByClassName("chatdiv")[0].style.display = "block";
    setInterval(this.update_partner, 1000)
  }

  get_user=()=>{
    var input = this.state.partnerkey;
    var parsedallkey = parseInt(this.state.key,10) + parseInt(this.state.partner,10);
    firebase.database().ref('USER-'+this.state.key).set({
     partner: input,
    });
    firebase.database().ref('USER-'+input).set({
      partner: this.state.key,
    });
    this.setState({allkey: parsedallkey})
  }
   
  update_partner=()=>{
  var parsedallkey = parseInt(this.state.key,10) + parseInt(this.state.partner,10);
  firebase.database().ref('USER-'+this.state.key).once('value', (snapshot)=>{
    var partner = snapshot.val().partner
    this.setState({partner: partner})
  })
  this.setState({allkey: parsedallkey})
  setInterval(this.identify_message, 2000) 
  }

  send_message=()=>{
    firebase.database().ref('MESSAGE'+this.state.allkey).push().set({ //Save user name and message in reference "messages" in firebase database
        sender: this.state.key,
        message: this.state.message
    });
  }

  identify_message=()=>{
    firebase.database().ref('MESSAGE'+this.state.allkey).limitToLast(1).on("child_added", (snapshot)=>{
      if(snapshot.val().sender + ": " + snapshot.val().message === this.state.prevmessage){}else{
      if(snapshot.val().sender === this.state.key){
        var li = document.createElement("li")
        li.innerHTML = snapshot.val().sender + ": " + snapshot.val().message + ' , you said'; 
        console.log(snapshot.val().sender + ": " + snapshot.val().message + ' , you said')
        console.log(this.state.allkey)
        this.setState({prevmessage: snapshot.val().sender + ": " + snapshot.val().message})
        document.getElementById("printmessage").appendChild(li)
      }else if(snapshot.val().sender === this.state.partner){
          var li = document.createElement("li")
          li.innerHTML = snapshot.val().sender + ": " + snapshot.val().message + ' , he said';
          document.getElementById("printmessage").appendChild(li)
          console.log(snapshot.val().sender + ": " + snapshot.val().message + ' , he said')
          this.setState({prevmessage: snapshot.val().sender + ": " + snapshot.val().message})
      }
    }
   });
  }

  render(){
    return (<>
     <div className='logindiv'>
     <h1 style=>chatApp</h1>
       <a href="#" role="button" onClick={this.login} style=>Guest login</a>
     <div style=>
       <h2 style=>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec dapibus sapien, quis sagittis quam. Pellentesque lacus mi, bibendum ac augue non, placerat tempus justo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Morbi laoreet tellus consequat pulvinar pulvinar. Cras neque ante, varius vel feugiat nec, cursus nec sapien. Sed <br></br>viverra ullamcorper accumsan. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nunc vitae pellentesque lectus. Vivamus eget urna at tellus porta sodales at quis urna. <br></br>Aliquam non enim non ipsum viverra gravida a convallis metus. Aenean dapibus accumsan nunc, non vestibulum nulla semper ut. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Curabitur commodo posuere ligula id varius. Morbi rutrum eu arcu sit amet viverra. Vestibulum hendrerit sodales eros eget imperdiet.</h2>
     </div>
     </div>

     <div className='chatdiv'>
<div>
  {/* Navbar */}
  <nav className="navbar navbar-expand-lg navbar-light bg-light">
    {/* Container wrapper */}
    <div className="container-fluid">
      {/* Navbar brand */}
      <h4 className="navbar-brand" >Your key: {this.state.key}</h4>
      {/* Toggle button */}
      {/* Collapsible wrapper */}
      <div className id>
        {/* Search form */}
        <form className="d-flex input-group w-auto ml-auto">
          <input type="search" className="form-control align-self-center" placeholder=" Enter a user code..." aria-label="Search" onChange={(e)=>{this.setState({partnerkey: e.target.value})}}/>
          <button className="btn btn-outline-primary" type="button" data-mdb-ripple-color="dark" onClick={this.get_user}>
            Search ({this.state.partnerkey})
          </button>
        </form>
      </div>
      {/* Collapsible wrapper */}
    </div>
    {/* Container wrapper */}
  </nav>
  {/* Navbar */}
  <div className="copntainer-fluid">
    <div className>
      <div className="form-group">
        <label htmlFor="exampleFormControlTextarea3" />
        <ul id="printmessage"></ul>
      </div>
    </div>
    <form className="d-flex input-group w-auto ml-auto">
      <input type="text" className="form-control align-self-center" placeholder=" Enter your message..." aria-label="Search" onChange={(e)=>{this.setState({message: e.target.value})}} />
      <button className="btn btn-outline-primary" type="button" onClick={this.send_message} data-mdb-ripple-color="dark">
        Send
      </button>
    </form>
  </div>
</div>


     </div>
  </>);
  }
}

export default App;

PUBLIC/INDEX.HTML: (it only has CDN links)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta name="description" content="Web site created using create-react-app"/>
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Bootstrap tooltips -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.4/umd/popper.min.js"></script>
<!-- Bootstrap core JavaScript -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.min.js"></script>
<!-- MDB core JavaScript -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.19.1/js/mdb.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
<!-- Google Fonts -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap">
<!-- Bootstrap core CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet">
<!-- Material Design Bootstrap -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.19.1/css/mdb.min.css" rel="stylesheet">
<title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

PACKAGE.JSON: (the problem is not here, i believe)

{
  "name": "myapp",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "firebase": "^8.2.1",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scripts": "4.0.1",
    "web-vitals": "^0.2.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

I will be very grateful for your help.




Gap between first element and top of page

I have the following code:

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="index.css">
    <title>Navbar Animations</title>
</head>
<body>
    <nav>
        <p>This is a test</p>
    </nav>
</body>
</html>

and css like this:

body {
    height: 100vh;
    margin: 0px;
    margin-top: 0px;
    flex-direction: column;
    background-color: rgb(41, 11, 22);
}

nav {
    color: white;
    background-color: rgb(214, 50, 50);
    height: 10vh;
}

But the end result is like this:

website

Question is: how would I get rid of that gap at the top?




Prevent scrolling with touch input on mobile website

I'm creating a website that simulates an os (graphically speaking) for my graphic design portfolio - http://dreamstate.graphics/. This means that I need several of my elements to be draggable. Everything is working fine on desktop and the project is pretty much finished, however on mobile the user can't drag elements without the entire website scrolling. Tapping on elements works fine as a click event, so the website isn't unusable, but I'd like to be able to drag with touch. I know this has been asked many times before, however none of the solutions are working for me and I'm completely lost.

In CSS I've hidden the overflows and made the positions fixed on my container element and the body:

body, html { position: fixed; height: 100%; width: 100%; top: 0; left: 0; right:0; bottom: 0; overflow: hidden}

In Javascript I've prevented the default function of touchmove:

document.addEventListener("touchmove", function(e){e.preventDefault()}, { passive: false });

But, if I change the called function on the event listener to alert("it works"), I'm not being alerted so I don't think it's detecting moving touch events anyway. I do have video overlays, but they are set to "touch-action: none;". What am I doing wrong here and how can I prevent scrolling from interfering with touch functionality?




How can I create a website for livestream video to YouTube and Facebook

Can someone tell me how can I develop a website to livestream from my website to YouTube and Facebook.

How can I achieve that please give me an rough idea.




Cannot add component in React

I am trying to add footer.js in my react App.js

This is my app.js.

import React, { Component } from "react";
import "./App.css";

import Navbar from "./Navbar";
class App extends Component {
  render() {
    return (
      <div className="App">
        <BrowserRouter>
          <div>
            <Navbar />    
            <Switch>
              <Route path="/" exact component={Home} />
              <Route path="/SignIn" component={SignIn} />
            </Switch>
            <navfooter />
          </div>
        </BrowserRouter>
      </div>
    );
  }
}

export default App;

In my App.js file, I have used NavBar and it is working fine. I am using the same concept to add footer.js file in App.js file. I could also try using a pre-built footer file, but I wanted my own footer file. this is my footer.js

import React from "react";

const navfooter = (props) => {
  return (
    <div>
      <p>footer</p>
    </div>        
  );
};

export default navfooter;

And it shows like this:

enter image description here

My code editor, VS Code is not showing any errors or warnings. But the console shows an error:

enter image description here

SO what am I doing wrong?




Precompile Material Design For Web

I am going to be using Material Design For Web in a PHP application with a custom theme. I am looking for instructions on how to precompile the JS and CSS with my custom theme variables so that I can just pull in the js and css like you would if using the CDN. It appears the CDN does offer some custom themed color options, but none look like what I am looking for which is why I am looking to create my own precompiled css and js files

What are the steps to precompile with the custom theme variables so that I can just have a dist css and js file?




How to move HTML elements when a page is scrolled?

How to make an HTML element that is initially 'fixed' then when we scroll the web page down or more specifically through the element, the element will move to the side or wherever we specify. And of course when we scroll the web page back up and pass the element, it will return to normal.

Please help if there is, I ask for an article or explanation of what to use and an example of the source code.

Check this image for more details.




TypeError: Cannot read property 'appendChild' of null in ReactJS

I am creating a chatApp in ReactJS but I am experiencing this error:

TypeError: Cannot read property 'appendChild' of null

I have called "printmessage" but still it is still returning null. (on line 144) APP.JS:

import React from 'react'
import './App.css';
import firebase from 'firebase'

const firebaseConfig = {
  apiKey: "AIzaSyBTwRj0vzQn4v-IRvRQ7UQSPMnBNT0Gi0A",
  authDomain: "whatapp-02.firebaseapp.com",
  databaseURL: "https://whatapp-02-default-rtdb.firebaseio.com",
  projectId: "whatapp-02",
  storageBucket: "whatapp-02.appspot.com",
  messagingSenderId: "1085780260212",
  appId: "1:1085780260212:web:540d871a14bb7536b4e821"
};

firebase.initializeApp(firebaseConfig)

class App extends React.Component {
  
  constructor(props){
    super(props);
    this.state = {
      name: ' ',
      partner: ' ',
      key: ' ',
      allkey: ' ',
      message: ' ',
      prevmessage: ' ',
      username: ' ',
      partnermessage: ' ',
      chatpartner: ' ',
    };
  }

  login=()=>{
    var key = Math.random().toString().substring(2, 8);
    this.setState({key: key,});
    firebase.database().ref('USER-'+key).set({
      key: key,
      partner: ' ',
    });
    document.getElementsByClassName("logindiv")[0].style.display = "none";
    document.getElementsByClassName("chatdiv")[0].style.display = "block";
    setInterval(this.update_partner, 1000)
  }

  get_user=()=>{
    var parsedallkey = parseInt(this.state.key,10) + parseInt(this.state.partner,10);
    var input = prompt("enter user code:")
    firebase.database().ref('USER-'+this.state.key).set({
     partner: input,
    });
    firebase.database().ref('USER-'+input).set({
      partner: this.state.key,
    });
    this.setState({allkey: parsedallkey})
  }
   
  update_partner=()=>{
  var parsedallkey = parseInt(this.state.key,10) + parseInt(this.state.partner,10);
  firebase.database().ref('USER-'+this.state.key).once('value', (snapshot)=>{
    var partner = snapshot.val().partner
    this.setState({partner: partner})
  })
  this.setState({allkey: parsedallkey})
  setInterval(this.identify_message, 2000) 
  }

  handle_message=(e)=>{
   this.setState({message: e.target.value});
   console.log(this.state.message)
  }

  send_message=()=>{
    firebase.database().ref('MESSAGE'+this.state.allkey).push().set({ //Save user name and message in reference "messages" in firebase database
        sender: this.state.key,
        message: this.state.message
    });
  }

  render(){
    return (<>
     <div className='logindiv'>
     <h1 style=>chatApp</h1>
       <a href="#" role="button" onClick={this.login} style=>Guest login</a>
     <div style=>
       <h2 style=>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec dapibus sapien, quis sagittis quam. Pellentesque lacus mi, bibendum ac augue non, placerat tempus justo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Morbi laoreet tellus consequat pulvinar pulvinar. Cras neque ante, varius vel feugiat nec, cursus nec sapien. Sed <br></br>viverra ullamcorper accumsan. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nunc vitae pellentesque lectus. Vivamus eget urna at tellus porta sodales at quis urna. <br></br>Aliquam non enim non ipsum viverra gravida a convallis metus. Aenean dapibus accumsan nunc, non vestibulum nulla semper ut. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Curabitur commodo posuere ligula id varius. Morbi rutrum eu arcu sit amet viverra. Vestibulum hendrerit sodales eros eget imperdiet.</h2>
     </div>
     </div>

     <div className='chatdiv'>
<div>
  {/* Navbar */}
  <nav className="navbar navbar-expand-lg navbar-light bg-light">
    {/* Container wrapper */}
    <div className="container-fluid">
      {/* Navbar brand */}
      <h4 className="navbar-brand" >Your key: {this.state.key}</h4>
      {/* Toggle button */}
      {/* Collapsible wrapper */}
      <div className id>
        {/* Search form */}
        <form className="d-flex input-group w-auto ml-auto">
          <input type="search" className="form-control align-self-center" placeholder=" Enter a user code..." aria-label="Search" />
          <button className="btn btn-outline-primary" type="button" data-mdb-ripple-color="dark" onClick={this.get_user}>
            Search
          </button>
        </form>
      </div>
      {/* Collapsible wrapper */}
    </div>
    {/* Container wrapper */}
  </nav>
  {/* Navbar */}
  <div className="copntainer-fluid">
    <div className>
      <div className="form-group">
        <label htmlFor="exampleFormControlTextarea3" />
        <ul id="printmessage"></ul>
      </div>
    </div>
    <form className="d-flex input-group w-auto ml-auto">
      <input type="search" className="form-control align-self-center" placeholder=" Enter your message..." aria-label="Search" />
      <button className="btn btn-outline-primary" type="button" onClick={this.send_message} data-mdb-ripple-color="dark">
        Send
      </button>
    </form>
  </div>
</div>


     </div>
  </>);
  }

  identify_message=()=>{
    firebase.database().ref('MESSAGE'+this.state.allkey).limitToLast(1).on("child_added", (snapshot)=>{
      if(snapshot.val().sender + ": " + snapshot.val().message + ' , you said' === this.state.prevmessage || this.state.partnermessage === snapshot.val().sender + ": " + snapshot.val().message + ' , he said'){}else{
      if(snapshot.val().sender === this.state.key){
        var li = document.createElement("li")
        li.innerHTML = snapshot.val().sender + ": " + snapshot.val().message + ' , you said'; 
        console.log(snapshot.val().sender + ": " + snapshot.val().message + ' , you said')
        console.log(this.state.allkey)
        this.setState({prevmessage: snapshot.val().sender + ": " + snapshot.val().message + ' , you said'})
        document.getElementById("printmessages").appendChild(li)
      }else if(snapshot.val().sender === this.state.partner){
          var li = document.createElement("li")
          li.innerHTML = snapshot.val().sender + ": " + snapshot.val().message + ' , he said';
          document.getElementById("printmessages").appendChild(li)
          console.log(snapshot.val().sender + ": " + snapshot.val().message + ' , he said')
          this.setState({partnermessage: snapshot.val().sender + ": " + snapshot.val().message + ' , he said'})
      }
    }
   });
  }


}

export default App;

I am using React-CLI. I have also integrated bootstrap using CDN in public/index.html. I have been scrathing my head on this for 2 days so I will be very grateful for your help.




What's the correct way to write HTML? [closed]

Sometimes, we need to wrap an element in only one or two divs to get it in the correct form and position. My question is: why in famous websites, if you inspect elements with your browser, you can see one element inside a big number of nested divs? Wrap an element inside more of two divs results to be a more efficient way to build a web page?




cant use information array of json file [duplicate]

i've problem, idk why but i can't use my json file for my website...

if i try call the json, it's good but i can't use information... if you have solution, tell me pls T-T

i've test all but nothing work...

entity = fetch("./entity/entity.json")
  .then(response =>{return response.json()})

console.log(entity) /*output: 
                    Promise {<pending>}
                    __proto__: Promise
                    [[PromiseState]]: "fulfilled"
                    [[PromiseResult]]: Array(3)
                        0: {id: "1", title: "inventory 1", description: "l'objet 1 de l'inventaire", price: 50, img: false}
                        1: {id: "2", title: "inventory 2", description: "l'objet 2 de l'inventaire", price: 25, img: false}
                        2: {id: "3", title: "inventory 3", description: "l'objet 3 de l'inventaire", price: 15, img: false}
length: 3
__proto__: Array(0)*/ 


console.log(entity[0]) //output : undefined

tks.




mercredi 30 décembre 2020

execute javascript pixel from separate file

I have the following sudo javascript code I wish to call when a user visits a page of my website (adapted from https://cloud.google.com/recommendations-ai/docs/record-events#monitor):

<script type="text/javascript">
var user_event = {
  "eventType" : "detail-page-view",
};

var _gre = _gre || [];
_gre.push(['apiKey', '<MY API KEY>']);
_gre.push(['logEvent', user_event]);

(function() {
  var gre = document.createElement('script'); gre.type = 'text/javascript'; gre.async = true;
  gre.src = 'https://www.gstatic.com/recommendationengine/v1beta_event.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gre, s);
})();

</script>

The script runs successfully, however, I want to organize my javascript into a separate file.

I have created assets/custom.js and loaded the functions successfully. I then call the function like this from the same page:

<script type="text/javascript">
  detailPageView();
</script>

and in assets/custom.js I have:

function detailPageView(){
  // exact same code as above!
  var user_event = {
  "eventType" : "detail-page-view",
};

var _gre = _gre || [];
_gre.push(['apiKey', '<MY API KEY>']);
_gre.push(['logEvent', user_event]);

(function() {
  var gre = document.createElement('script'); gre.type = 'text/javascript'; gre.async = true;
  gre.src = 'https://www.gstatic.com/recommendationengine/v1beta_event.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gre, s);
})();
}

I code runs, however, the script does not successfully log the event. How can I fix this?




SSL: WRONG_VERSION_NUMBER ON PYTHON REQUEST

Python version: 3.9.1

Hello big brains!!

I trying to write bot that send requests and it work perfectly fine, the only issue that i have is when i trying to use web debugging programs such as Charles 4.6.1 or Fiddler Everywhere. When i open it to see bot traffic and response form server it crash showing me this error:

(Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1124)')))

i used to have this issue by i was available to fix it by simply adding "verify=False" to my request post but right now it does not work and i try a lot of things to fix it but nothing help and i have no idea whats wrong.




Displaying user uploaded image in Python Django

I am creating a website using the Django python framework and am currently stuck on a problem. I am using function views to display a page called myaccount, and on 'myaccount' i would like all user details to be displayed using context objects, for this page it is 'user'. I also have another model called Profile, which holds the profile picture and date of birth of the user. However when i attempt to display the image which has been uploaded during the account creation into the media folder named '/media/%y/%m/%d/imagename.filextension' i receive an error saying "The 'profilepicture' attribute has no file associated with it." I have been searching vastly for fixes to this issue and have so far found no result which has worked, i have tried to create a property function which gets the url from the image called 'get_absolute_url' by doing user.profile.profilepicture.get_absolute_url but it fails to work and displays the same error. I was wondering if anyone could point me in the direction of a fix for this or a solution.

The code to display the image, views.py and urls.py is down below

views.py

@login_required
def myaccount(request):
    return render(request, 'account/myaccount.html', {'section': 'myaccount'})

urls.py

path('', views.myaccount, name='myaccount'),

myaccount.html

<img src="" width="260" height="234"/>

Profile model

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    date_of_birth = models.DateField(blank =True, null =True)
    profilepicture = models.ImageField(upload_to='users/%Y/%m/%d', blank=True)
    def __str__(self):
        return f'Profile for user {self.user.username}'

The model for User is from 'django.contrib.auth.models'

To confirm whether it was a problem with the context object I tried to display the users first name which worked as expected.

The account register view

def register(request):
    if request.method == 'POST':
        user_form = UserRegistrationForm(request.POST)
        if user_form.is_valid():
            # Create a new user object but avoid saving it yet
            new_user = user_form.save(commit=False)
            # Set the chosen password
            new_user.set_password(
                user_form.cleaned_data['password'])
            # Save the User object
            new_user.save()
            Profile.objects.create(user=new_user)
            # Create the user profile
            return render(request,
                          'account/register_done.html',
                          {'new_user': new_user})
    else:
        user_form = UserRegistrationForm()
    return render(request,
                  'account/register.html',
                  {'user_form': user_form})

If any other code or information is needed please ask.




trying to make tiled map load in JS using phaser and wont work?

i am trying to use Phaser3 to create a web based game for my course and I am using tiled to create the maps. I have saved the tiled map as a .json file and I cant load the level I designed. The code i am using is from a tutorial as seen below. The problem is it is only showing a black screen when loading and the tilemapTiledJSON function is coming up as an unresolved function instead of working how it should. i am Webstorm for the coding and i am using phaser 3.50.0.

const config = {
    type: Phaser.AUTO, // Which renderer to use
    width: 800, // Canvas width in pixels
    height: 600, // Canvas height in pixels
    parent: "game-container", // ID of the DOM element to add the canvas to
    scene: {
        preload: preload,
        create: create,
        update: update
    }
};

const game = new Phaser.Game(config);

function preload() {
    this.load.image("tiles", "../Assets/Tileset/GB_TileSet_Cemetery_16x16_Sheet.png");
    this.load.tilemapTiledJSON("map", "../Assets/Level/Cemeterymap.json");
}

function create() {
    const map = this.make.tilemap({ key: "map" });

    // Parameters are the name you gave the tileset in Tiled and then the key of the tileset image in
    // Phaser's cache (i.e. the name you used in preload)
    const tileset = map.addTilesetImage("cemetery 5", "tiles");

    // Parameters: layer name (or index) from Tiled, tileset, x, y
    const belowLayer = map.createStaticLayer("Base", tileset, 0, 0);
    const worldLayer = map.createStaticLayer("Base objects", tileset, 0, 0);
    const aboveLayer = map.createStaticLayer("Non Collision objects", tileset, 0, 0);
}

function update(time, delta) {
    // Runs once per frame for the duration of the scene
}

enter image description here




Django: Filter ListView on currently logged-in user (manytomanyfield)

I'm working on a django project, and as I'm quite new to this framework and backend in general, I'm having a hard time finding out how to do this.

I'm building a ListView that is used to display a list of products in a template. However, I need it to only display the products made available on the site by the dealer who's currently logged in. So in other words, just a page where a dealer can see what products they've put on our site.

Here's my view:

class ArticleListView(ListView, LoginRequiredMixin):
    template_name = "accounts/list_articles.html"
    model = Product
    
    def get_context_data(self,**kwargs):
        context = super().get_context_data(**kwargs)
        context["website"] = Website.objects.first()
        context["product_list"] = context["product_list"].filter(published=True)
        return context
    

Here's the Products and Dealers models (only the relevant parts):

class Product(models.Model, CloneMixin):
    published = models.BooleanField(null=True,blank=True, default=False)
    title = models.CharField(null=True,blank=True,max_length=100)
    subtitle = models.CharField(null=True,blank=True,max_length=200)
    (...)
    dealer = models.ManyToManyField(Dealer, null=True,editable=True,related_name="product_to_dealer")
    (...)
    # Not sure what this does:
   _clone_many_to_many_fields = ['parameter', 'tag', 'category', 'dealer','images']
    (...)

    
class Dealer(models.Model, CloneMixin):
    dealer_check = models.ForeignKey("self",null=True, blank=True, on_delete=models.SET_NULL)
    published = models.BooleanField(null=True,blank=True, default=True)
    (...)
    users = models.ManyToManyField(User,null=True,blank=True, related_name='dealers')
    (...)

As it is, my ListView just displays every products there is in the db. From what I've understood, I need something like

def get_queryset(self):
        return Product.objects.filter(user=self.request.user)

or in the get_context_data, it would do the same I guess:

context["product_list"] = context["product_list”].filter(user=self.request.user)

But in this case, the user related to the product is in the Dealer model (ManyToManyField in the Product model). I want to ask django "Show me only the products for which the current logged-in user is in the "users" of the dealer related to this product."

I don't think that's too complicated by I need some pointers on this. Thanks for your help.




Using Multiple Technologies on One Website is With Different Urls

What I want to do is to be able to switch to different projects on a simple server I rented (standard windows hosting) without subdomains. For example :

website.com/javapproject, website.com/c#.net project, ...... etc can also be on a forum site

What kind of work do I need to follow to establish a structure like this. I've searched this place a little bit, but I can't find a fully satisfactory answer. How is something like this possible?. You can talk about possible solutions. (docker ... etc) I would be glad if you explain. Thank you.




Speeding up the Line bar in react

I made a covid-tracker app but it is too slow. How can I make it faster and more efficient. The line Bar loads more slow than others. https://github.com/Mahmedabid/covid-tracker ahm-covidTracker.surge.sh




Show robots.txt file at domain.com/robots.txt instead of domain.com/context/robots.txt in Spring Java web app

I'm trying to add a robots.txt file to my Spring Java web application, but when I put the file in the webapp folder, the text is only visible through localhost:8000/context/robots.txt instead of localhost:8000/robots.txt (the url that google crawler would check), where I receive a 404 error. I've tried putting the robots.txt file at src, WEB-INF, the project's root folder, etc. with the same results.

I've also tried changing my application-context.xml redirecting "/robots.txt" to my file with <mvc:resources mapping="/robots.txt" location="/robots.txt" order="0"/> for all the previous locations and still doesn't work. The index page of my app would be domain.com/context/firstpage.ac so every page is accessible under that context and as I said also the robots.txt file is showed there when I put it on the webapp folder.

Is there any way to separate my robots file from the others and put it at localhost:8000/robots.txt or it isn't possible since my app is deployed under that specific context? It's my first time with a java web app front and I'm completely unfamiliar with all of this, I've tried all the possible solutions that I've found (even though I don't fully understand any of them) and nothing works so any help or hint on this would be very appreciated!

folder-structure




differentiating between post requests

I have this jquery function which sends a POST request to the server

function loadInfo() {
    jQuery(function($) {
        $.ajax({
            method: "POST",
            url: "/admin.php",
            dataType: "json",
            success: function(data) {
                console.log(data);
                for (var i = 0; i < data.length; i++) {
                    setMarker(data, i, "red");
                    printInfo(data, i);
                }
            }
        })
    });
}

This is how the request gets handled

if($_SERVER['REQUEST_METHOD'] === 'POST'){
    header('Content-Type: application/json');
    require 'private/database.php';

    $sql = "SELECT * FROM form";
    $result = mysqli_query($conn, $sql);

    $data = array();
    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            $data[] = $row;
        }
    }
    die(json_encode($data));
}

The code works, but what if I have send multiple POST requests to the same server? Is there a way to differentiate between them like how you would when handling HTML forms? e.g. If the of the button that submits the form is "submit_button"...

if (isset($_POST['submit_button'])) {
   ...
}



Can I make a website only visible on chrome and redirect to other website when it's not chrome?

I am trying to make a website with features only available on browsers with WebKit engines, So I wanted the website to be displayed only on WebKit browsers and redirect to an alternative website if the host's browser doesn't use Webkit, Is it possible? If yes, How can it be done?




How can I add a href to an entire figure

I have the following html snippet:

 <figure>
        <img src='image.png' height="250" width="250">
        <figcaption>Album name goes here
            <br>Year goes here
        </figcaption>
</figure>

And the following css:

figure {
    display: inline-block;
    border: 1px;
    margin: 20px; /* adjust as needed */
}
figure img {
    vertical-align: top;
}
figure figcaption {
    border: 1px;
    text-align: center;
}

It would end up looking like this:

enter image description here

How can I set it up so that if a user clicks on the image or the caption under it he gets directed to a new page.




React Hook Forms Controller issues

I am quiet new to React Hook Forms. I am trying integrate Material UI with react hook forms. I am avoiding the use of normal submit rather using onClick on a button to trigger submit, I am using controller but for some reason when I submit my values always reflect default values and not the actual values on the input.

  <Controller
    name={name}
    control={control}
    defaultValue={defaultValue}
    render={() => (
      <QControl
        uiProp={uiProp}
        context={context}
        handleChange={handleChange}
      />
    )}
  />
        <Button
          type="submit"
          className="form-actions"
          variant="contained"
          color="primary"
          startIcon={<SaveIcon />}
          onClick={onSubmission}
        >
  const { control, handleSubmit } = useForm();
  const onSubmit = (data) => console.log(data);

  const onSubmission = handleSubmit(onSubmit);



I need to use web-based online chat in my website has the ability to keep the chat history for the visitor

I used some web-based chat services with monthly payment, all of them do not save the chat history for the visitors when they coming back again to my website.

So, I need to use web-based online chat in my website has the ability to keep the chat history for the visitor, and I know this feature needs an unique Identifier from the visitors for recognizing them when they come back again in another time.

I see most of the chats ask about the email before the visitor begin the chat, is there is any chat provider identify the visitor by their email when they come another time to the chat?




How to Connect Frontend and Backend

As I am a bit beginner

Could anyone help with how can I connect my Front-End (deployed on gh-pages) and backend ( deployed on Heroku) with each other

Frontend consists of simple index.html file and app.js file. And my Backend consist of server.js file.

How should I make changes to both of them. To integrate with each other.




Custom pc builder [closed]

Since I have a school project I decided to make a website just like the "PC PART PICKER", but the problem is I really don't know how to make the same pc builder which makes you custom your pc by selection the parts. I am really confused right now . by the way I am a beginner at web dev . So can anybody help me with this problem?




Scraping stats with Selenium

I would to scrape 1st half result and minute of goals in 2nd half from this page https://www.flashscore.co.uk/match/dxm5iiWh/#match-summary

Then I tried to scrape 1st half stats from this page https://www.flashscore.co.uk/match/dxm5iiWh/#match-statistics;1 with this code but I would fix Xpaths

P.S In the example I put only two stats but I will apply for all.

Thanks

        try:
        driver.find_element_by_xpath("//*[@id='a-match-statistics']")
        WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='a-match-statistics']"))).click()   
        home_shot=WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='tab-statistics-0-statistic']/div[2]/div[1]/div[1]"))).text
        away_shot=WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='tab-statistics-0-statistic']/div[2]/div[1]/div[3]"))).text
        home_shotontarget=WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='tab-statistics-0-statistic']/div[3]/div[1]/div[1]"))).text
        away_shotontarget=WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='tab-statistics-0-statistic']/div[3]/div[1]/div[3]"))).text
    except NoSuchElementException:
        home_shot = "no stats"
        away_shot = "no stats"
        home_shotontarget = "no stats"
        away_shotontarget = "no stats"



I need web-based online chat to my website keeping the chat history for the visitor

I used many online chat services like https://www.tawk.to/, all of them do not save the chat history for the visitor when they come again to my website.

I need web-based online chat to my website keeping the chat history for the visitor, and I know this feature needs an Identifier from the visitor for recognizing them where they come back again in another time.

I see most of the chats ask about the email before the visitor begin the chat, is there is any chat provider identify the visitor by their email when he come another time to the chat?




Cookies appear in chrome lock-icon menu but not in DevTools > Application Tab > Cookies section?

I was checking the Application tab in the Chrome DevTools to debug an analytics issue and I noticed that the cookies section was empty, although the cookies menu under the lock icon in the chrome search bar seemed to show the cookie that I was interested in.

I did a bunch of refreshing, clearing site data, and restarting Chrome with no change in behaviour.

Is this a bug in Chrome? Why is there a discrepancy between the two menus? Does it have to do with httpOnly or secure cookies?

Not a very important question, mostly just curious!




Unable to count clicks on links in a web page using javascript/php

I am trying to record the number of clicks performed by the user on the hyperlinks that are being retrieved from the Database on the web page.

This is my code:

echo "Name: ". $row["user"] . str_repeat('&nbsp;', 5).
'<a href="'.$row['lin'].' onClick= "Click();" ">Click</a>';

below is the function being called:

function Click() {
    
    if (typeof(Storage) !== "undefined") {
      if (localStorage.clickcount) {
        localStorage.clickcount = Number(localStorage.clickcount)+1;
      } else {
        localStorage.clickcount = 1;
      }
      document.getElementById("result").innerHTML = "You have clicked " + localStorage.clickcount + " time(s).";

    } else {
      document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
    }
    return true;
  }

Above is not showing the count when clicking on the hyperlinks. Any idea?




Developer.facebook.com asks for Data Deletion Url

When trying to switch from developer to live mode, developer.facebook.com gave me this warning:
Before switching to live mode, you must provide both a valid Privacy Policy URL and data deletion information. Update this information in Basic Settings on App Dashboard
I have provided my Privacy policy url, but I dont know what tu put here:
enter image description here

To be honest, I dont need this for live app, just for fb login on my test app, but when I try to login with Facebook, I got the error This app is still in development mode. Ok fb, I know...




mardi 29 décembre 2020

What is Serverless in Azure and AWS used for? [closed]

Good day,

i have a very basic question about serverless under Azure and AWS.

What is a concrete use case for it? As i understand Serverless is used so that you dont need to care about any of the underlying infrastrucure but rather only use functions for this (Function as a service). A bit confusing for me is that once you created your serverless envirement what can you do? me specifically i look to host a "visual website" where users can request and browse through this website. But after doing the quickstart of Azure for example i only get more confused about it?

Question:

Can somebody explain Serverless and maybe use a concrete use case or if you have experience in it to share it with me?

Thanks in advance




Hugo theme and local font with sass

Now, I use for a little project a Hugo theme blog called Persian. I'm trying it in gitlab and I want to use local fonts. Well, the problem is that I can't achieve load the fonts. Here the structure of my files on the exampleSite folder:

resources
└──_gen
    └── assets
          ├── scss
          │    ├── style.scss_f300667da4f5b5f84e1a9e0702b2fdde.content
          │    └── style.scss_f300667da4f5b5f84e1a9e0702b2fdde.json
          │ 
          └── fonts
               └── Open-Sans.woff2

On the file style.scss_f300667da4f5b5f84e1a9e0702b2fdde.content I wrote the next lines:

@font-face {
    font-family: 'OpenSans';
    src: url('../fonts/openSans.woff2') format('woff2');
}

But, when I call the font in other css rule doesn't work:

.class {
    font-family: "OpenSans"; /*this line doesn't work*/
}



AWS API Gateway 429 response - no CORS headers

The 429 responses issued by API Gateway (when lowering the max concurrent requests and exceeding it) do not have the CORS headers, so the ajax request in the browser just throws error without any info that could selectively make it trigger a retry.

Any workaround but for retrying any error in the client app / i.e. any work around to have AWS include the CORS headers in the 429 response? CORS is enabled in API gateway, the OPTIONS method is there and responds the headers, and a lambda responds them itself (proxy integration) - all works well but for the 429.




I am having errors with react repositories?

yarn add react-scripts
yarn add react-number-format

Every time I run vs-code I have to install react-scripts and react-number-format. I uninstalled and reinstalled the vs-code but issue still exists. It was solved before but not now. I use yarn start but it says react-scripts is not found.




How to prevent a website detecting from switching tabs? [closed]

I am using autoproctor website to write an online exam it detects when I switch tabs or windows. how to get rid of that?. The website does not use any visibility API or blur focus event




How disable the blue boundary box when a touch occurs on chrome mobile?

I would like to get rid of the blue rectangle for touch visual feedback on my web application. It's always get very unpleasant on rounded button.

enter image description here

The button above has a css to make it rounded and an active state color. I don't need the native chrome mobile visual feedback.

How can I disable this feature in my mobile website?




Collapse responsive navbar on angular 7

Hi im using navbar in angular 7 and i need to collapse it on another page location click, when i resize my browser or when i use my app on mobile the navbar put 3 bars icon for display menu, when i click on another place in the app the menu still shown, how can i collapse the menu ?

here is my HTML file.

<nav class="navbar navbar-inverse sub-navbar navbar-fixed-top">
    <div class="container"> 
        <div class="collapse navbar-collapse" id="subenlaces">
            <ul class="nav navbar-nav navbar-right">
                <li><a data-toggle="collapse"routerLink="/">Inicio</a></li>
                <li *ngFor="let item of menu" class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button"
                        aria-expanded="false"><span class="caret"></span></a>
                    <ul class="dropdown-menu" role="menu">
                        <li  *ngFor="let subitem of item.secundario">
                            <a routerLink="">
                                
                            </a>
                        </li>
                    </ul>
                </li>

...
...

here is the menu, if i click on white section the menu still shown, i need to clic the 3 bars icon again to collapse it. How can i collapse it on click another element or white space?

enter image description here

Best regards!




How load (server-side) localhost webpage from web server?

How can I load a web page running on http://localhost:9001 from my website on http://localhost:9000?

Currently the website loads the client's localhost.




downloading the database of usernames in a website as a text file

so I'm trying to troll scammers online, and to do so, I need to download a massive list of real usernames from a website, and combine those with fake passwords, how would I go about downloading the list of usernames in a website, if its even possible?




What is the best web hosting service

I am currently making a website on HTML js css... I want to know what is the best WebHosting service that is cheap




Is using fs.writeFile() an acceptable replacement for a database for a fully Front-end website?

I have a fully developed and deployed front end website that is looking to have a way for users to voluntarily enter their name and email. To move the website to a server to host and implement a backend seems really difficult. Would it be possible for us fs.writeFile() to write to a file in the path? Would this run into security issues?

We don't mind if the names are public, we would make it a disclosure above the form. The main concern is that the website would be flagged as unsafe.




I want to find all the configuration files used in a Java web project

for eg:

there might have unused configuration files in a J2ee web application.

I want to get to know only the configuration files used in an J2ee web application.

is there anyway or tool available?




Is there a possible chance to download an embedded video from a Website which has its controlslist="nodownload"?

The Problem im facing right now, is that I want to download a Video from a Website. Thsi Website has an Account protection (Thats means that online converters do not have any permissions). Furthermore the embedded Html Video has the controlslist set to no download. I do not know if this was a reasonable try but I inspected and changed it to download. Now there was a possible downlaod button but I only could downlaod the whole html file of the website - without video. After that I tried to grab the URl of the video since the html player was not useable for a downlaod and I cant right-click. I checked on inspecting again and found through the Network Media Filter Option the Video URL. That is what i think- it leads to some server that I have no permissions for to look into if I go back in the path. example path server/data/videos/example.mp4 Now if I try to just insert the Video Url into the search bar it just sends me back to the Home site of the website. Seems like a securtiy system. So now im a bit Stuck and im not a pro programmer. Just a regular pc guy. Maybe you can help me a bit ;D




How can i make the text in my web server change line

Hey i did a small project to display text on a web server but for some reason all the text is on the same line and i don't know how to change it.

code:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def main():
    return """fxfxzvxczxcvxvzx
cxzvxczxcvcxvfdsvxz"""

if __name__ == "__main__":
    app.run(debug=True, host="127.0.0.1", port=5050) ```



Microsoft IIS Virtual Directory: Host images on local server, show on local website

I am developing a website, and publishing / seeing results on my machine. I want to store images on a LAN server, that others may access on their local machine for website development. Next step is to create a virtual folder corresponding to physical location of the images. So that others can work on the website on their own machines, and access the images from one location.

I am new to IIS tools. How should I proceed, even in a general over-view that helps me figure it out?

It was suggested to me that this virtual folder in IIS should be a sub-directory of my working folder.




Fortumo WEB SDK

I trying to use fortumo web sdk So, I get last ip addresses of fortumo but I getting Error: Unknown IP

  if(!in_array($_SERVER['REMOTE_ADDR'],
//add Fortumo hosted ip addresses inside the 'array'.
array(my ip addresses here)))
{
  header("HTTP/1.0 403 Forbidden");
  die("Error: Unknown IP");
}



Web Scraping with Python by Ryan Mitchell Chapter 3

I am trying to teach myself python web scraping. I came across this line of code that I cannot fully understand. The line I do not understand is.

for link in bs.find_all('a', href=re.compile('^(/|.*'+includeUrl+')')):

The larger code snippet is here.

from urllib.request import urlopen
from urllib.parse import urlparse
from bs4 import BeautifulSoup
import re
import datetime
import random

pages = set()
random.seed(datetime.datetime.now())

#Retrieves a list of all Internal links found on a page
def getInternalLinks(bs, includeUrl):
    includeUrl = '{}://{}'.format(urlparse(includeUrl).scheme, urlparse(includeUrl).netloc)
    internalLinks = []
    #Finds all links that begin with a "/"
    for link in bs.find_all('a', href=re.compile('^(/|.*'+includeUrl+')')):
        if link.attrs['href'] is not None:
            if link.attrs['href'] not in internalLinks:
                if(link.attrs['href'].startswith('/')):
                    internalLinks.append(includeUrl+link.attrs['href'])
                else:
                    internalLinks.append(link.attrs['href'])
    return internalLinks

I understand that the includeUrl function already extracts the scheme and the netloc to create a full fledged link. As an example if we use the following url, we would get that result.

'https://ift.tt/1003CGT' is the url,

'https' is the scheme

stackoverflow.com netloc

So what exactly does this function do if you already have a well formed link like https://www.facebook.com? Does this only work for not complete links and can someone give me an example of how to correctly interpret this function?

Thank you.




Scraping a lazy loading website using Selenium

I am trying to build a simple Web Scraping Project on Goibibo.com and am trying to work on this page specifically.

Generally, my approach to scraping any dynamic website is to scroll down until I have enough data to scrape, then load the HTML into BeautifulSoup to scrape. But in this case, the website uses some kind of lazy loading where it loads only the elements visible to the user are rendered in HTML and the ones the user scroll pasts are removed. So, if I try to parse the HTML data I find about 6-10 hotels in the soup.

I want to find a way to extract all of the hotels on this page. I initially thought of scrolling to each div of each posting but I am not sure how I can achieve that.

Here's what I have done so far

chrome_options = webdriver.ChromeOptions()
chrome_options.binary_location = "chromedriver.exe"

driver = webdriver.Chrome()
link = "https://www.goibibo.com/hotels/hotels-in-delhi-ct/"
driver.get(link)
driver.maximize_window()
sleep(2)

driver.execute_script("window.scrollTo(0, document.body.scrollHeight*(0.75))") #75% as the footer is tall
sleep(2)

showMore = driver.find_elements_by_xpath("//*[@id='root']/div[2]/div/section[2]/button") #Clicking the show more button
driver.execute_script("window.scrollTo(0, document.body.scrollHeight*(0.75))")
showMore[0].click()

for _ in range(10):

    driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
    sleep(1)
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight-2000)") 
    # Hacky way to load more listings as the loading was stuck for some reason until I scrolled again
    sleep(2)

html = driver.page_source
soup = BeautifulSoup(html, "html.parser")



How l can add cookies in library fetch-nodejs

l need help Lam use fetch-nodejs To fetch url like chegg.com

But l need add cookies in my code l need help for that

How l can add cookies in library Fetch-nodejs




Which headless CMS should I use for website and mobile app?

So I would like to create a sports website (with live scores and articles, etc.) which I will develop using ReactJs. And I was looking to find if I should use a CMS and if yes which one, because I read and saw a bunch of things about the wordpress headles CMS but I am not sure if I should use it. In addition propably later on I will create a mobile app to go with the website ( using flutter or maybe react native) and I would like to display my website's content on my app as well without having to do double the work needed to post something. I would really appreciate it if you could help me. Thank you in advance.




What does this error say? [CS50 WEB FINANCE]

I am doing CS50 Web track finance buy and this is my code which gives the error given below The error which it is giving is confusing and I dont understand what it is saying as well as how to correct my code. Any help wpuld be appreciated.

def buy():
    """Buy shares of stock"""
    if request.method == "POST":
        symbol = request.form.get("Symbol")
        quote = lookup(symbol)
        # Checking if Quote is available
        if not quote:
            return apology("Quote not Found",403)
        else:
            shares = request.form.get("Shares")
            # Get current user cash
            rows = db.execute("SELECT * FROM users WHERE id=?", session["user_id"])
            cash = rows[0]["cash"]
            print(cash)
            amount = float(shares)*quote["price"]
            if cash < amount:
                return apology("NOT ENOUGH CASH",403)
            else:
                cash -= amount
                # Add to transactions
                db.execute("INSERT INTO transactions (user_id,symbol,price,shares,amount) VALUES(:user_id,:symbol,:price,:shares,:amount)",user_id=session["user_id"],symbol=quote["symbol"],price=quote["price"],shares=shares,amount=amount)
                # update cash in users
                db.execute("UPDATE users SET cash = :cash WHERE id=:user_id",user_id =session["user_id"],cash=cash)
                return redirect("/")
    else:
        return render_template("buy.html")

Error

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/ubuntu/finance/helpers.py", line 34, in decorated_function
    return f(*args, **kwargs)
  File "/home/ubuntu/finance/application.py", line 57, in buy
    quote = lookup(symbol)
  File "/home/ubuntu/finance/helpers.py", line 44, in lookup
    response = requests.get(f"https://cloud-sse.iexapis.com/stable/stock/{urllib.parse.quote_plus(symbol)}/quote?token={api_key}")
  File "/usr/local/lib/python3.7/urllib/parse.py", line 850, in quote_plus
    string = quote(string, safe + space, encoding, errors)
  File "/usr/local/lib/python3.7/urllib/parse.py", line 834, in quote
    return quote_from_bytes(string, safe)
  File "/usr/local/lib/python3.7/urllib/parse.py", line 859, in quote_from_bytes
    raise TypeError("quote_from_bytes() expected bytes")
TypeError: quote_from_bytes() expected bytes
INFO: 192.168.239.121 - - [29/Dec/2020 13:18:22] "POST /buy HTTP/1.0" 500 -
INFO: 192.168.239.121 - - [29/Dec/2020 13:18:23] "GET /static/styles.css HTTP/1.0" 200 -
INFO: 192.168.239.121 - - [29/Dec/2020 13:18:23] "GET /static/favicon.ico HTTP/1.0" 200 -



PHP array value not returning from a function?

When I'm trying to return an array from a php function, its not returning any value.Tried after json_encode also. Array displays its value while printing it inside the corresponding function.




STARTTLS extension not supported by server while attaching more than 1 mb file

I am getting "STARTTLS extension not supported by server" while attaching more than 1 MB file with the mail. While attaching less than 1 MB file the exception is not being generated in python.

if file_size <= ATTACHMENT_FILE_SIZE :
            print('in if condition')
            logger.info(f'{thread_name} : In If Condition')
            mailDetails.attach(MIMEText(body_to_be_sent, "html"))
            attachment = open(filepath, 'rb')
            payload = MIMEBase('application', 'octet-stream')
            payload.set_payload(attachment.read())
            encoders.encode_base64(payload)
            payload.add_header('Content-Disposition', "attachment; filename= %s" % f'''{file_name}.xlsx''')
            mailDetails.attach(payload)
            try:
                connection = smtplib.SMTP(SMTPserver)
                connection.ehlo()
                connection.starttls()
                connection.set_debuglevel(False)
                connection.login(SMTPUSERNAME, SMTPPASSWORD)

                text = mailDetails.as_string()
                connection.sendmail(FROM_MAIL_ADDRESS,toAddress.split(",") + ccAddress.split(",")+bccAddress.split(","), text)
                logger.info(f'{thread_name} : Mail Sent successfully')
                # os.remove(filepath)



Wt++ TableView and QueryModel

I have a problem with tableView and queryModel this is my error:

    lo.C: In constructor ‘HelloApplication::HelloApplication(const Wt::WEnvironment&)’:
hello.C:162:48: error: no matching function for call to ‘Wt::WTableView::setModel(std::remove_reference<Wt::Dbo::QueryModel<Wt::Dbo::ptr<Utente> >*&>::type)’
 tableView->setModel( std::move(modelDataTable) );
                                                ^
In file included from hello.C:30:0:
/usr/local/include/Wt/WTableView.h:94:16: note: candidate: virtual void Wt::WTableView::setModel(const std::shared_ptr<Wt::WAbstractItemModel>&)
   virtual void setModel(const std::shared_ptr<WAbstractItemModel>& model)
                ^
/usr/local/include/Wt/WTableView.h:94:16: note:   no known conversion for argument 1 from ‘std::remove_reference<Wt::Dbo::QueryModel<Wt::Dbo::ptr<Utente> >*&>::type {aka Wt::Dbo::QueryModel<Wt::Dbo::ptr<Utente> >*}’ to ‘const std::shared_ptr<Wt::WAbstractItemModel>&’

This is a Utente class: class Utente { public: Utente(); std::string nome; std::string cognome;

    template<class Action>
    void persist(Action& a)
    {
        dbo::field(a, nome, "nome");
        dbo::field(a, cognome,     "cognome");
    }
   ~Utente();
};

this code is in inside in application class :

auto *modelDataTable = new Wt::Dbo::QueryModel<Wt::Dbo::ptr<Utente>>();
modelDataTable->setQuery(session.query<Wt::Dbo::ptr<Utente>>("select utente from utente Utente"));
modelDataTable->addAllFieldsAsColumns();

auto tableView = root()->addWidget(std::make_unique<Wt::WTableView>() );
tableView->setModel( std::move(modelDataTable) );



Download SVG files

I want to download files using javascript which have svg extension. Actually I have around 300 svg urls which i want to download via code. I have tried with this code

function downloadURI(uri, name) {
  var link = document.createElement("a");
  link.download = name;
  link.href = uri;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  delete link;
}
downloadURI("https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/410.svg", "helloWorld.svg");

but by this a tab with the given url is getting opened, i want it to be downloaded.

Here is the example link i am trying to download Example Link




iOS - Link from web browser opens an app in iOS app although it should be redirected to web browser

There is an iOS app.

There is a link on a web: <a href="https://ift.tt/3nS8FEq>"

In iOS app, there is an apple-app-site-association file with config

{
  "applinks": {
    "apps": [],
    "details": [
      {
         "appID": "....",
         "paths": ["NOT /forgotPassword", "*"]
      },
      {
         "appID": "....",
         "paths": ["NOT /forgotPassword", "*"]
      }
    ]
  }
}

but the redirection happens from that link on a web to the iOS app, although this is in configuration: "NOT /forgotPassword" and redirection to iOS app should be intercepted and blocked.

( I followed instructions from: How to support Universal Links in iOS App and setup server for it? )

I tried "paths": ["NOT /forgotPassword", "*"] as well as "paths": ["*", "NOT /forgotPassword"]

How do I configure it so opening links in browser would be redirected to iOS app (this part is working), EXCEPT when client calls https://somedomain.com/forgotPassword...

Sidenote: This part: opening links in browser would be redirected to IOS app - was working fine and still works fine when I had "paths": ["*"] but when I introduced NOT clause, as is suggested in the stack overflow link above that I provided, this doesn't work. Should I format it in some other way?

P.S. I'm a web developer, so if there are steps to be taken on iOS part, please be as concise and detailed as possible so I can forward it to iOS team.




lundi 28 décembre 2020

Serve Voice files in Django

I want to serve voice files in the Django app and let users play and have all features like youtube. Voice files are in large size, and the client should not wait for all file to play, and they can move in all voice time and play any part they want




how to find much visitor on my blog in 2021?

I have a blog- My experiences

How to Increase page view in 2021 whereas google updated his algorithm.




My site isn't loading proper on first 2secs

My site when opened or searched is not loading proper on first to 2 sec later its perfect my page doesn't appear proper only 1sec later its perfect.




Back-end donation-tracking solution for a small DIY website

What is the most efficient way to implement web-based customer/sales tracking for a small DIY website?

I’ve implemented a bare-bones HTML/JavaScript ecommerce-donation front end, using PayPal as the payment processor, and now I’m trying to figure out how to build the back end to track donors and what item they donated to.

My web host (Namecheap) runs MySQL, so my first thought is to create a custom database (a table each for Donors, Donations, and Items) and transfer data back and forth with client-side JavaScript. However, I know just enough about databases to know it’s a steep learning curve fraught with traps. If it’s the best way, fine, but there are other things I could do with those hours.

Tracking donors and items is similar to tracking customers and sales, so I’m wondering if there’s an off-the-shelf solution available with a friendly JavaScript-accessible API. I asked Namecheap Support, they don’t offer anything.

Googling turns up a bunch of CRMs (e.g. AgileCRM) but I can’t tell which ones have good APIs, or how much I’d have to pay. I have to think there’s a solution somewhere out there in the cloud that I can bend to work….anyone?

I’m not looking to add any graphics to my web page, I just need the back-end functionality: list donors’ email addresses, track donations, etc.




Why I get a black model when I load a GLTF model which have materials?


I m trying to load my 3d model which have glb format. Here's the code:

What I exept: Image
What I have: Image

var renderer = new THREE.WebGLRenderer();

renderer.setSize(1000, 1000);
renderer.setPixelRatio(window.devicePixelRatio);
const camera = new THREE.PerspectiveCamera(75, 1000 / 1000, 0.1, 1000)
camera.position.z = 0.5;

document.body.appendChild(renderer.domElement);

const scene = new THREE.Scene();
scene.background = new THREE.Color('white');

const gltfLoader = new THREE.GLTFLoader();
  const url = 'hub.glb';
  gltfLoader.load(url, (gltf) => {
    const root = gltf.scene;
    scene.add(root);

  });

var render = () => {   
    requestAnimationFrame(this.render);
  
    
    renderer.render(scene, camera);
}

render();

When I check the variables, the color material is set and correct.
Here's the variable explorer: Image

Thank you !




Accessing deleted Tinder conversation

Is there a way to access Tinder messages if the conversation itself is already deleted? If this is the wrong sub, please advice on the correct one.




Is this bad javascript practice? [closed]

My website has multiple pages that use the Google Maps api. Each page uses a different part of the api (e.g. autocomplete, displaying markers etc). However, every page needs to call the initMap() function for the api to be initialized.

maps.js

function initMap() {
  const mapOptions = {
    center: {lat: 0, lng: 0},
    zoom: 7
  };
  window.map = new google.maps.Map(document.getElementById("map"), mapOptions);

  if (typeof callback !== 'undefined') {
    callback(); // defined above html link to maps.js
  }
}

Instead of writing out a different initMap() function for every page, I opted to have it in one .js file which is linked to every page. After initializing the map, the function executes a callback function which is defined in each page's corresponding .js file.

index.js

function autocomplete() {
    var input = document.getElementById('address');
    var options = {
    };
    new google.maps.places.Autocomplete(input, options);
}

As initMap() cannot take parameters, I had to define the callback function's name using a cross-script global variable before maps.js is linked. This variable is different on every page depending what function needs to be run in initMap() after the map is initialized.

<script type="text/javascript" src="js/index.js"></script>
<script> var callback = autocomplete </script> <!-- global variable, defines the callback function (in index.js) to initMap()(in maps.js) -->
<script type="text/javascript" src="js/maps.js"></script>

The code works but is very disjointed. Is there a cleaner way to accomplish this?




Trying to query database if user inputted city and state is there and redirect if True or False in Django

I have a sorting page that the visitor to my website enters in a city and state where they want to live. I need to check against out database if we have any results in or near that city. Below is my code.

def address(request):
    if request.method == 'POST':
        form = CityStateForm(request.POST)
        if form.is_valid():
            obj = Location_Targeting()
            city = request.POST.get("city")
            state = request.POST.get("state")
            homeAvailable = Home.objects.get(city = city, state=state)
            obj.city = form.cleaned_data["city"]
            obj.state = form.cleaned_data["state"]
            obj.save()
            return render(request, 'app/success.html')
        else:
            obj = Location_Targeting()
            obj.city = form.cleaned_data["city"]
            obj.state = form.cleaned_data["state"]
            obj.save()
            return render(request, 'app/failed.html')

    return render(request, 'GMH_app/address.html')

I want to save the form to my database in its own table which it should, but doesn't do. Then I want it to query the Home table in my database and look up the city and state and if there are homes in the city or surrounding area it redirects to a success page otherwise it redirects to a failure page.

In my debugger it shows the correct kwargs but returns a does not exist but I know it does. Also it seems to be case sensitive which wont be user friendly.

I know this probably seems like a lot but I have tried a lot of different things including the documentation and the above is as far as I've gotten. It may be that the state is a tuple ("1", "Alabama") etc. that may need to be unpacked? It shows the key number in the state column for the table it gets in the debugger. "1" instead of "Alabama". Would this throw it off? It wont save the state it just gives a Keyerror 'state'.

Any help is greatly appreciated. Thanks in advance. Hopefully I'm on the right track.




React Native Alert.alert() only works on iOS and Android not web

I just started learning and practicing React Native and I have run into the first problem that I cant seem to solve by myself.

I have the following code, which is very simple, but the Alert.alert() does not work when I run it on the web. if I click the button nothing happens, however, when i click the button on an iOS or android simulator it works fine.

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, Button, View, Alert } from 'react-native';

export default function App() {
  return (
      <View style={styles.container}>
        <Text style={styles.headerStyle} >Practice App</Text>
        <Text style=>Open up App.js to start working on your app!</Text>
        <Button
          onPress={() => alert('Hello, Nice To Meet You  :)')}
          title="Greet Me"
        />
        <StatusBar style="auto" />
      </View>
  );
}

I also know that alert() works on all three devices, however, I want to understand why Alert.alert() only works for iOS and Android.

My question is more so for understanding rather than finding a solution. Is the only solution to use alert(), or am I implementing Alert.alert() in the wrong way?




How to get SSL certificate for homemade webserver

I've created my own webserver using Node.js ans is using it with my DNS from webhost routed to my raspberry pi at home. How do I prepare the webserver and all the files for getting an SSL certificate using Let'sencrypt?

I've not made any work prior to getting the SSL other than creating the server to run on localhost. Now it's running on a public ip while using my purchased DNS.

I haven't been able to find any litterature other than the off the shelf webservers like apache and such and I really want to run with my own.




React list component won't rerender after deleting one component from it

I am writing a kind of a ToDo app in React, which has Boards, Lists and Cards as components. I am using an API to do operations with these components. Board has a list of List components, List component has a list of Card components.

The Board filters the list of List components to only display the ones set as open. When I try to close a List from the Board, somehow the Board gets rerendered to only remove the last List component. I have checked it through Postman and the correct List gets closed, but I just can't get it to render properly. After refreshing the page, the Board component is rendered correctly, at the List components are displayed as expected.

Here is my code sample below.

//List component
 const archiveList = () => {
    fetch(
      `https://URL/${
        props.list.id
      }/closed?key=${API_KEY}&token=${TOKEN}&value=${true}`,
      {
        method: "PUT",
      }
    )
      .then((response) => response.json())
      .then(props.setLists(props.lists.filter((list) => list.id !== props.list.id)))
  };

//Board component

const [lists, setLists] = useState([]);
const { selectedBoard } = useContext(BoardContext);


useEffect(() => {
    fetch(
      `https://URL/${getBoardId()}/lists?key=${API_KEY}&token=${TOKEN}`
    )
      .then((response) => response.json())
      .then((data) => setLists(data.filter((d) => d.closed === false)));
  }, [selectedBoard]);

const displayLists = () => {
    return lists.map((list, i) => {
      return (
        <Cell key={i} col={12} shadow={1}>
          {list.idBoard === getBoardId() ? ( <div>
            <List list={list} setLists={setLists} lists={lists} />
           </div>
          ) : (
            <div></div>
          )}
        </Cell>
      );
    });
  };

I am still new to React so this confuses me quite a bit. Any help is greatly appreciated!