dimanche 31 janvier 2021

Use Flutter's TabBar and TabBarView: When you locate the last tab and add a new tab, the page will load twice

使用Flutter的TabBar和TabBarView开发一个可以动态增加tab的页面: (Use Flutter's TabBar and TabBarView to develop a page that can dynamically add tabs:)

class _DemoTabState extends State<DemoTab> with TickerProviderStateMixin {
  TabController tabController;
  int tabNum = 3;

  @override
  Widget build(BuildContext context) {
    int index = tabController?.index ?? 0;
    tabController?.dispose();
    tabController = TabController(length: tabNum, vsync: this, initialIndex: index);
    tabController.animateTo(tabNum-1);
    var tabs = List.generate(
      tabNum,
      (index) => Tab(
        text: 'tab' + index.toString(),
      ),
    );
    var tabPages = List.generate(
      tabNum,
      (index) => Center(
        child: TestPage(index),
      ),
    );

    var tabBar = TabBar(
      tabs: tabs,
      controller: tabController,
    );
    var tabBarView = TabBarView(
      children: tabPages,
      controller: tabController,
    );
    var result = Scaffold(
      appBar: tabBar,
      body: tabBarView,
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          setState(() {
            tabNum++;
          });
        },
      ),
    );
    return result;
  }
}
  1. 当定位在最后一个tab时再增加时,新增的page会加载两次,第一次加载后立刻被dispose,pring: (When it is added when positioned at the last tab, the new page will be loaded twice, and it will be dispose immediately after the first load, print:)

    2--testPage--didUpdateWidget  
    2--testPage--build  
    3--testPage--initState  
    3--testPage--didChangeDependencies  
    3--testPage--build  
    3--testPage--dispose  
    3--testPage--initState  
    3--testPage--didChangeDependencies  
    3--testPage--build  
    2--testPage--dispose  
    
  2. 当定位在最后一个tab时再增加时,新增的page只加载一次,打印: (When it is added when positioned at the last tab, the newly added page is only loaded once, print:)

    1--testPage--didUpdateWidget  
    1--testPage--build  
    3--testPage--initState  
    3--testPage--didChangeDependencies  
    3--testPage--build  
    1--testPage--dispose  
    

Live Demo: http://cairuoyu.com/flutter_demo
Code: https://github.com/cairuoyu/flutter_demo/blob/main/lib/demo/demo_tab.dart or
https://github.com/cairuoyu/flutter_admin/blob/master/lib/pages/layout/layout_center.dart

Results of flutter doctor -v:

[√] Flutter (Channel beta, 1.25.0-8.3.pre, on Microsoft Windows [Version 10.0.18363.1316], locale zh-CN)
    • Flutter version 1.25.0-8.3.pre at F:\projects\f\flutter
    • Framework revision 5d36f2e7f5 (2 weeks ago), 2021-01-14 15:57:49 -0800
    • Engine revision 7a8f8ca02c
    • Dart version 2.12.0 (build 2.12.0-133.7.beta)
    • Pub download mirror https://pub.flutter-io.cn
    • Flutter download mirror https://storage.flutter-io.cn

[√] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
    • Android SDK at C:\Users\cairu\AppData\Local\Android\sdk
    • Platform android-30, build-tools 29.0.3
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
    • All Android licenses accepted.

[√] Chrome - develop for the web
    • Chrome at C:\Program Files (x86)\Google\Chrome\Application\chrome.exe

[√] Android Studio (version 4.1.0)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)

Is this a Flutter bug, or is there a problem with my writing?




Intellij Dart Webdev Cannot Find "devtools0.9.7+1/build"

I had no issues at all building my project, I duplicated it to start a new one, still worked then I made some code changes then I randomly can't build it at all. Even the previous project stopped building and I have no idea what the error is. I've tried purging the dart pub cache and everything but it seems this specific error hasn't happened to anyone yet from what I've searched.

Output:

Unhandled exception:
Invalid argument(s): A directory corresponding to fileSystemPath "/Users/chrisl/.pub-cache/hosted/pub.dartlang.org/devtools-0.9.7+1/build" could not be found
#0      createStaticHandler (package:shelf_static/src/static_handler.dart:50:5)
#1      defaultHandler (package:devtools_server/src/external_handlers.dart:40:23)
<asynchronous suspension>
#2      serveDevTools (package:devtools_server/src/server.dart:183:21)
#3      DevTools.start (package:dwds/src/servers/devtools.dart:26:15)
#4      Dwds.start (package:dwds/dwds.dart:132:33)
#5      WebDevServer.start (package:webdev/src/serve/webdev_server.dart:130:25)
#6      ServerManager.start (package:webdev/src/serve/server_manager.dart:23:38)
#7      _startServerManager (package:webdev/src/serve/dev_workflow.dart:103:27)
#8      DevWorkflow.start (package:webdev/src/serve/dev_workflow.dart:196:31)
<asynchronous suspension>
#9      DaemonCommand.run (package:webdev/src/command/daemon_command.dart:108:29)
<asynchronous suspension>
#10     CommandRunner.runCommand (package:args/command_runner.dart:197:27)
#11     _CommandRunner.runCommand (package:webdev/src/webdev_command_runner.dart:38:24)
#12     CommandRunner.run.<anonymous closure> (package:args/command_runner.dart:112:25)
#13     new Future.sync (dart:async/future.dart:223:31)
#14     CommandRunner.run (package:args/command_runner.dart:112:14)

Build Output




Save input from html to text file problem

So, I've copied this code and tried to run it. It supposed to take the input (in this case, name) and save it into a text file. But, it didn't work as I expected, can someone tell me what's wrong with this code?

<!DOCTPYE html>

<head>
<title>Web test</title>
</head>

<body>
<form onSubmit="WriteToFile(this)">
    <label>Name please: </label>
    <input type="text" name="nname" id="fname" size="18">
    <br>
    <br>
    <input type="submit" value="submit"> 
</form>
<script>
    function WriteToFile(passForm){
    set fso = CreateObject("Scripting.FileSystemObject");
    set s = fso.CeateTextFile("test.txt", True);
    var firstName = document.geteElementById('fname');
    s.writeline(firstName);
    s.writeline("");
    s.Close();
    }
</script>
</body>
```


php __destruct why get different result by file_get_contents

the content in hint.php is "111"

<?php

class T{
    public $filename = "hint.php";

    function __destruct() {
        var_dump(file_get_contents($this->filename));
    }
}

new T();

this got

string(3) "111"

And when I set a variable $t, the result will be different.

$t = new T();

this got

string(0) ""

why this happend




How to share network remotely from a remote computer

The company has a computer A (windows 10 system), the company only this computer A can connect to a trading center test network, usually we will write the trading center test code into the computer A test run, but due to the use of many people, resulting in the need to queue to use, a lot of code into this computer to run computer A is very stuck.

We use VPN remote connection to connect to PC A. Is there any way to share the network of this computer and use it as a gateway to forward requests so that we can all connect to the trading center test network, so that we don't need to put the program on PC A to run,

For example, the network of the trading center is 200.XX.XX.XX, which is not accessible from the external network, but only PC A can access it, for example, PC A's network IP is 172.20.20.20.

How can we achieve this so that our local computer can access 200.XX.XX.XX normally? For example, is there any way to forward our request to access 200.XX.XX.XX to 172.20.20.20, then 172.20.20.20 will access 200.XX.XX.XX and get the result, and then return to our computer by the same path.

It's like building a ladder, but unlike a ladder, we are also connected via VPN when accessing computer A:172.20.20.20. Can I ask if the normal way of building a ladder can meet this requirement?

  1. List item

Or are there any links to help with this?




How Opera is caching web content?

My preferred web browser is Opera but I'm having hard time dealing with PC freezing whenever disk usage culminates to 100% (a frequent event now since I'm always opening many tabs similtaneusly). When trying to understand what is happening under the hood of the filesystem, I'm quickly lost among all these folders such as :

data/cache/data_01

data/cache/data_02

data/gpucache/

data/shadercache/

data/service worker/scriptcache/index-dir

I know what is caching and what is webstorage but I don't know where people who wrote Opera or Chrome code learned to design this cache system ?

Since this system seems to be liable for performance degradation (IMHO),I want to understand and modify it...

Is there any link for a book or serious forum explaining such "architecture" - knowing that many contents on the Internet don't give real answers




API to classify location as urban, suburban, or rural

I'm trying to classify colleges as having a urban/suburban/rural location. I can't seem to find any websites that classify colleges in these categories (odd, right?). So I was thinking of using the location of the school to classify the college as urban/suburban/rural. Are there any apis or even websites (where I would have to use web scraping) that could classify a location as urban/suburban/rural?




Which is the best website to practice PHP programs?

Which is the best website to practice PHP programs? except W3schools




How is it possible to validate the clipboard content into an HTML input textbox?

<input type="number" id="example">

I can easily limit the set of the typed characters.

I don't want to prohibit the ctrl+v and mouse pasted inputs. Also, this field shouldn't accept any content. If the solution is using jQuery, it would also perfect.

In case of a pasted text is set into an input field, how can I validate it?




Why do we need to bundle out web application for deployment?

When we publish the web application to production we usually bundle it and the entire bundle (main.js/venndor.js) gets downloaded on the browser.

Why cant we serve files as it is (other than vendor files), one at a time, obviously after compressing them but not bundling them together?

What are the advantages and disadvantages of deploying single files instead of bundles, I understand there is limit in terms of how may resources browser can download at a time, what else is stopping us other than this?




How to use Python to create a forum website?

I'd like to build a website using Python. I have a lot of free time and I figured that I'd like to make a website which reviews pretty much anything.

I have looked at website builders etc. but I feel like I'll gain more from the experience if I code it myself.

I know python to a decent level but I have never touched html, I know that I can use flask (though I'd have to learn it) to build websites using python.

Are there any other resources that you'd recommend? Should I try to actually code it or just find a website builder? Any help is much appreciated :)




Unable to change variable by function

I can't figure out why my function getID() isn't changing the galleryID variable. Any help appreciated!

var img;
var gallery = {0: "CIBf-QSFMZD", 1: "CFfihZ0BxQo", 2: "CDUNuwvgB7N", 3: "CByDTh8gUWa", 4: "CB3i7NoA-IK", 5: "CKSEJG9rlJn", 6: "CEHrD8yAFXn", 7: "CIY6OZ-FGJB", 8: "B-12Va2DQ96", 9: "CB3e-QHAx5e", 10: "CI29bFllEBm", 11: "B1enhruHg9i"};
var galleryID;
function on(ima) {
  img = ima.id;
  document.getElementById("instagram-embed").src = "https://www.instagram.com/p/" + img + "/embed?utm_source=ig_embedembed/captioned/";
  document.getElementById("overlay").style.display = "block";
  document.getElementbyId("container").style.backgroundColor = "black";
  document.getElementById("container").style.zIndex = "2";
  getID();
}

Everything seems to work fine aside from the function below

function getID() {
var i = 0;
while(!(img == gallery[i])){
i++;
}
galleryID = i;
}

The value of galleryID just won't change from undefined. I've checked the equality comparison statement separately and it seems to be working ok, giving the right true and false outputs.

Thanks for any help!




Profanity Filter with ReactJS

Consider the following code:

/* eslint-disable array-callback-return */
/* eslint-disable no-unused-expressions */
import React from 'react'
import './App.css';


let swear = [
'arse',
'ass',
'asshole',
'bastard',
'bitch',
'bollocks',
'bugger',
'bullshit',
'crap',
'damn',
'frigger',
]

const App = () => {
  let [count , setCount] = React.useState(0)
  let [approval , setApproval] = React.useState(false)
  let [text , setText] = React.useState('')


  
  const bogusCheck = (text) =>{
    swear.map(word => {
      text.includes(word) === true ? (console.log('Bad word found') ): (console.log('No bad word found')); 
    })
  }

  return (
    <div className="App">
      <h1>Profanity Checker</h1>
      <p>Enter a sentence below and click the button below:</p>
      <textarea cols="30" rows='10' value={text} onChange={e => setText(e.target.value) } />
      <br />
      <button onClick={() => bogusCheck(text)} >Profanity Check</button>
    </div>

  );
}
export default App;

This is supposed to be a profanity filter. The theory is that it takes input from the text area and then uses the .map() and .includes() function to compare.

swear is an array it includes some bad word.

So the map loops over the swear array, picks up each word and see if it is included in the text. If returns true it console logs (Bad word found). If not it logs(No bad word found)

The issue is that when I click the button, it logs 13 times the not required result and then logs once the required result followed by more non required result. See the image below.

What is the turnabout solution for this??

(NOTE: THIS ALGORITHM / FUNCTION WILL BE USED IN A LARGE PROJECT I'M CURRENTLY DOING FOR A UNIVERSITY, SO A GOOD SOLUTION IS REQUIRED)

Thanks in Advance




Will it be decreased google rank?

If a good google ranked website is rebuilt from scratch with same content, same design, same template (everything same) in the same domain and hosting , Will it be decreased google rank?




404 error when running local host command: django, python

when running the local host command, I get a 404 error. I have defined the empty ' ' path but the only URL paths that work are the '/admin', /posts/', and '/posts/about'.

urls.py

from django.urls import path
from . import views

urlpatterns = [
path('', views.home, name='Posts-Home'),
path('about/', views.about, name='Posts-About'),

]

views.py

from django.shortcuts import render
from .models import verdict

posts1 =[
    {
        'author' : 'Tom E',
        'title' : 'review1',
        'content' : 'verdict1',
        'date_posted' : 'today',
    },
    {
        'author' : 'Adam K',
        'title' : 'review2',
        'content' : 'verdict2',
        'date_posted' : 'yesterday' 
    }
]


    # Create your views here. 
    def home(request):
        #puts data into dictionary
        context ={
            #postkey
            'reference' : verdict.objects.all()
        }
        return render(request, 'posts/home.html', context)
    
    
    def about(request):
         return  render(request, 'posts/about.html', {'title': 'about'})



How to do user specific deployment of web application?

I have a web application and I came across a scenario where I am about to release a new version of my application but I want that version to be available to only a specific set of users first?

For example my app has users (a, b, c, d, e, f g, h). I am releasing v2 of my app, these users do not need to know that I have released a new version of my app. Whenever users (a,b,c) try to access the application they should be redirected to v2 and whenever rest of the users try to access the application they should be redirected to v1.

How can this be achieved from the point of view of deployment and system design?




Rental room system with easy modification of room layout

I am during analysis of one of rental room reservation and there is a requirement to modify or to replace with a brand new solution. The current one uses SVG for reservation and it works like that: enter image description here

There red squares are rooms, and black lines separates between them to distinguish different ones. When I focus my pointer on selected room it is being highlighted with some additional information like pictures, surface area and many other properties. The idea I'm looking for is to have such utility to be able to modify one of selected rooms by adding extra line within one of rooms, and after adding such line there are two rooms. There is no special requirement for technology (I can use something totally new) but the only requirement I have is have it inside web page. Also, there is no need to divide a room with saving precise properties, I just need to use one tool to create a new room from one.

Are you aware of a project which uses such feature?




website different output in windows/android and apple ecosystem

first, i'm sorry if my english bad. the problem is, i don't know what's happening here, but my website site if you open it in safari or chrome on IOS or MacOs is not the same like in the windows10 or android

look at the List of receiving countries on picture, in windows and android its what i expected

ios

android

here's the css properties for LIST OF RECEIVING COUNTRIES

  width: 336px;
  color: #48a9b5;
  text-transform: uppercase;
  text-align: center;
  font-size: 24px;
  font-family: "GothamLight";
  background-color: white;
  display: block;
  border-radius: 10px;
  margin: 0 auto;
  padding: 15px 30px;
  position: absolute;
  top: -50px;
  left: calc(50% - (336px / 2));



How to place multiple lines of text right to image

HTML: https://pastebin.com/ALpLGdLt

CSS: https://pastebin.com/nDn8V9dj

I want to place multiple lines of text right to image, as in the picture below.

this

Please, help.

<html>
<head>
    <title>Профиль - RPGrad.Online</title>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="style.css">
    <link rel = "stylesheet" href="Main_Font.ttf">
</head>
<body>
    <div id="profile">
        <br>&nbsp;&nbsp;&nbsp;<img id="avatar" src="Image/Standart_Avatar.png">
        <name id = "name" >farkon</name>
        <emp class = "money">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;44</emp>
        <img class = "moneyimg" src="Image/money.png">
    </div>
    <br><br><br><div id="my_bills">
        <div class="bill">
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="Image/money.png" class="bill_icon" align="top"> 
                <name class="bill_name">Счёт Farkon'а</name> 
                <br><emp class = "money">20</emp>
                <img class = "moneyimg" src="Image/money.png">
        </div>
        <div class="bill">
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="Image/money.png" class="bill_icon" align="top">
            <name class="bill_name">Казна UseFul Town</name>
        </div>
    </div>
</body>
</html>```



samedi 30 janvier 2021

Update the data from date picker in react js

I want to ask How to get data from date picker . and when pick the date from datepicker enter image description here




Django: Adding monthly goal for products model, and daily production

I'm sorry if my question seems weird, I'll try to explain:

I'm building an app for my family's company, there are some products, and every month I need to set a goal for each product for each user.

I also need each user to be able to submit how much they've sold of each product every day

I'm confused about the approach I should use to relate all of these

What I've done is created models for the Products, for the goals and for 'production' (how much they've sold that day)

First, I put each product as field in the 'Production' model, but that wouldn't allow me to change anything using the admin panel

So, how can use the Products models in the Production models as "fields". ex:

class ProductsModel(models.Model):#This is the form each worker is supposed to fill every day, Worker is set accordingly to logged in user

     Worker = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL)  
     ProductsModel1 = models.FloatField()#How much they've sold of this product
     ProductsModel2 = models.FloatField()#How much they've sold of this product
     I'd like to do this for as many Products as there are

And for the goals, this is what would be ideal:

class GoalsModel(models.Model):#This is me or the manager that are supposed to use, could be done throught the django admin page
      
        Worker = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL)
        Month = models.CharField(max_length=9, choices=MONTH_CHOICES, default='1')
        Product1 = models.FloatField() #The goal for this product in the selected month
        Product2 = models.FloatField() #Goal for this product in the selected month
        .... This for as many Products as there are

This is what I have so far in my models.py:

class ProductsModel(models.Model):
    Name = models.CharField(max_length=50)

    def __str__(self):
        return self.Name


class GoalsModel(models.Model):
    Worker = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL)
    Product = models.ForeignKey(ProductsModel, on_delete=models.SET_NULL, null=True)
    Month = models.CharField(max_length=9, choices=MONTH_CHOICES, default='1')
    Goal = models.FloatField()

class ProductionModel(models.Model):
    Worker = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL)
    Day = models.DateField(default=now)

    #What I had done was: I placed each product here, instead of creating a model for them, but that wouldn't allow me to add new products without changing the code directly

    def  __str__(self):
        answer = ('{}s production in {}'.format(self.Worker, self.Day))
        return answer

I'm sorry if it feels like I'm trying to get someone to do everything for me, but I am just trying to explain so that everything hopefully makes sense.




Is it possible to render a browser in colab output cell?

I know that html pages can be rendered in colab output cell, but is it possible to render as well as browse webpages that we specify in input. I have tried IPython.display.Iframe and IPython.display.HTML but Iframe doesn't show most of the modern websites and IPython.display.HTML can't handle links inside a rendered webpage.




Curl Command: how do you register an account non-temporarily with Curl command?

I created a website that you can just create an account and login with that account, and then I tried to register an account by POST method and get the user information by GET method with Curl in terminal. But, it seemed that I can only get the user info while running the program. It means that the user I registered with Curl POST disappears from the database after shutting down the program. Is it possible to register an account that remains in the database non-temporarily?

This is the Curl command I used:

curl -X POST -H "Content-Type: application/json" -d /some contents/ http:///some address/

Best regards,




Add another cards on the Voyage Slider

I found a code for voyage slider,

https://gist.github.com/Blazingiowa/95ef74491a8e7dd6235b7621e88f5ab9

But now I am stuck, how can we add more number of cards on this slider?




Vue 2 Typescript error: 'No overload matches this call' and 'Property does not exist'

I need to use Typescript for the first time and it's in a Vue 2 project. I'm trying to write a simple Login component (actually it's in views) and I get a few type errors that I can't find a solution for.

(Actually the type errors don't prevent it from running on localhost (everything seems to work fine) but I can't host it the website because I can't run 'npm run build' as it won't finish with the errors.)

Would really appreciate any help!

Login.vue

<template>
<div>
  <div class="wrapper">
    
    <div class="form">
      <h1 class="title">Login</h1>
      <div class="tile is-vertical is-8">
        <b-field label="Email">
          <b-input type="email" icon="email" v-model="email"/>
        </b-field>
        <b-field label="Password">
          <b-input icon="lock" type="Password" password-reveal v-model="password" validation-message="Succeeded!"/>
        </b-field>
        <b-message type="is-danger" v-if="error">
            
        </b-message>
        <b-button class="is-primary login-button" @click="login">Login</b-button>
      </div>
      <GoogleLogin />
          <div class="register-wrapper">
        <p>Don't have an account yet? <router-link :to="{path: '/register'}"> Register here</router-link></p>
      </div>
    </div>
    

  </div>
  <Footer/>
</div>
</template>

<script lang="ts">

import Vue from "vue";
import GoogleLogin from "@/components/GoogleLogin.vue";
import Footer from "@/components/Footer.vue";
import firebase from "firebase/app";
import "firebase/auth";

import { mapGetters } from "vuex"; 

export default Vue.extend({
    components: {
      GoogleLogin,
      Footer
    },
    computed: {
      ...mapGetters(["user"]),
      nextRoute() {
        return this.$route.query.redirect || "/profile";
      }
    },
    data() {
        return {
            email: '',
            password: '',
            error: ''        
        }
    },
    watch: {
      user(auth) {
        if (auth) {
          this.$router.replace(this.nextRoute);
        }
      }
    },
    methods: {
        login() {
          firebase.auth().signInWithEmailAndPassword(this.email, this.password)
            .catch(err => this.error = err)
        },
        loginGoogle() {
          const provider = new firebase.auth.GoogleAuthProvider();
          firebase.auth().signInWithPopup(provider)

        },
        
    },
})
</script>

Errors

ERROR /src/views/Login.vue(62,32):
62:32 No overload matches this call.
  Overload 1 of 2, '(location: RawLocation): Promise<Route>', gave the following error.
    Argument of type 'unknown' is not assignable to parameter of type 'RawLocation'.
      Type 'unknown' is not assignable to type 'Location'.
  Overload 2 of 2, '(location: RawLocation, onComplete?: Function | undefined, onAbort?: ErrorHandler | undefined): void', gave the following error.
    Argument of type 'unknown' is not assignable to parameter of type 'RawLocation'.
      Type 'unknown' is not assignable to type 'Location'.
    60 |       user(auth) {
    61 |         if (auth) {
  > 62 |           this.$router.replace(this.nextRoute);
       |                                ^
    63 |         }
    64 |       }
    65 |     },
ERROR in /src/views/Login.vue(68,59):
68:59 Property 'email' does not exist on type 'CombinedVueInstance<Vue, unknown, unknown, { nextRoute: unknown; user: any; }, Readonly<Record<never, any>>>'.
    66 |     methods: {
    67 |         login() {
  > 68 |           firebase.auth().signInWithEmailAndPassword(this.email, this.password)
       |                                                           ^
    69 |             .catch(err => this.error = err)
    70 |         },
    71 |         loginGoogle() {
ERROR in /src/views/Login.vue(68,71):
68:71 Property 'password' does not exist on type 'CombinedVueInstance<Vue, unknown, unknown, { nextRoute: unknown; user: any; }, Readonly<Record<never, any>>>'.
    66 |     methods: {
    67 |         login() {
  > 68 |           firebase.auth().signInWithEmailAndPassword(this.email, this.password)
       |                                                                       ^
    69 |             .catch(err => this.error = err)
    70 |         },
    71 |         loginGoogle() {
ERROR in /src/views/Login.vue(69,32):
69:32 Property 'error' does not exist on type 'CombinedVueInstance<Vue, unknown, unknown, { nextRoute: unknown; user: any; }, Readonly<Record<never, any>>>'.
    67 |         login() {
    68 |           firebase.auth().signInWithEmailAndPassword(this.email, this.password)
  > 69 |             .catch(err => this.error = err)
       |                                ^
    70 |         },
    71 |         loginGoogle() {
    72 |           const provider = new firebase.auth.GoogleAuthProvider();



HTML/CSS Fill div with color from right to left and left to right

I'm trying to make my own bar chart which i imported it to pdf using Dom PDF. i have minus number on my result so i need to fill my bar from right to left. This is my current code right now

<td width="400px">
                <div style="width:100%; margin-bottom: 2px; margin-top:10px;">
                    <div
                        style="width:50%;display:inline-block;text-align:right">
                        <div class="w3-light-grey w3-round-large"
                            style="margin-bottom: 2px; margin-top:2px;text-align:right;">
                            <div class="w3-container w3-blue w3-round-large"
                                style="width:40%;text-align:right;float:right">0</div>
                        </div>
                    </div>
                    <div
                        style="width:50%;display:inline-block;text-align:right">
                        <div class="w3-light-grey w3-round-large"
                            style="margin-bottom: 2px; margin-top:2px;text-align:left">
                            <div class="w3-container w3-blue w3-round-large"
                                style="width:50%;text-align:center;"></div>
                        </div>

                    </div>
                </div>

</td>

and the result goes like this. result bar

Is it possible to achieve that? Thank you




I want to control the same LED with button on web and phsysical push-button use NodeMCU

I want to control the same LED with a button on the web and physical push-button. I use NodeMCU. I tried running each of them and running well. My web is made in PHP & Mysql and HTML. When I press a button on the web led will turn on or off. Then NodeMCU will give feedback on GPIO status to the database and show it on the web. Then when I press a push-button led will turn on or off then NodeMCU will give feedback GPIO status to database and show it on the web too. It's running well when I'm running each of them. but when I'm combining them it doesn't work. Here is my code. Can anybody help me out?

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#define ON_Board_LED D0

int button_on = D5;
int button_off = D6;
int led = D4;

const char* ssid = "joday";
const char* password = "";
const char* host = "http://192.168.43.64/";

void setup() {
  pinMode(button_on, INPUT);
  pinMode(button_off, INPUT);
  pinMode(led, OUTPUT);
  pinMode(ON_Board_LED,OUTPUT);
  Serial.begin(115200);
  delay(500);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password); //--> Connect to your WiFi router
  Serial.println("");
    
  pinMode(ON_Board_LED,OUTPUT); //--> On Board LED port Direction output
  digitalWrite(ON_Board_LED, HIGH); //--> Turn off Led On Board

  pinMode(led,OUTPUT); //--> LED port Direction output
  digitalWrite(led, LOW); //--> Turn off Led

  //----------------------------------------Wait for connection
  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    //----------------------------------------Make the On Board Flashing LED on the process of connecting to the wifi router.
    digitalWrite(ON_Board_LED, LOW);
    delay(250);
    digitalWrite(ON_Board_LED, HIGH);
    delay(250);
    //----------------------------------------
  }
  //----------------------------------------
  digitalWrite(ON_Board_LED, HIGH); //--> Turn off the On Board LED when it is connected to the wifi router.
  //----------------------------------------If successfully connected to the wifi router, the IP Address that will be visited is displayed in the serial monitor
  Serial.println("");
  Serial.print("Successfully connected to : ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println();
  //----------------------------------------
  
}

void loop() {
  
  HTTPClient http;

  //----------------------------------------Getting Data from MySQL Database
  String GetAddress, LinkGet, getData, LEDStatResultSend;
  int id = 0; //--> ID in Database
  GetAddress = "Nodemcu_web/GetData.php"; 
  LinkGet = host + GetAddress; //--> Make a Specify request destination
  getData = "ID=" + String(id);
  Serial.println("----------------Connect to Server-----------------");
  Serial.println("Get LED Status from Server or Database");
  Serial.print("Request Link : ");
  Serial.println(LinkGet);
  http.begin(LinkGet); //--> Specify request destination
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");    //Specify content-type header
  int httpCodeGet = http.POST(getData); //--> Send the request
  String payloadGet = http.getString(); //--> Get the response payload from server
  Serial.print("Response Code : "); //--> If Response Code = 200 means Successful connection, if -1 means connection failed. For more information see here : https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
  Serial.println(httpCodeGet); //--> Print HTTP return code
  Serial.print("Returned data from Server : ");
  Serial.println(payloadGet); //--> Print request response payload
  
  if (payloadGet == "1") {
    digitalWrite(led, HIGH);
    LEDStatResultSend = "1";
  }
  
  else if (payloadGet == "0") {
    digitalWrite(led, LOW);
    LEDStatResultSend = "0";
  }
  else if (digitalRead(button_on) == HIGH){
    digitalWrite(led, HIGH);
    LEDStatResultSend = "1";
   }
  else if (digitalRead(button_off) == HIGH){
   digitalWrite(led, LOW);
    LEDStatResultSend = "0";
   }  
 

  //----------------------Sends LED status feedback data to server-------------------------
    Serial.println();
    Serial.println("Sending LED Status to Server");
    String postData, LinkSend, SendAddress;
    SendAddress = "Nodemcu_web/getLEDStatFromNodeMCU.php";
    LinkSend = host + SendAddress;
    postData = "getLEDStatusFromNodeMCU=" + LEDStatResultSend;
    Serial.print("Request Link : ");
    Serial.println(LinkSend);
    http.begin(LinkSend); //--> Specify request destination
    http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //--> Specify content-type header
    int httpCodeSend = http.POST(postData); //--> Send the request
    String payloadSend = http.getString(); //--> Get the response payload
    Serial.print("Response Code : "); //--> If Response Code = 200 means Successful connection, if -1 means connection failed
    Serial.println(httpCodeSend); //--> Print HTTP return code
    Serial.print("Returned data from Server : ");
    Serial.println(payloadSend); //--> Print request response payload
  //-----------------------------------------------------------------------------------------
  
  Serial.println("----------------Closing Connection----------------");
  http.end(); //--> Close connection
  Serial.println();
  Serial.println("Please wait a seconds for the next connection.");
  Serial.println();
  //delay(1000);
  
}



React Build Pages/Router/SEO/Sitemap

I have an react web app and it has routes like about,contact etc... When i type "x.x/route" to the browser i get "404 Not Found" but when i click to the link with the component i get the page and my url = "x.x/route" even i get 404 in manual type

And in sitemap.xml i do not receive the routes

So ... is there anyway to make it optimized for SEO or SITEMAP.XML ? or how can i make a build with folders




More Detailed/Waved Line Chart

I am trying to create a line chart using Google Charts Library, what I tried so far is: I added 2 columns and 50 rows and what I get is something like this: enter image description here Count is generated randomly on every row

What I want is something like this:enter image description here which has more waves, I tried to add more rows like around 500 but it still looks like the chart above.

So what should I do? is it because I generate random numbers?




Composer detected issues in your platform: Your Composer dependencies require a PHP version ">= 8.0.0"

I upload my laravel project on azure. However when I go to the link I got this error. My project php version is 8.0.0 and my azure php version is 7.4.11. How can I can increase the version on my azure php.




How to develop a website for courier trackings?

I want to develop a website where people track their shipments like TCS, LCS, Bluedart, etc. Can anyone guide me from where I can start or from where I can buy a complete website?

Thanks




How can I evaluate an HTML input element for any possible changes and reshape the value?

I have an HTML input element for positive integer numbers. I need to evaluate this input field and ensure that only proper values are inserted.

HTML:

<input id="exampleInput" type="number"
      value="0" min="0" step="1" maxlength="5" onkeypress="exampleFunction(event, this)">

JS:

function exampleFunction(event, element){

  // If event is not backspace and Not a Number
  if(event.which != 8){

    //If the event is Not a Number
    if(isNaN(String.fromCharCode(event.which))){

      // Cancels the event
      event.preventDefault();
    }
    //If the length reached the limit
    else{

      var value = document.getElementById(element.id).value;
      var maxLength = document.getElementById(element.id).maxLength;
      var valueLength = document.getElementById(element.id).value.length;

      if(valueLength >= maxLength){

        // Cancels the event
        event.preventDefault();
      }else{

        // Convert the value to a number and back to string. This means leading 0 will be gone.
        document.getElementById(element.id).value = Number(value);
      }
    }
  }

};

purposes:

  • default value is 0
  • only numbers shall be accepted
    • no decimal value .,
    • no other characters +-e
  • the input can come from:
    • typing
    • copy
  • backspace and delete can also modify the value
  • length of input shall also be limited for 5 character length
  • leading 0 shall be eliminated after a proper new value

Problems:

  • the default value is 0 and leading zeros are not immediately deleted, only after the second number is typed
  • with ctrl+v .,+-e characters can be inserted

Question: Is any better solution for my purposes? If it is jQuery related, it is also acceptable.

Maybe I am not using the proper event. I tried also to handle the input event but it is not possible to evaluate the input text. I am not sure if I make this too complicated, or the solution would be much more complex than I think.




Ajax.BeginForm does not update the page but it get a new one

I am working on Ajax Demo with MVC in my example there is a submit button and radio buttons when i click on the button the form is post successfully and the ajax.BeginForm Work well but the radio buttons also can submit but it returns the partial view and view it without update which means that all the page disappears and just the partial view appears

the model code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AjaxDemo.Models
{
   public class Customer
   {
       public int ID { get; set; }
       public string Name { get; set; }
       public int  Age { get; set; }
   } 
}

the CustomerControler Code is

using AjaxDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AjaxDemo.Controllers
{
    public class CustomerController : Controller
    {
    
        public ActionResult Index()
        { 
           List<Customer> l = new List<Customer>() { new Customer() { Name = "a", ID = 1, Age = 20 },
                                                  new Customer() { Name = "b", ID = 2, Age = 21 },
                                                  new Customer() { Name = "c", ID = 3, Age = 22 },
                                                  new Customer() { Name = "d", ID = 4, Age = 23 },
                                                  new Customer() { Name = "e", ID = 5, Age = 24 },
                                                  new Customer() { Name = "f", ID = 6, Age = 25 },
                                                   };
           Tuple<List<Customer>, Customer> tuple = new Tuple<List<Customer>, Customer>(l, l[0]); 
           return View(tuple);
        }
        [HttpPost]
        public ActionResult GetCustomerDetails(int id)
        {
           List<Customer> l = new List<Customer>() { new Customer() { Name = "a", ID = 1, Age = 20 },
                                                     new Customer() { Name = "b", ID = 2, Age = 21 },
                                                     new Customer() { Name = "c", ID = 3, Age = 22 },
                                                     new Customer() { Name = "d", ID = 4, Age = 23 },
                                                     new Customer() { Name = "e", ID = 5, Age = 24 },
                                                     new Customer() { Name = "f", ID = 6, Age = 25 },
                                                   };
          Tuple<List<Customer>, Customer> tuple = new Tuple<List<Customer>, Customer>(l, l[id-1]);
          return PartialView(@"~\Views\Shared\_CustomerDetails.cshtml", l[id-1]);
        }
    }
 }

The Index View Code is

@using AjaxDemo.Models
@model Tuple<List<Customer>, Customer>
@{
    ViewBag.Title = "Index";
    AjaxOptions ajaxOptions = new AjaxOptions();
    ajaxOptions.UpdateTargetId = "InformationDiv";
    ajaxOptions.HttpMethod = "post";
    ajaxOptions.InsertionMode = InsertionMode.Replace;
}
<h2>Customers</h2>
@using (Ajax.BeginForm("GetCustomerDetails","Customer", ajaxOptions,new { @id = "customerform" }))
{
    foreach (var item in Model.Item1)
    {
        <div>
            @{
               bool selected = item == Model.Item2;
               @Html.RadioButton("id",item.ID,selected,
                                  new{@onchange="$('#customerform').trigger('submit')" })
               @Html.Label(item.Name)
               <br />
             }
       </div>
    }
    <input type="submit" value="Details" id="SubmetButton" />
}
<div id="InformationDiv">
    @Html.Partial("_CustomerDetails", Model.Item2)
</div>

The _CustomerDetails PartialView Code

@model AjaxDemo.Models.Customer
<div>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.ID)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.ID)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.Name)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Name)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Age)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Age)
        </dd>

    </dl>
</div>

in the layout Code i Imported the files

<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>



How is Zoom able to launch itself from the browser? [duplicate]

When opening a Zoom link, the browsers shows a popup that asks if you'd like to launch zoom. Then, the Zoom desktop installation is launched.

What is the mechanism for doing this? I thought you couldn't access the local system from Javascript.

enter image description here




how to create wordpress registeration and login form

I want too create a custom website using wordpress, not a blogging one though, I want users to be able to register and login to my website through a form , please note that I don't want users to be "wordpress" users who can manage posts. any idea how to achieve that?




Need a call recording solution for android or web

We are trying to make an android app for call recording. The idea is to record outgoing calls to ensure customer satisfaction. However, we cannot record calls according to Android's policy for android 9 and above. I need a workaround. I don't care if it is a web solution or an android solution, I just need a solution. Can you guys recommend how will I able to record local calls made by the customer support team?

Thanks.




Web Worker: Problems on NodeJS

I tried to implement the w3schools demo of web worker on nodejs, but it doesn't work. The OS is Windows 10 (v10.0.18363.1256), Chrome (v88.0.4324.104) is set on developer mode and nodejs (x64-v14.15.4). No errors appear both on the browser and command prompt, which tells me that it's all ok (Server running at http://127.0.0.1:80/). The web page appears, but the buttons don't work. You can read the code below. The file myapp.js to start the node is in my own user folder, whereas demo_worker.js and index.html are in the folder c:\nodejsworker. Thank you in advance for your help.

// demo_workers.js
var i = 0;

function timedCount() {
  i = i + 1;
  postMessage(i);
  setTimeout("timedCount()", 500);
}

timedCount();

//myapp.js
const http = require('http');
var fs = require('fs');

const hostname = '127.0.0.1';
const port = 80;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/html');
  // res.end('Hello World');
  var myReadStream = fs.createReadStream('C:/nodejsworker/index.html', 'utf8');
  myReadStream.pipe(res);
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
<!DOCTYPE html>
<html>

<body>

  <p>Count numbers: <output id="result"></output></p>
  <button onclick="startWorker()">Start Worker</button>
  <button onclick="stopWorker()">Stop Worker</button>

  <script>
    var w;

    function startWorker() {
      if (typeof(Worker) !== "undefined") {
        if (typeof(w) == "undefined") {
          w = new Worker("./demo_workers.js");
        }
        w.onmessage = function(event) {
          document.getElementById("result").innerHTML = event.data;
        };
      } else {
        document.getElementById("result").innerHTML = "Sorry! No Web Worker support.";
      }
    }

    function stopWorker() {
      w.terminate();
      w = undefined;
    }
  </script>

</body>

</html>



is Node interface just a concept ? What is the difference between element interface and node interface?

is Node interface just a concept ? What is the difference between element interface and node interface ? when Programmatically used for i need examples please !!




Error returned as Object of class mysqli_result could not be converted to string

I have function like below

function getUserBooking(){
        $uId = $_SESSION['userId'];
        $sql = "SELECT eventName,type,date,status FROM booking WHERE userId='$uId'";
        global $connection;
        $result = mysqli_query($connection,$sql);
        return $result; 
}

Then I call it as below and loop it as shown

$res = getUserBooking();
while($row = mysqli_fetch_assoc($res)){
    echo $row['eventName'];
    echo '<br>';
}

But it gives a error like below

Fatal error: Uncaught Error: Object of class mysqli_result could not be converted to string

What am I doing wrong here? Thank for your help !




saving multiple values in select not working PHP

I am having trouble to save the option values in a select box?, it only save one option, adding a [] after the name in the selectbox (array) the whole function breaks and saves nothing

Here's my code:

 function wp_custom_client($post)
{
    $args = array(
        'role' => 'customer',
        'order_by' => 'user_nickname',
    );
    $users = get_users($args);

    $customer = get_post_meta($post->ID, 'wp_custom_attachment_user', true);


    print '<select id="wp_custom_attachment_user" name="wp_custom_attachment_user" style="width:250px; height: 150px;" multiple>';
    print '<option value="" disabled selected>' . __('Kies een klant') . '</option>';
    foreach ($users as $user) {
        $selected = ($user->ID == $customer) ? 'selected' : '';
        print '<option value="' . $user->ID . '" ' . $selected . '>' . $user->display_name . '</option>';
    }
    print '</select>';
    print '<p>Hou Ctrl (Windows) of Command (Mac) ingedrukt om meerdere opties te selecteren.</p>';

}

And the saving code:

  /* Customer */
    if (isset($_POST['wp_custom_attachment_user'])) {
        update_post_meta($id, 'wp_custom_attachment_user', $_POST['wp_custom_attachment_user']);

    }

Anyone can help please?? Much appreciaded




Does anyone have a good tutorial for understanding how to make a database and link it with a searchbar

Does anybody have a tutorial or wants to explain to me how to make a functional search bar? I have designed but I can t find any piece of information on the internet on how to make a functional search bar for an ecommerce type of website. I need to search for the names of the products and display the image, title and price of it. I have all the code for the website, but I can find my way around this problem. Thank you!




What methods and techniques of web-layouts do you use?

Everyone knows that layout is the most time-consuming, tedious, creative and situational process. Someone is building a pile of crutches, to live to please in throws layouts, someone sculpts styles directly in inline-style property, thinking that he's got the styles and layout in one file to not have the cereal in style.css file (in this case in style.css were only some common elements); someone who does modular layout like BAM , for example, and someone just uses bootstrap and him coding the actual top of the mountain (well, until you meet the real layouts)

As for me, I use some particle of BEM methodology (from yandex, it's not advertising) -- > describe independent blocks and elements inside them and then apply modifiers there to change the color or size (padding, width). If you need to adjust the position of the element (margin, float, display, etc.), then I use two styles -- > navbar (as general styles for the component) and header _ _ navbar (where I will adjust the margin or width, if it is set as a percentage)

At the very least, I use the inline property style, so as not to produce sooo many blocks or elements and their modifiers However, in this case, I still get porridge and it is not quite convenient to maintain it, just time passes, or in the development process I forget what the default block looks like and start producing modifiers to customize the appearance. Accordingly, after I start to forget what a particular block/element looks like, I simply lose all desire to work on the project further and keep it all in my head.

I understand that the preprocessor (e.g. Sass) will save the situation and allow the styles of the independent components to keep in one place, but what about the fact that I forget, how this or that independent component or the element --> okay, even when elements or components tens, and when rolled over a hundred already such a mess begins in the mind.

I think to make up separate pages, where I will have all the independent components and elements -- > for example, as it is done in UI / UX design (actually, I also do design), there is a separate ArtBoard for components and it is very convenient to work with them, even when there are a lot of them.

Could you share your thoughts and suggestions on this matter? After all, every chef has their own approaches and techniques.

For the layout, I use twelve columns (in the design) and I just take the same grid from bootstrap (just the grid)




I can't set a php cookie

I made a php script that allows me to switch the language of my website and for that, I used a cookie called lang to store the user's language prefer but I don't Know why this cookie can't be set as I can't find it in the chrome developer tap .. Although I made this script also with session variable in case cookie isn't set, it doesn't work either, as it shifts the language whenever I change the page

this is my PHP script

<?php
  session_start();
  if(isset($_GET['lang'])) {
    $lan = $_GET['lang'];
    $_SESSION['lang'] = $lan;
    setcookie("lang", $lan, time() + (3600 * 24 * 30), '/');
  } else if (isset($_SESSION['lang'])) {
    $lan = $_SESSION['lang'];
  } else if (isset($_COOKIE['lang'])) {
    $lan = $_COOKIE['lang'];
  } else {
    $lan = 'en';
  }

  include "languages/" . $lan . ".php";
?>

I have two files in that language folder en.php and ar.php and each one contains an array with translation like below

<?php
$lang = array(
  "Give" => "Give",
  "Blood" => "Blood",
  "Register as a donator" => "Register as a donator",
  "Search for a donator" => "Search for a donator"

I include my script in all my site's pages
here is my chrome developer tap screen shot

any thoughts?
Thanks for helping in advance :)




vendredi 29 janvier 2021

Can I get the ID of an HTML element in a javascript function without passing any parameters?

Can I get the ID of an HTML element in a javascript function without passing any parameters?

I have an HTML element:

<input type="text" id="exampleInput" value="0" onkeypress="exampleFunction()">

From javascript, I would like to change the value of the HTML element.

function exampleFunction{
  
}

Is it possible to achieve this without passing the ID as a parameter?




ExpressJs : Get data of Form data body

I use express js to create api.

In Postman I pass:

POST http://localhost:3000/test

Form data :     email: 'nasd@gmail.com'

header :     Content-Type: 'application/x-www-form-urlencoded'

when I console.log(req.body)

It appear:

{ '------WebKitFormBoundary9RYiOTi2ZDqN1AnB\r\nContent-Disposition: form-data; name': '"email"\r\n\r\nasd@gmail.com\r\n------WebKitFormBoundary9RYiOTi2ZDqN1AnB--\r\n' }

How can I get the email field?

This is my Code:

let express = require("express");
let morgan = require("morgan");
let bodyParser = require("body-parser");
let expressValidator = require("express-validator");
let session = require("express-session");
var multer = require("multer");
var upload = multer();
let MySQLStore = require("express-mysql-session")(session);

let app = express();
let PORT = 3000;

let options = {
  host: "localhost",
  port: "3306",
  user: "root",
  password: "12345678",
  database: "timekeeper4",
};
let sessionStore = new MySQLStore(options);

app.use(
  session({
    key: "session_cookie_name",
    secret: "session_cookie_secret",
    store: sessionStore,
    resave: true,
    saveUninitialized: false,
  })
);
app.use(morgan("dev"));
app.use(bodyParser.json());
app.use(expressValidator());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(upload.array());
app.use(express.static("public"));

app.use("/test", (req, res) => {
  console.log(req.body.name);
  console.log(req.body);
  res.send("Hello World!");
});

app.listen(PORT, () => {
  console.log("Server started on http://localhost:" + PORT);
});

module.exports = app;



Localhost REFUSED to connect AGAIN

so yesterday i had a problem with my website. it said php pdo could not find driver. so i asked mr stackoverflow and someone suggested removing the semicolon in front of the extension. I did that, but now i have a bigger problem. localhost refused to connect. I tried to search it up but most of the results were irrelevent. any ideas?




When is console is executed in JavaScript?

if console is a web API then does it goes into callback queue? and if so then it means that all the console are executed after the JS code has finished running?




What's the best ways for a management server (from the public cloud) to access the REST APIs serving from a server sitting in the private networks?

We have a management server and UI sitting in the public cloud (Azure). We have a server which sits in our private networks, and it serves some REST APIs.

We want to access these REST APIs from the UI of the management (in the public cloud) to the REST API server serving from the private networks. The REST API server sitting in the private networks does not have a public IP address and hence the cloud UI/ management server cannot access it directly. What's the best way to handle this problem?

Would it be a good way to make the REST API server (which is sitting in the private networks) to initiate websocket connections to the cloud UI/ management, and then allowing the UI/ management (which becomes the client in this case) to initiate API requests within the websocket to the REST API server which sits in the private networks?




In flipkart or Amazon what type of image use?

In flipkart or Amazon I saw very high quality photo in 4,5KB. How it possible. What type of technology they use? When I use even webp format also pic is not too good after compress but in flipkart they use very high resolution image with very low file size. Please explain...




Python 3.8.5 Flask giving internal server error with WSGI application when template is called using render_template in VS Code - 500 server error

I have been following a YouTube tutorial made by Corey Schafer using Flask. I have reached the 2nd tutorial about using html templates, but that is the only place I have reached. This is the program I am running called hello.py:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')

app.run()

This is the HTML file I have been using, called home.html:

<!DOCTYPE html>
<html>
  <head>
    <title>Flask Template Example</title>
</head>
<body>
    <div>
        <p></p>
    </div>
</body>
</html>

Whenever I try to run my code, I always get the error jinja2.exceptions.TemplateNotFound: template.html. I've tried to look at all possible solutions, but none have seemed to work. How could I fix this? I'm on a Windows 64-bit machine.




How to add an image to website with the image address including you website

How do you add an image to you website so that the image address's domain is you website? Such as; https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png Cick here because I am not allowed to embed pictures into my post because don't have more than 10 points And not like this;

<html>
<head>
<title>Example</emaxple>
</head>
<body>
<img src="https://lh3.googleusercontent.com/TyjVGZqfT_MuQh86xLiQtr6MIPeAJSmvOHnTpj7r2Go-V68dkOfw1zyZX_ZQo0j54O2jitom6mF94fFsiUC7UXNr_SznAk8WbYqiHogylNnPnFi9PR2qD8kaH5LCF05SzXpZ9PPzWQE128x8sz8kXuvtmnfrCwCWUCfgk-1NusQ_1qwQhGNj3EW_n9QaqO_2eryLyTJQzquIz0sRj8--80r8lFwrL8iFzSfri48Kpny1BWmbaxKAueurIfYOc8VyX4d2Do2QKat43wXOxWbaeCWjkvsahMDoLSwJbvHxLOSzRTfUOQH1etJsUGJQbt5cgbCcHhsKEQQiZ3qqf-rXSHkdeyb6QL4EMVJsvfU7k45cdRba1gq0w7uAfWovZSsSv65A_dvJtIHvmvCPmpNcwU2-uN7hGRyuMUl8g5gm3KA6FrxPLQ8v0gZCeLCGJ5Je8JoCVYQ8Z9wHm2qLlo6mGPu_NIarHz7H9m4KM_CftWaG_Q1d82U8OFDbVWBdBEjlR7sYVnDCMSb2oUXRioRahLaQjnQzRpVfacBUZNa_a5Amnw2txzI0ly8JfVcRu3TYCWA74bHGDPAs3ijRGh_Lk2ggJabOhZ9pGTl1_BbCp8ihCnQYLwwR2Smmwub55Kdv4CibSM57_dFe7bo3xNYjqzFEoZnebeX8xX7YWpNI1LiGK3jeZeeieDS9JAw=w328-h177-no?authuser=0">
</body>
</html>

How do I get a clean image address that includes my website domain on Github (exaple.com/media/photo.jpeg)?




favicon doesn't show HTML

i want to but favicon in my sit, it work good in browser tab but don't work In the search results

Picture for illustration

this is my code

   <link rel="icon" href="layout/f/icon1.png">



Assistance with Custom Domain to Redirect to Discord Server

I was wondering if anyone could help me/point me in the right direction of creating a custom domain that redirects to the invite of my discord server...

Essentially, I want to have a domain like BrennanIsCool.com redirect to discord.gg/myserver.

If anyone can help me I would greatly appreciate it.




Three.js - How do I change the edge colors of my SphereGeometry object?

This is the basic example from the Threejs documentation

function initSphere(){
       const geometry = new THREE.SphereGeometry( 150, 14, 14 );
       const material = new THREE.MeshBasicMaterial( {color: 0xFF0000, vertexColors: 0xFFFFFF} );
       const sphere = new THREE.Mesh( geometry, material );
       scene.add( sphere );
}

It creates a red sphere which is what I wanted, but I can't really see the sphere and it's edges because it just looks like a red circle. I was thinking that changing the edges to a white color would help make the effect I want, but I can't seem to know how to ask this question to solve it.

Can anyone help?




How to add notifications to website based on database change?

I am creating website for fastfood ordering. How can i alert a personal, that someone made an offer on website? I have created web where customer can make offer and other site for administration. Both connected to database. What i need is to give notification, alert any beep or anything for admin, when customer make offer and add row to table in database.

I found this enter image description here

but i dont know how to execute notification when database is changed. How to check it.




How to get IAB category for 1M websites

I am writing a publication about websites privacy. Quite a standard of such works [e.g., 1, 2] is to summarize categories of websites in the study, to either prove that the study is not biased, or the opposite that some privacy violations are skewed towards some categories.

I found that categories are usually IAB categories and there is a pleothora different APIs (BrandFetch, ClearBit, WebShrinker) offering resolution of website to this IAB category. However, these APIs seem to be meant for SEO analysts, with pricing fairly exceeding 1000$ for getting categories of Alexa/Tranco top 1M websites. They offer far more details (logo, Facebook link, and similar services for marketing analysis), while I want just an offline list of these IAB categories, at most business size and country would be useful.

The past works were not helpful. [1] refer to McAfee SmartFilter Internet Database (discontinued), [2] to SimilarWeb, another online service that does not seem to scale. Also Alexa lists by categories were discontinued in September 2020.

I feel like I am just not searching the right keywords. Maybe there is some plain text/csv file with all of this for top 1M websites that would solve all my issues. In parallel I am contacting SimilarWeb and WebShrinker if they would give me academic access for acknowledgement in the publication. Do you know source of such a list of top 1M websites with their IAB categories?

References

[1] Urban, Tobias, et al. "Beyond the front page: Measuring third party dynamics in the field." Proceedings of The Web Conference 2020. 2020. https://dl.acm.org/doi/pdf/10.1145/3366423.3380203

[2] Trevisan, Martino, et al. "4 years of EU cookie law: Results and lessons learned." Proceedings on Privacy Enhancing Technologies 2019.2 (2019): 126-145. https://content.sciendo.com/downloadpdf/journals/popets/2019/2/article-p126.xml




What are some reasons a long task like this would occur in a Chrome Devtools Performance tab?

Devtools Long Task

I am developing a website with a lot of updates and moving parts so I'm guessing it's related to that but I'm confused why it doesn't say it is updating layer tree or painting underneath it. Any reasons for a super long task that doesn't have a reason associated with it? Why would self be equal to 665ms?




Explain the difference between frontend and backend development?

If I use Node.js, Can I develop frontend and backend with Node? what will be the backend framework to be used?




i get "Cannot modify header information" warning when i try to refresh my page with php code [duplicate]

im trying to make messaging thing and how it works? it stores user input to txt file but after it, it refreshes the page to display latest input but i can make it refresh it because i get "cannot modify header information" warning :/ and all that i tried didn't work, i test every answer i get.

<?php
$ip = (isset($_SERVER["HTTP_CF_CONNECTING_IP"])?$_SERVER["HTTP_CF_CONNECTING_IP"]:$_SERVER['REMOTE_ADDR']); 
$user_agent = $_SERVER['HTTP_USER_AGENT'];

if(isset($_POST['send']))
{
$message=$_POST['message'];
$fp = fopen('messages.txt', 'a',1);
fwrite($fp, "Unknown: $message".PHP_EOL);
fclose($fp);

header("Refresh:0");
}

?> what did i do wrong? :( it works if i manually refresh page after sending message :/

[image of error][1] [1]: https://ift.tt/3t87ofy




Serve static content from Subdomain in coded Website

How to serve Static contents like images or PDF's and many other's from Subdomain on HTML website?




Background scale, keep position of drawn element in canvas

I use a system that combine a div background image and a canvas. This system let me appear the background like there is a light like this : enter image description here

I permit to the user to zoom in/out the background. But i need to keep every drawn element positions. Today i have this : enter image description here

After zoom in : enter image description here

The wall height and width are correctly resize but its position move with the scale.

For the code i have this for the background :

document.getElementById("background").style.transform = "translate("+backgroundTransform.x+"px,"+backgroundTransform.y+"px) scale("+backgroundTransform.zoom+","+backgroundTransform.zoom+")";

And this for the drawn element :

        this.x = function(x){ 
        if(x != undefined)
            this.position.x = x;

        return this.position.x + backgroundTransform.x;
    },
    this.y = function(y){ 
        if(y != undefined)
            this.position.y = y;
        return this.position.y + backgroundTransform.y;
    },
    this.width = function() {return this.baseWidth * this.globalZoom()};
    this.height = function() {return this.baseHeight * this.globalZoom()};

If you need any informations please let me know.

Thanks.




How to prevent Enter causing Dojo website to reload

I have a Dojo Dialog and within it there is a Form, TextBox and Button. When the Form is open and I type something in the TextBox and press Enter, the entire website reloads. How can I prevent this? Clicking the OK button works as expected. Is there a way I can disable the Enter behavior?

    var form = new Form();

    new TextBox({
        placeHolder: "enter value:"
    }).placeAt(form.containerNode);

    new Button({
      label: "OK", 
      'onClick': function () {
        console.log(`form value is: ${form._descendants[0].value}`)
        dia.hide();
      },
    }).placeAt(form.containerNode);

    var dia = new Dialog({
      content: form,
      title: "Save",
      style: "width: 300px",
  });

  form.startup();
  dia.show();



Adding Record to a Database Using a Button

I am making a website that stores videos. I would like to be able to have a button that adds a video to a table called Favourites which has the videoID, videoRef(youtube embed code) and the userID of the user that has clicked the button. I have tried a few things but for the most part I didn't know what I was doing. Code:

$user = $_SESSION["user"];

$GetUserID = mysqli_query($link, "SELECT userID FROM users WHERE username = '$user'");

$query=mysqli_query($link, "SELECT * FROM videos WHERE videoID = '$id'");

while ($data = mysqli_fetch_array($query) ){
    
    $GetVideoID = $data['videoID'];
    $GetVideoRef = $data['videoRef'];
    
}

if(isset($_POST['submit'])){
    
    $insert = mysqli_query($link,"INSERT INTO favourites (userID, videoID, videoRef) VALUES ('$GetUserID', '$GetVideoID', '$GetVideoRef')");

}

In my eyes this is the right logic but I'm quite new to websites. Any tips or solutions at all would make a big difference.




Use a prop function inside useEffect return: prop.function is not a function

I am currently trying to build an next.js app.

So what I want to do is passing a function to a component and call it with useEffect

I have the following component in order to change the props of the parents element. Therefore I pass the function from the parent like this:

<NumberInput name="height" update={manuelUpdate}></NumberInput>

The manuelUpdate function is a another props function from the actual parent:

const manuelUpdate = (name, value) => {
    props.update(name, value);
};

It works fine if I run the props.function with the onclick functions. However as soon as I try to use it in useEffect, it returns that the function is not a function. Maybe I am just thinking to complicated..

this is the component;

const NumberInput = ({ name, min = undefined, max = undefined, ...props }) => {
   
    const minInput = min !== undefined
        ? min
        : null;

    const maxInput = max !== undefined
        ? max
        : null;

    const [numb, setNumb] = useState(0);

    useEffect(() => {
        console.log(props.update)
    }, [numb]);

    const increaseNumb = () => {
        if (numb < maxInput || maxInput == null) {
            setNumb(numb + 1)
        }
        props.update(name, numb)
    };

    const decreaseNumb = () => {
        if (numb < minInput || minInput == null) {
            setNumb(numb - 1)
        }
    };

    const changeHandler = ({ e }) => {
        let n = parseInt(e.target.value)
        if (Number.isNaN(n)) {
            setNumb(numb)
        } else {
            setNumb(n)
        }
    }

    return (
        <div className={styles.def_number_input, styles.number_input}>
            <button onClick={decreaseNumb} className={styles.minus}></button>
            <input className={styles.quantity} name="quantity" value={numb} onChange={(e) => changeHandler({ e })}
                type="number" />
            <button onClick={increaseNumb} className={styles.plus}></button>
        </div>
    );
};

sorry in advance if my question is stupid or my code messy, I am still in the process of learning :D




PHP UNDEFINED VARIABLE on SELECT is there any better way to do this?

Is there any better way doing this without having an error if $personal_info['reg_civil_status'] and $_POST['reg_civil_status'] is empty? Because I'm having an "Undefined Variable Error"

                    <b>Civil Status: </b>
                    <select class="controler-1" name="reg_civil_status">
                        <?php 
                            foreach($civil_status_opt as $civil_status_opt){
                                if($personal_info['reg_civil_status'] == $civil_status_opt || $_POST['reg_civil_status'] == $civil_status_opt) {
                                    echo "<option selected='selected' value='$civil_status_opt'>$civil_status_opt</option>";
                                }
                                else {
                                    echo "<option value='$civil_status_opt'>$civil_status_opt</option>";
                                }
                            }
                        ?>
                    </select>



How to save data in json or any other file format for the further use by JavaScript

i am trying to make a tracker application, which include the daily entry inside the file. what i am trying to do is, I want to save the data on some external file (each time i update the entry), so i can easily access data from that file every-time I open the application.

For example : if I am tracking the height of the plant i am growing, so i will use excel to store date and the height of the plant on the respective day and every time i open excel old data is there as well as i can also update new entries in the excel.

Is there any way to do this kind of thing in JavaScript. I am new to this stuff hope you can help me! looking forward to your suggestions.




Importing useGLTF from '@react-three/drei/useGLTF' cause Module not found:

I have installed the react three fiber here's a dependences

"dependencies": {
"@react-three/drei": "^3.0.0",
"@testing-library/jest-dom": "^5.11.9",
"@testing-library/react": "^11.2.3",
"@testing-library/user-event": "^12.6.0",
"drei": "^2.2.21",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.1",
"react-spring": "^8.0.27",
"react-three-fiber": "^5.3.18",
"three": "^0.125.1",
"web-vitals": "^0.2.4"

},

and I run npm i drei

after it, I tried to import useGLTF

import { useGLTF } from '@react-three/drei/useGLTF'

and I got error

./src/Components/Three/Scene.js
Module not found: Can't resolve '@react-three/drei/useGLTF' in 'D:\coding\react\mincraft\src\Components\Three'

I decided to check the file manually inside @react-three/drei/useGLTF but there's no name such as useGLTF

do I need to run something else ?




jeudi 28 janvier 2021

The record cannot be inserted into the database after adding a record on the admin panel in django

models.py

from django.db import models

class NewsUnit(models.Model):
    catego = models.CharField(max_length=10,null=False)
    nickname = models.CharField(max_length=20,null=False)
    title = models.CharField(max_length=50,null=False)
    message = models.TextField(null=False)
    pubtime = models.DateTimeField(auto_now=True)
    enabled = models.BooleanField(default=False)
    press = models.IntegerField(default=0)

    def __str__(self):
        return self.title

views.py

from django.shortcuts import render
from newsapp import models
import math

# Create your views here.
page1 = 1

def index(request,pageindex=None):
    global page1
    pagesize = 8
    newsall = models.NewsUnit.objects.all().order_by('-id')
    datasize = len(newsall)
    totpage = math.ceil(datasize/pagesize)
    if pageindex == None:
        page1 = 1
        newsunits = models.NewsUnit.objects.filter(enabled=True).order_by('-id')[:pagesize]
    elif pageindex == '1':
        start = (page1-2)*pagesize
        if start >= 0:
            newsunits = models.NewsUnit.objects.filter(enabled=True).order_by('-id')[start:(start+pagesize)]
            page1 -= 1
    elif pageindex == '2':
        start = page1*pagesize
        if start < datasize:
            newsunits = models.NewsUnit.objects.filter(enabled=True).order_by('-id')[start:(start+pagesize)]
            page1 += 1
    elif pageindex == '3':
        start = (page1-1)*pagesize
        if start < datasize:
            newsunits = models.NewsUnit.objects.filter(enabled=True).order_by('-id')[start:(start+pagesize)]


    currentpage = page1
    return render(request,'index.html',locals())

def detail(request, detailid=None):
    unit = models.NewsUnit.objects.get(id=detailid)
    category = unit.catego
    title = unit.title
    pubtime = unit.pubtime
    nickname = unit.nickname
    message = unit.message
    unit.press += 1  
    unit.save()  
    
    return render(request, "detail.html", locals())

urls.py

from django.contrib import admin
from django.urls import path
from newsapp import views

urlpatterns = [
    path('',views.index),
    path('index/<pageindex>/',views.index),
    path('detail/<detailid>/',views.detail),
    path('admin/', admin.site.urls),
]

For this django project, I would like to insert the new record on the database list after adding a record from the admin panel. It works if I clicked save record in the admin panel but however the current new record cannot be added into the database on http://127.0.0.1:8000/index/1/. May I ask if I would like to have the record being inserted anything I am missing?




How do I choose suitable template for my website? [closed]

I am developing Makeup studio applications and trying to find out a suitable template. Can anyone suggest to me how to pick the right one?




Save form data to local machine for reuse

I have a php form that generates a work procedure for configuring routers. The form has about 20 fields. The process can span a couple of days and there can be a few configs going at the same time. I'm looking for a way to save the form data to the users machine and then have the ability to reopen the webpage and fill in the form with the locally stored data. I can use a save file /load file button, but ideally it would be great to have a "save" button that allows user to save a html (or other file that is associated with web browsers) that contains the completed form data. To load the "completed form", the users clicks the saved file and the web page opens with the form already filled in.




Github: Why does the new changes appeared on the file but not on the website?

I am trying to edit the content(e.g. change a few word) of a file from the repo below.(i am the co-owner). This owner use vue to create the website. When i added the changes, it is reflected on the file but not on the website. I try several methods: edit directly from git, edit on my local branch and pushed it to remote repo. etc... but it is not working.(FYI, i am a beginner at web development and git). Before vue is used, everything works fine

repo: https://github.com/busase/busase.org

git command:

git clone https://github.com/busase/busase.org.git

git add src/views/EBoard.vue

git commit -m 'new change'

git push -u origin master

result: Enumerating objects: 9, done. Counting objects: 100% (9/9), done. Delta compression using up to 4 threads Compressing objects: 100% (5/5), done. Writing objects: 100% (5/5), 528 bytes | 264.00 KiB/s, done. Total 5 (delta 3), reused 0 (delta 0), pack-reused 0 remote: Resolving deltas: 100% (3/3), completed with 3 local objects. remote: remote: GitHub found 3 vulnerabilities on busase/busase.org's default branch (1 high, 1 moderate, 1 low). To find out more, visit: remote: https://github.com/busase/busase.org/security/dependabot remote: To https://github.com/busase/busase.org.git 885fddb..f3ffadb master -> master Branch 'master' set up to track remote branch 'master' from 'origin'




I wan tot migrate my wordpress website to wix

I am facing some issue in my wordpress cms builder and want to migrate my website, how it will done and I want no any data break.

Here is the url




NextJS and Vercel CNAME for www domain

I have finished my web page in NextJS, pushed to GitHub and from there deployed the project via Vercel. I have set up custom domain DNS - added the required A record - and set in Vercel to use this domain. Everything works well, just a small thing going wrong. Whenever I try to access my domain like this example.com or https://example.com there are no issues, only problem appears when I try to access it like www.example.com - with the "www".

What would be the solution for this? When using ReactJS with GitHub pages I had to add CNAME into my domain DNS settings, do I have to do something similar now?

Thank you.




Gatsby soruce contentful body

Hey I'm using gatsby srouce contentful get my blog post from contenful. I'm trying to get the body as rich text or json but the only option graphql will let me use is raw which gives me back a bunch of objects and the text which I don't want.




Store files on google drive, for a website

Recently, I've wanted to make a website. My concept for it would be that I could store my videos and photos on my Google Drive, and access them from everywhere! Is there I way I could display photos from Google Drive and have them auto show up on a website (using google drives api)




my WordPress website got a 404 error without doing anything it says 404 not found openresty

I was just looking my website's page speed in google page speed insights and GTmetrix but when I tested again I got the error 404 NOT FOUND openresty I have done nothing to my website but I don't know how it encountered an error.




robots.txt with no user-agent specified?

A website I want to scrape has this robots.txt:

User-agent: Disallow: /wp-login.php
Disallow: /wp-admin/
Crawl-delay: 10

How do I interpret this when there seems to be no user-agent specified? Am I blanking on something obvious? Never seen something like this before.




How do I add API to a WordPress website to get real-time gold rates?

How do I add API to a WordPress website to get real-time gold rates? website




Jquery - Insert HTML if element doesnt exist within every instance of certain element on page

I need to Insert HTML after a class if an element doesn't exist within every instance of a certain class on the page. More elements can be loaded into the page from a pagination that doesn't reload the page, but takes around 2-3 seconds to load content. So I was thinking id need something that looped every few seconds just in case the user changed page and more elements were loaded.

After messing around for a while and searching over stackoverflow, I got the code to add the element on page load working but I wasn't able to make it dynamic enough to add the elements if the users changed page using the pagination.

I tried a set interval function that checked for the visibility of the element then used .after to add code after the element. I couldn't get this working at all.

setInterval(function(){ 
    if ($('.CHECKFOR').visible(false)) {
        $('.BEFORECLASS').after('<span class="INSERTEDCLASS"></span>');  
  } else {
    clearInterval(interval);
  } 
}, 1000);

Any help would be really appreciated. Thank you.




How can I prevent my fixed div from overlapping my other divs

I'm making a website for my world history class and I am attempting to make a heading for the website. Unfortunately, the heading overlaps the first paragraph. Is there any way I can fix this without changing the position? I need the position to be fixed. This is the html for the header:

<div id="menu">
<a href="#about">About</a>
<a href="#donatello">Donatello</a>
<a href="#michelangelo">Michelangelo</a>
<a href="">Martin Luther</a>
<a href="">Henry VIII</a>
<a href="">Mary Wollstonecraft</a>
<a href="">Francis Bacon</a>
<a href="">Isaac Newton</a>
<a href="">Galileo Galilei</a>
<a href="">Marquis de Lafayette</a>
</div>

This is the css:

#menu{
padding:30px;
background:#000;
border:5px solid #000000;
border-radius:0px;
position:fixed;
z-index:1;
right:0px;
left:0px;
top:0px;
text-align:center;
}

Thank you for the help.




Displaying all available images of several RSS Feeds on a php website

first I want to apologize for that extensive description of my issue. As silent reader here I already solved some issues in my current project, which I would describe as follows: RSS feeds (xml files) from several sources I want to display ordered by date descending on a website using php. This already works fine with that first script:

function array_sort_by_column( &$array, $column, $direction = SORT_DESC ) {
    $new_array = json_decode( json_encode( $array ), true );
    if ( 'date_created' === $column ) {
        $mapping_arr = array_map( 'strtotime', array_column( $new_array, $column ) );
        array_multisort( $mapping_arr, $direction );
    } else {
        $reference_array = array();
        foreach ( $array as $key => $row ) {
            $reference_array[ $key ] = $row[ $column ];
        }
        array_multisort( $reference_array, $direction, $array );
    }}

$files= array(
'https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml',
'http://feeds.foxnews.com/foxnews/latest',
'https://feeds.npr.org/1002/rss.xml',
'https://feeds.a.dj.com/rss/RSSWorldNews.xml',
'https://www.ft.com/?format=rss',
'https://rssfeeds.usatoday.com/UsatodaycomWorld-TopStories',
'https://www.washingtontimes.com/rss/headlines/news/',
'https://www.huffpost.com/section/world-news/feed',
'https://www.theguardian.com/international/rss',
'https://www.telegraph.co.uk/rss.xml',
'https://rss.politico.com/politicopulse.xml',
'https://lifehacker.com/rss', );

$dom = new DOMDocument('1.0', 'utf-8');
$dom->formatOutput = true;
$dom->preserveWhiteSpace = false;
$dom->appendChild($dom->createElement('channel'));

foreach ($files as $filename) {
  $addDom = new DOMDocument('1.0', 'utf-8');

  $addDom->load($filename);
  if ($addDom->documentElement) {
    foreach ($addDom->getElementsByTagName("item") as $node) {
      $dom->documentElement->appendChild(
        $dom->importNode($node, TRUE)
      );  }}}

$dom->save('fileout.xml', LIBXML_NOEMPTYTAG); // save as file
$xml=simplexml_load_file("fileout.xml");
$namespaces = $xml->getNamespaces(true);

$items = array();

foreach($xml->item as $item) {
    $items[] = array(
                     'title'             => (string)$item->title,
                     'link'          => (string)$item->link,
                     'description'           => (string)$item->description,
                     'pubDate'         => date('Y-m-d H:i:s',(strtotime((string)$item->pubDate))),
                     'img' => (string)$item->enclosure['url']
                    );
$unique = array_unique($items, SORT_REGULAR);             
}
array_sort_by_column($unique, 'pubDate');

echo '<div class="flex">';
for ($i = 0; $i < count($unique); $i++)
{
$str = ['http://','https://','www.','rss.','rssfeeds.'];
$rplc =['','','','',''];

$quelle = strtoupper(strstr(str_replace($str,$rplc, $unique[$i]['link']), '.', true));

  echo '<div id="artikel">';

if(isset($unique[$i]['img']) && !empty($unique[$i]['img'])) {
  echo '<a target="_blank" href="' . $unique[$i]['link'] . '"><img id="image" src="' . $unique[$i]['img'] . '" alt="' . $unique[$i]['title'] . '" title="' . $unique[$i]['title'] . '"></a>';
}
  echo '#' . $i . ' - <a id="title" target="_blank" title="' . $unique[$i]['title'] .'" href="' . $unique[$i]['link'] . '">' . $unique[$i]['title'] . '</a><br />';
  echo '<span id="quelle" class="' . $quelle . '">'. $quelle . '</span> <span id="pubDate">(' . date_format(new DateTime($unique[$i]['pubDate']), 'd. M Y H:i:s') . ')</span><br />';
  echo strip_tags($unique[$i]['description']) . '</div><br />';
}
echo '</div>';

Because I don't get that way all available images displayed that are included in this RSS-sources I managed to create a second script, which (hopefully) shows all file paths from all images. Some image paths may appear multiple times, but that's okay for me:

$files= array( /* see code snippet above */ );

...
// same code as above until 'foreach ($xml->item as $item){'...}

echo 'title: ' . $item->title . '<br />';
echo 'description: ' . strip_tags($item->description) . '<br />';
echo 'link: ' . $item->link . '<br />';
echo 'pubDate: ' . $item->pubDate . '<br />';

$imgOutput = $item->enclosure['url'];
if(!empty($imgOutput)) {
    echo 'image0: ' . $imgOutput . '<br />';
}

$bild1 = $item->children('http://search.yahoo.com/mrss/')->group->content;
if (is_array($bild1) || is_object($bild1)) {
    foreach($bild1 as $abc) {
          $imgOutput = $abc->attributes()['url'];
        echo 'imageA: ' . $imgOutput ."<br/>";
   }}

$bild2 = $item->children('http://search.yahoo.com/mrss/');
if (isset($bild2->content)) {
$imgOutput = $bild2->content->attributes()['url'];
$imgOutput_dscrptn = $bild2->description;
echo 'imageB: ' . $imgOutput .'<br />';
if(!empty($imgOutput_dscrptn)) {
echo 'imageB dscrptn: ' . $imgOutput_dscrptn . '<br />';
}}

    $bild3 = $item->children($namespaces['media']);
    foreach($bild3 as $xyz){
        $imgOutput = $xyz->attributes()->url;
        if(!empty($imgOutput)) {
        echo 'imageC: ' . $imgOutput . '<br />';
  }}

    $bild4 = $item->children('content', 'http://purl.org/rss/1.0/modules/content/');
    $html_string = $bild4->encoded;
    $dom = new DOMDocument();
if (!empty($bild4->encoded)) {
$dom->loadHTML(html_entity_decode($html_string));
$imgOutput = $dom->getElementsByTagName('img')->item(0);
if ($imgOutput != null) {
echo 'imageD: '.$imgOutput->getAttribute('src').PHP_EOL.'<br />';
}}
echo '<br />';
}

The point where I'm stuck right now is to combine those both scripts. My goal finally is a php script that displays my disered informations all entries fom the collected RSS Feeds ordered by date including all available images.

I already read this forum for hours to find a solution and I'm just an occasional programmer - so, please apologize my (noob) mistakes, my lack of understanding and that extensive description of my issue.

I already tried to find the empty (not set) 'img'-fields in my array to fill them with the matches from my second script and thought about creating a new array with completed information to display them ordered by date ... but both without success sof far.
It would be great if someone understand my issue and could find some time helping me to fix it ... and maybe, but not necessary, additionally to correct or improve my code. Thanks for reading.




Is any concern of PHP language with page speed? [closed]

One of my website pages is taking time to loading. Is there any issue of PHP language as I don't have deep knowledge of PHP. Is there any concern of page loading time with PHP language?




Nginx: Finding the location of specific folder

Using nginx on my website, am trying to exclude https://www.example.com/folder1 from basic auth. But the problem I don't know folder1 to which location block it belongs, so then I can exclude it.

Trying to find the folder name in the root directory (like below) doesn't work, since it return so many results with the same name in different directories.

find /root_dir/ -iname folder1 

And excluding just the folder name as location as below doesn't work as well:

   location ^~ /folder1/ {
        auth_basic      "off";
        allow all;
    }

Any specific way to find https://www.example.com/folder1 to which location block it belong?

Thanks!




Save multipart/form-Data image to database in asp.net web API

I have the following post method to receive id and image multipart/form-Data and save it in sql server database

[Route("api/save_cus")]
[HttpPost]
public async Task<IHttpActionResult> save_cus([FromBody] MultipartFileData CUS_PHOTO,int id)
{
 if (!Request.Content.IsMimeMultipartContent())
            {
               return Ok( "UnsupportedMediaType");
            }
    string root = HttpContext.Current.Server.MapPath("~/App_Data");
 if (Directory.Exists(root) == false) Directory.CreateDirectory(root);

           var provider = new MultipartFormDataStreamProvider(root);

           // Read the form data.
           await Request.Content.ReadAsMultipartAsync(provider);

                            
           // we take the first file here
           CUS_PHOTO = provider.FileData[0];

           // and the associated datas
           int myInteger;
 if (int.TryParse(provider.FormData["MyIntergerData"], out myInteger) == false)
          throw new ArgumentException("myInteger is missing or not valid.");
var fileContent = File.ReadAllBytes(CUS_PHOTO.LocalFileName);
var Customers = db.Customers.where(a=> a.id == id)
Customers.CUS_PHOTO =fileContent ;
db.SaveChangesAsync();
}

and me model look somthing like this

 public class CUSTOMERS
    {
        public int id { get; set; }

        public string CUS_NAME { get; set; }

        public byte[] CUS_PHOTO { get; set; }
}

then when I try to post this with postman I got UnsupportedMediaType can you help me please to know where is the problem and solve it.




service mumurai cant start , verify you have neccasery privileges

i dont know what happened but it keeps saying this error when i install

enter image description here




My website does not open after going from trial to payment on google cloud hosting

Good morning. I have the following problem: My account in the Google Cloud Hosting console was a test one, and when they sent me the notification to change it to a paid account, the via after a day, therefore Google stopped the services. A day later I put my credit card and problem solved. The strange thing is that 8 days have passed and my website does not open, and neither does my CPanel and WHM ip, call Billing and they tell me that everything is fine, to stop the machine and start it again, I did so, but, the site remains unopened. Any idea for a solution? I have not touched anything, this happened after the change from test to payment. Website: ItalianaSpA.com




Restful API Graphql with ExpressJs: Get document by Id not working

I am using graphql, express and react to build my app, and it is a job board app and I succeeded in query in the backend, this is how I did

query

now, I want to fetch it throughout API requests.js

const endpointURL = 'http://localhost:9000/graphql';

export async function loadJob(id) {
  const request = await fetch(endpointURL, {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
    },
    body: JSON.stringify({
      query: `
          query JobQuery($id: ID!) {
            job(id: $id) {
              id
              title
              company {
                id
                name
              }
              description
            }
          }
                `,
      variables: {id},
    }),
  });
  const requestBody = await request.json();
  console.log(requestBody, 'json');
  return requestBody.data.job;
}

and import it in other components jobDetail.js

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { loadJob } from './requests';

export class JobDetail extends Component {
  constructor(props) {
    super(props);
    this.state = {job: null};
  }

 async componentDidMount(){
  const {jobId} = this.props.match.params;
  const job = await loadJob(jobId);
  
  this.setState({job});
 }

  render() {
    const {job} = this.state;
    console.log(job, "job");
    return (
      <div>
        <h1 className="title">{job.title}</h1>
        <h2 className="subtitle">

      <Link to={`/companies/${job.company.id}`}>{job.company.name}</Link>
    </h2>
    <div className="box">{job.description}</div>
  </div>
);

} }

as you can see in file requests.js, i tried to print out request 's body but is not be called in the console, in file jobDetail.js, i did the same to print out job but it still null but the jobId is valid

Please show me how to solve it, thank you so much and have a good day