Friday, September 30, 2022

VLC not playing video on Kubuntu 22.10

Black screen instead video on VLC.

VLC not playing video, but only audio on Kubuntu 22.10

VLC do not show video, but black screen. Kaffeine plays video.

VLC => Ctrl+P => All => Video => Embedded video => uncheck // play video in separate window


Discover => PulseAudio Volume Control => Remove 

pavucontrol-qt-l10n/kinetic,kinetic 1.1.0-1 all
pavucontrol-qt/kinetic 1.1.0-1 amd64
pavucontrol/kinetic 5.0-2 amd64

Removal of pa solved problem with YouTube videos: not downloading video in Firefox, no sound in YouTube video . Also removal of pa solved problem with long video start freeze in Kaffeine. Glitches and other problems with sound also solved.

Thursday, September 29, 2022

Update, delete object in MongoDB

Update individual field in collection database object

db.collection.updateOne({title: "3 title"}, {$set:{counter: 3}})


Insert new string in collection database object

db.collection.update({}, {$set: {counter: 1}}, {$inc : {counter: 1}}, {upsert : true})


Delete string from collection database object

db.example.updateMany({},{"$unset":{"tags.words":1}})


Delete collection object by id

db.test_users.deleteOne( {"_id": ObjectId("4d512b45cc9374271b02ec4f")})


Delete all documents from collection

db.collection.deleteMany({})

https://www.mongodb.com/docs/mongodb-shell/crud/delete/


db.collection.update({ { _id : id }, { $pull: { "list": "four" } }});


db.collection.updateMany( { URL: { $regex: /Long("/ } }, [{ $set: { URL: { $replaceOne: { input: "$URL", find: "Long("", replacement: "" }  }}  }])


db.getCollection('collectionName').updateMany({$inc : {counter: 1}}, {upsert : true})


db.getCollection('collectionName').updateMany({counter: {$in : ["some title",  "some title 3"]}}, {$inc : {counter: 1}}, {upsert : true})


db.collection.aggregate([ { $group:{"_id":null, "data":{ $push:"$$ROOT" } } }, { $unwind:{ "path" : "$data", includeArrayIndex: 'counter' }  },  {  $addFields:{ "data.counter":{  $sum:["$counter", 1] }} },  {   $replaceRoot:{ "newRoot":"$data" } }])


For this, set “unique:true” i.e. the unique constraint and avoid inserting duplicates as in the below syntax

db.cards.ensureIndex({yourFieldName: 1}, {unique: true, dropDups: true})


https://www.mongodb.com/basics/create-database

https://stackoverflow.com/questions/57982189/is-there-a-way-to-add-a-counter-to-mongodb-query

https://www.tutorialspoint.com/mongodb/mongodb_autoincrement_sequence.htm

https://www.tutorialspoint.com/mongodb/mongodb_update_document.htm

https://stackoverflow.com/questions/61964449/mongodb-update-multiple-documents-solution-update-document-counter-or-insert

https://stackoverflow.com/questions/12589792/how-to-replace-substring-in-mongodb-document

https://stackoverflow.com/questions/57982189/is-there-a-way-to-add-a-counter-to-mongodb-query

https://stackoverflow.com/questions/29487351/how-to-convert-string-to-numerical-values-in-mongodb

https://stackoverflow.com/questions/29487351/how-to-convert-string-to-numerical-values-in-mongodb

https://stackoverflow.com/questions/8218484/mongodb-inserts-float-when-trying-to-insert-integer

https://database.guide/7-ways-to-count-documents-in-mongodb/

https://stackoverflow.com/questions/24985684/mongodb-show-all-contents-from-all-collections

https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field

https://stackoverflow.com/questions/1740023/mongodb-how-to-update-multiple-documents-with-a-single-command

https://www.w3resource.com/mongodb/mongodb-field-update-operator-$inc.php

https://stackoverflow.com/questions/71732533/add-number-field-in-project-mongodb?rq=1

https://stackoverflow.com/questions/66206713/trying-to-iterate-through-a-collection-of-mongodb-results-to-update-another-coll

https://www.baeldung.com/mongodb-upsert

Wednesday, September 28, 2022

Wrong icon on .directory file in home folder

grep ICONNAME -r --exclude-dir={media,proc,run,sys,var}

/home/user/.local/share/mime/

After changing application icon, changed icon appears on .directory file inside home folder.

Issue solved by removing wrong icon from /home/user/.local/share/mime/mime.cache and /home/user/.local/share/mime/icons => these files are empty on my system.

Also removed following files, which included wrong icon: home/user/.local/share/mime/application/x-desktop.xml and home/user/.local/share/mime/packages/application-x-desktop.xml

Tuesday, September 27, 2022

ndb Chrome DevTools for Node.js.

https://www.npmjs.com/package/ndb

sudo npm i ndb -g

"scripts": {
"start": "react-scripts start & nodemon node src/server.js",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"debug": "ndb server.js"
},

npm run debug

https://geshan.com.np/blog/2019/01/getting-started-with-debugging-nodejs-applications-with-ndb/

KDE Plasma desktop dependencies

sudo apt install libkf5notifyconfig-dev

sudo apt install libkf5runner-dev

libkf5activities-dev

libkf5activitiesastats-dev

libkf5qqc2desktopstyle-dev

kuserfeedback-dev

libkaccounts-dev

sudo apt install libkf5kdelibs4support-dev

sudo apt install libkf5idletime-dev

libkf5wayland-dev

libkf5people-dev

libkf5prison-dev

libkf5networkmanagerqt-dev

modemmanager-qt-dev

libopenconnect-dev

libqca-qt5-2-dev

grep command in Linux

grep string filename: Search for and display lines of filename that contain occurrences of string. 

grep string -r --exclude-dir={media,proc,sys} //  recursive search in  / excluding certain dirs

MongoDB and Node.js connection

https://zetcode.com/javascript/dotenv/

https://www.mongodb.com/languages/mern-stack-tutorial

https://attacomsian.com/blog/nodejs-mongodb-local-connection

https://stackoverflow.com/questions/68958221/mongoparseerror-options-usecreateindex-usefindandmodify-are-not-supported

https://mongoosejs.com/docs/connections.html

https://stackoverflow.com/questions/13190370/how-to-remove-duplicates-based-on-a-key-in-mongodb

https://stackoverflow.com/questions/62092955/how-do-i-remove-duplicates-in-mongodb-based-on-multiple-fields

Fetching data from API

https://javascript.info/json

https://learn.javascript.ru/fetch

https://blog.logrocket.com/modern-api-data-fetching-methods-react/

https://stackoverflow.com/questions/39019094/reactjs-get-json-object-data-from-an-url

const fetchData = fetch('api/v1/cards', {
method: 'GET',
dataType: 'json',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
})
.then((res) => res.json())
.then((obj) => {
// console.log(obj.data.cards);
// console.log(obj);
return Promise.resolve(obj.data.cards);
})
.catch((err) => {
console.log('Error getting data', err);
throw err;
});

console.log(fetchData);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve

https://stackoverflow.com/questions/33237200/fetch-response-json-gives-responsedata-undefined

https://stackoverflow.com/questions/51619534/fetch-data-from-mongoose-and-put-into-an-array

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

https://stackoverflow.com/questions/64611880/how-to-fetch-an-array-object-from-api-json-file

https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call

https://stackoverflow.com/questions/37533929/how-to-return-data-from-promise

https://www.digitalocean.com/community/tutorials/how-to-use-the-javascript-fetch-api-to-get-data

https://stackoverflow.com/questions/60791658/value-undefined-returned-from-fetch-promise

https://stackoverflow.com/questions/12460378/how-to-get-json-from-url-in-javascript

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

https://stackoverflow.com/questions/66655216/why-is-my-response-data-undefined-when-sending-a-fetch

https://stackoverflow.com/questions/72217657/fetch-json-data-from-url-and-write-in-a-file

https://www.freecodecamp.org/news/json-stringify-example-how-to-parse-a-json-object-with-javascript/

https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Fetching_data

Sunday, September 25, 2022

Access-Control-Allow-Origin not present: CORS policy

Access to fetch at 'http://127.0.0.1:3001/api/v1/posts' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

const posts = () => {

fetch('http://127.0.0.1:3001/api/v1/posts')
.then((r) => r.json()
.then((data) => ({ status: r.status, body: data })))
.then((obj) => console.log(obj));
};

Use 'api/v1/posts' instead 'http://127.0.0.1:3001/api/v1/posts'

If you want to enable CORS for all the request  => npm i cors --save-dev

const cors = require('cors');
app.use(cors())

https://stackabuse.com/handling-cors-with-node-js/

fetch(url, {
method: 'GET',
mode: 'no-cors', // set this mode
dataType: 'json',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
})

fetch_url = https://site.tech/api/tech

ping site.tech // get IP Adress and put it instred url

fetch_url = https://0.0.0.0/api/tech

Connect to local MongoDB database

// mongoose do not work globally => install into project

// needed to import mongoose in both cases

npm i mongoose

const mongoose = require('mongoose');

// with Mongoose

const dbUrl = 'mongodb://127.0.0.1:27017/_db';
(async () => {
try {
await mongoose
.connect(dbUrl, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then((con) => {
console.log(con.connection);
console.log(`MongoDB connected: ${dbUrl}`);
});
} catch (err) {
console.error(err);
}
})();

// with MongoClient

const dbUrl = 'mongodb://127.0.0.1:27017/_db';
const mongoClient = require('mongodb').MongoClient;
mongoClient.connect(
dbUrl,
{ useNewUrlParser: true, useUnifiedTopology: true },
(err, client) => {
if (err) {
return console.log(err);
}

// Specify database you want to access
const db = client.db('_db');

console.log(`MongoDB Connected: ${dbUrl}`);
}
);

DATABASE_LOCAL=mongodb://user:pass@127.0.0.1:27017/_db

https://mongoosejs.com/docs/connections.html

https://zellwk.com/blog/local-mongodb/

https://stackoverflow.com/questions/54573548/how-to-connect-to-mongodb-in-local-network-with-express-and-mongoose

MongoDB failed to unlink socket file

IGNORE THIS FUCKING ERROR AND START WORKING

User administration MongoDB Shell

sudo dpkg -i mongodb-mongosh_1.6.0_amd64.deb

mongosh

Current Mongosh Log ID: 632f7956d170bc14bd1fb47d
Connecting to:          mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0
Using MongoDB:          6.0.1
Using Mongosh:          1.6.0

For mongosh info see: https://docs.mongodb.com/mongodb-shell/


To help improve our products, anonymous usage data is collected and sent to MongoDB periodically (https://www.mongodb.com/leg
al/privacy-policy).
You can opt-out by running the disableTelemetry() command.

test>

////////////////////////////////////////////////////////

CREATE ADMIN USER

use admin

switched to db admin

db.createUser({user: "user", pwd: "user", roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]})

exit

////////////////////////////////////////////////////////

mongosh -u user -p --authenticationDatabase admin

show dbs

admin   132.00 KiB
config   12.00 KiB
local    88.00 KiB

////////////////////////////////////////////////////////

CREATE COLLECTION

use user

switched to db user

db.cards.insertOne({image: "http://127.0.0.1:3001/img/", link: "#1", title: "1 title", text: "1 Lorem ipsum dolor sit ns ectetur adipisicing elit. Similique architecto voluptatem dignissimos rerum doloribus vero dolore adipisci, maiores commodi u llam suscipit dolores cum. Vel, nemo!"})

{

 acknowledged: true,
 insertedId: ObjectId("633033768383cef7a400914f")
}

show collections

cards

db.cards.find()

[
 {
   _id: ObjectId("633033768383cef7a400914f"),
   image: 'http://127.0.0.1:3001/img/',
   link: '#',
   title: '11111111',
   text: '1Lorem ipsum dolor sit nsectetur adipisicing elit. Similique architecto voluptatem dignissimos rerum doloribus ver
o dolore adipisci, maiores commodi ullam suscipit dolores cum. Vel, nemo!'
 }
]

////////////////////////////////////////////////////////

DELETE USER

mongosh -u user -p --authenticationDatabase admin

show users

[]

CREATE NON-ADMIN USER

use user

db.createUser({user: "user", pwd: "user", roles: [ { role: "readWrite", db: "user" } ] })

{ ok: 1 }

db.dropUser("user", "comment")

{ ok: 1 }

db.dropUser("user", "writeConcern") // delete user

////////////////////////////////////////////////////////

https://stackoverflow.com/questions/23943651/mongodb-admin-user-not-authorized

use admin

db.grantRolesToUser("user", ["root"])

DELETE DATABASE

use user

switched to db user

db.dropDatabase()

{ ok: 1, dropped: 'user' }


show dbs //to list existing databases

use <dbname> //the <dbname> is the database you'd like to drop

db //should show <dbname> just to be sure I'm working with the right database

db.dropDatabase() //will delete the database & return { "dropped" : "<dbname>", "ok" : 1 }

MongoDB errors and troubleshooting

sudo systemctl daemon-reload // if failed to start mongod.service

sudo service mongod stop

sudo apt-get purge mongodb-org*

sudo rm -r /var/log/mongodb

sudo rm -r /var/lib/mongodb

sudo apt remove mongodb-org-server


sudo systemctl stop mongod

sudo systemctl start mongod

sudo systemctl status mongod


nmap -p- localhost | grep mongod

sudo ufw status


IGNORE "/tmp/mongodb-27017.sock","error"

"msg":"Failed to unlink socket file","attr":{"path":"/tmp/mongodb-27017.sock","error":"Operation not permitted"}

https://wiki.archlinux.org/title/MongoDB

https://mongoosejs.com/docs/migrating_to_6.html#no-more-deprecation-warning-options

https://mongoosejs.com/docs/plugins.html

Working with MongoDB Shell

Saturday, September 24, 2022

KDE Wallet Service Google Chrome problem

System Settings > KDE Wallet >  uncheck "Enable the KDE wallet subsystem"

ps aux | grep wallet

kill kwalletd5

Copying, moving or migrating Wine to new PC

Install fresh winehq on fresh Kubuntu. Copy following folders from backup. Do not overwrite, skip.

~/.local/share/applications/wine/Programs/

/home/user/.local/share/icons/

~/.wine/

Removing Wine completely from system after upgrade

sudo apt --purge remove wine wine64 libwine fonts-wine // no effect

rm -rfv $HOME/.wine // -v shows list of files and directories removed

rm -fv $HOME/.config/menus/applications-merged/*wine*

rm -rfv $HOME/.local/share/applications/wine

rm -fv $HOME/.local/share/desktop-directories/*wine*

rm -fv $HOME/.local/share/icons/*wine*


sudo apt remove winehq-devel

sudo apt remove winehq-stable

sudo apt remove winehq-staging


sudo apt remove libkwineffects14 

Reading package lists... Done

Building dependency tree... Done

Reading state information... Done

The following packages were automatically installed and are no longer required:

  aha appmenu-gtk-module-common appmenu-gtk3-module clinfo fonts-noto-unhinted ibus-data kwin-data

  libappmenu-gtk3-parser0 libcolorcorrect5 libgps30t64 libibus-1.0-5 libkf5people-data libkf5people5

  libkf5peoplebackend5 libkf5peoplewidgets5 libkfontinst5 libkfontinstui5 libksgrd9 libkwinglutils14

  libnotificationmanager1 libplasma-geolocation-interface5 libprocessui9 libqaccessibilityclient-qt5-0

  libqalculate-data libqalculate22t64 libscim8v5 libtaskmanager6 libweather-ion7 libxres1 plasma-firewall

  plasma-workspace-data qml-module-org-kde-kholidays qml-module-org-kde-pipewire qml-module-org-kde-solid

  vulkan-tools wayland-utils

Do you get blue screen with login, password and large keyboard?

Ctrl + Alt + F3, login and sudo apt reinstall plasma-desktop

Ctrl + Alt + F2 to return to KDE


wine public key is not available: NO_PUBKEY

GPG error: https://dl.winehq.org/wine-builds/ubuntu jammy InRelease:  The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 76F1A20FF987672F solution in the end:

List users and groups on Linux

cat /etc/passwd

less /etc/passwd

more /etc/passwd

https://devconnected.com/how-to-list-users-and-groups-on-linux/

File permissions changing on Kubuntu

sudo su - temporarily become the superuser

chmod - modify file access rights

chown - change file ownership

chgrp - change a file's group owner


cat /etc/group |cut -d: -f1 //  find all the groups available on your system

find /home -group user // find user named user

find /etc -group root // find group root
-rwxrw-r--
  • rwx (Owner) - The owner has read/write and execute permissions.

  • rw- (Group) - The group has read and write permissions.

  • r-- (Everyone else) - Everyone else has read permissions.

Running chmod -R 777 / as root will break your system.

KDE Plasma Shortcuts and System Settings

sudo nano /etc/default/grub => GRUB_CMDLINE_LINUX_DEFAULT="" // verbose boot mode

sudo update-grub

Shortcuts

Ctrl+Esc // "System Monitor" which is a slimmed down KSysGuard without the sensor tabs

Alt+F2, Alt+Space // KRunner

Ctrl+Alt+Del // Log Out

Meta+Alt+K // Switch to Next Keyboard Layout

Meta+L // Lock Session

Custom Shortcuts > Examples > Ctrl+Al+T // tick Examples and Run Konsole

Advanced Power Settings > Energy Saving > Screen Energy Saving

Graphic Tablet

System Settings > Workspace Behavior > Screen Locking > Lock screen automatically

Ctrl+Alt+F2 // switch to tty2 (terminal only interface) => login prompt up to Ctrl+Alt+F6

Alt+F1 // back to  regular GUI => tty

ps ax | grep -v grep | grep getty

  3819 tty2     Ss+    0:00 /sbin/agetty -o -p -- \u --noclear - linux
  3820 tty4     Ss+    0:00 /sbin/agetty -o -p -- \u --noclear - linux
  4146 tty3     Ss+    0:00 /sbin/agetty -o -p -- \u --noclear - linux
  4168 tty5     Ss+    0:00 /sbin/agetty -o -p -- \u --noclear - linux
  4180 tty6     Ss+    0:00 /sbin/agetty -o -p -- \u --noclear - linux

Ctrl+Alt+F7 // switch to tty7 (terminal only interface) => seventh virtual tty => empty

Ctrl+Alt+Del in ttys allows to reboot system without using hard reset.

https://askubuntu.com/questions/277517/what-does-ctrl-alt-f12-do

npm essentials for Linux

https://docs.npmjs.com/

node -v

sudo apt install npm

sudo npm i eslint express live-server nodemon node-sass npm-run-all -g

npm list

npm list -g // list globally installed packages

/usr/local/lib
├── eslint@8.24.0
├── express@4.18.1
├── live-server@1.2.2
├── node-sass@7.0.3
├── nodemon@2.0.20
├── npm-run-all@4.1.5
└── pm2@5.2.2

npm install package@1.0.0 // install npm package v 1.0.0

npm uninstall package

npm outdated

Install Node.js on Kubuntu Linux

Install apps without snap in Kubuntu

sudo apt install telegram-desktop

sudo add-apt-repository ppa:mozillateam/ppa // Install Firefox ESR via PPA

sudo apt install firefox-esr

sudo add-apt-repository --remove ppa:mozillateam/ppa // remove repository

Build and install Krusader from source

git clone --branch master 'https://github.com/KDE/krusader'

sudo apt install build-essential cmake make extra-cmake-modules git gettext zlib1g-dev libkf5archive-dev libkf5doctools-dev libkf5kio-dev libkf5parts-dev libkf5wallet-dev libkf5xmlgui-dev libkf5notifications-dev zip unzip rar unrar bzip2 bzip2-doc gzip libminizip1:amd64 libzip4:amd64 p7zip p7zip-full p7zip-rar kdiff3 krename kget

cd krusader

mkdir build && cd build

cmake ..

make -j12 // -j[N] depends on CPU cores

sudo make install

Reinstall Ubuntu without formatting and loosing data

NO ADVANTAGE IN DOING SO. Better backup boot etc home folders and fresh install. Make bootable flash drive from Linux ISO with rufus-3.4p or other software. Use dd write if getting error message. During install choose Manual and then / and swap partitions. Do not tick / to be formatted. Still it is good to delete some folders, BUT BACK UP boot etc home before any removal or deletion.

Choose minimal option to install Kubuntu and install necessary software later.

Kubuntu directories to backup in case of crash

boot // especially directory /boot/efi/EFI containing Boot Microsoft ubuntu

etc // storage system configuration files, executables required to boot the system, some log files

home // all user data

Thursday, September 22, 2022

Configuring MongoDB on Kubuntu 22.10

sudo dpkg -i libssl1.1_1.1.1f-1ubuntu2.16_amd64.deb

sudo dpkg -i mongodb-org-server_6.0.1_amd64.deb

mongod --version

sudo cp -r /var/lib/mongodb /var/lib/mongodb.bak

sudo chown -R mongodb:mongodb /var/lib/mongodb

sudo chown mongodb:mongodb /tmp/mongodb-27017.sock

ls -la

sudo ufw allow 27017


sudo systemctl start mongod

sudo systemctl status mongod

MongoDB install on Kubuntu 22.10

sudo apt update

apt list mongodb*

https://www.mongodb.com/try/download/community

sudo dpkg -i libssl1.1_1.1.1f-1ubuntu2.16_amd64.deb

sudo dpkg -i mongodb-org-server_6.0.1_amd64.deb

sudo dpkg -i mongodb-mongosh_1.6.0_amd64.deb

dpkg - package manager for Debian

dpkg --get-selections | grep -v deinstall | grep package-name

dpkg -i package-name.deb // install

sudo dpkg -r package-name // remove

sudo dpkg -P package-name // purge

dpkg -l package-name

https://manpages.ubuntu.com/manpages/kinetic/en/man1/dpkg.1.html

Route handler for POST request to add JSON item

Route handler for POST request to add JSON item => solution without database

app.post('/api/v1/cards', (req, res) => {
// console.log(req.body);
// solution to work without database
const newId = cards[cards.length - 1].id + 1;
const newCard = Object.assign({ id: newId }, req.body);

cards.push(newCard);

fs.writeFile(
`${__dirname}/data/card-data.json`,
JSON.stringify(cards),
(err) => {
res.status(201).json({
status: 'success',
data: { images: newCard },
});
}
); // use asynchronous writeFile
});

node

Install Posman API platform on Kubuntu

If Postman do not start after system reinstall, do this:

Extract Postman from postman-linux-x64.tar.gz to Downloads.

touch /home/user/.local/share/applications/Postman.desktop

////////////////////////

[Desktop Entry]

Encoding=UTF-8

Name=Postman

Exec=/home/user/Downloads/Postman/app/Postman %U

Icon=/home/user/Downloads/Postman/app/resources/app/assets/icon.png

Terminal=false

Type=Application

Categories=Development;

////////////////////////

Start Postman, skip creating account and go to File => Settings => Themes => select dark theme.

Ctrl++, Ctrl+- to increase user interface font size.

https://learning.postman.com/docs/getting-started/installation-and-updates/#installing-postman-on-linux

https://www.postman.com/downloads/?utm_source=postman-home

https://www.postman.com/

Wednesday, September 21, 2022

Check and listen open active ports on Unix

sudo lsof -i -P -n | grep LISTEN // list open ports

sudo netstat -tulpn | grep LISTEN

sudo ss -tulpn | grep LISTEN

sudo lsof -i:22 // see a specific port such as 22 with PID USER FD TYPE DEVICE NODE NAME

sudo nmap -sTU -O IP-address-Here

https://www.cyberciti.biz/faq/unix-linux-check-if-port-is-in-use-command/

sudo kill `sudo lsof -t -i:3000` // kill process on port 3000

https://stackoverflow.com/questions/9346211/how-to-kill-a-process-on-a-port-on-ubuntu

Node server backend for React App

cat /etc/hosts

http://localhost:3001/ === http://127.0.0.1:3001/

run react and node servers in parallel on UNIX => & as separator in react-app/package.json

"scripts": {
"start": "react-scripts start & nodemon node src/server.js",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},

npm init -y // if install new empty project

npm i dotenv // in existing project

npm i express // in existing project

sudo npm i nodemon -g // automatically restarts node server after change

npm list -g // global install === -g

/usr/local/lib

├── eslint@8.22.0

├── live-server@1.2.2

├── node-sass@7.0.1

├── nodemon@2.0.20

└── npm-run-all@4.1.5

https://stackoverflow.com/questions/30950032/how-can-i-run-multiple-npm-scripts-in-parallel

https://towardsdev.com/how-to-set-up-a-node-js-express-server-for-react-c19104568d12

https://www.freecodecamp.org/news/how-to-create-a-react-app-with-a-node-backend-the-complete-guide/

https://www.geeksforgeeks.org/how-to-connect-node-js-with-react-js/

gitignore not working or remove untracked files in git

git rm -r --cached .

git add .

git commit -m "untrack files contained in the .gitignore file"

git reset HEAD . // cancel all commits

git reset --hard

git clean -n

git clean -d -n

https://linuxize.com/post/how-to-remove-untracked-files-in-git/

Tuesday, September 20, 2022

Understanding what are props in React

// search-box.jsx

import './search-box.scss';

const SearchBox = (props) => (
<input
className='search'
type='search'
placeholder={props.placeholder}
onChange={props.onSearchChange}
/>
);

export default SearchBox;

// is same as above but worse in terms of code

import './search-box.scss';

export const SearchBox = ({ placeholder, onSearchChange }) => (
<input
className='search'
type='search'
placeholder={placeholder}
onChange={onSearchChange}
/>
);

export default SearchBox;

// App.js

<SearchBox
placeholder='Search...'
onSearchChange={this.onSearchChange}
/>

//

`value` prop to a form field without an `onChange` handler

You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.

<input value='' />

// change to defaultValue=''

Pass multiple parameters to onClick function

Function parameters are the names listed in the function's definition. Function arguments are the real values passed to the function. Parameters are initialized to the values of the arguments supplied.

If parameter is function (clickHandler in this case), pass argument as function => clickHandler();

import Button from './btn';
import { useNavigate } from 'react-router-dom';

export default function BtnNav(footer, btnText, btnLink, clickHandler) {
const navigate = useNavigate();
return (
<ul className={`${footer}__nav`}>
{btnText.map((el, index) => (
<li key={`${footer}-k-${index}`}>
<Button
id={`${footer}-btn-${index}`}
className={`${footer}-btn-${index}`}
onClick={() => {
navigate(btnLink[index]);
clickHandler();
}}

content={el}
/>
</li>
))}
</ul>
);
}

// to avoid message error clickHandler, pass empty function as onClick in necessary components

const falseClick = () => {};

https://blog.openreplay.com/3-ways-of-passing-multiple-parameters-to-the-onclick-handler-in-react

https://stackoverflow.com/questions/26069238/call-multiple-functions-onclick-reactjs

Monday, September 19, 2022

Make footer stick bottom with flex

index.html

<div class="wrapper" id="root"></div>

<div class="wrapper"> // content container

  <header></header>

  <main></main>

  <footer></footer>

</div>

main {
flex: 1;
}
.wrapper {
display: flex;
flex-direction: column;
justify-content: space-between;
height: 100vh;
}

https://stackoverflow.com/questions/40515142/how-to-make-a-sticky-footer-in-react

https://stackoverflow.com/questions/71478639/footer-not-sticking-to-the-bottom-of-the-page-in-react

https://stackoverflow.com/questions/10099422/flushing-footer-to-bottom-of-the-page-twitter-bootstrap

https://stackoverflow.com/questions/55541850/how-to-make-footer-stay-at-bottom-of-the-page-with-flex-box

tailwindcss and daysiui in React

https://tailwindcss.com/docs/guides/create-react-app

https://daisyui.com/docs/use/

index.css // add these lines

@tailwind base;
@tailwind components;
@tailwind utilities;

tailwind.config.js // paste into

/** @type {import('tailwindcss').Config} */
module.exports = {
content: ['./src/**/*.{html,js,jsx}'],
theme: {
extend: {},
},
plugins: [require('daisyui')],
};

package.json // consider to install

"devDependencies": {
"autoprefixer": "^10.4.8",
"node-sass": "^7.0.1",
"postcss": "^8.4.16",
"react-icons": "^4.4.0"
}

postcss.config.js

module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

//

Show changes in specific file using git

git show filename // will show the log message and textual diff

git status -s // list modified files

git diff filename

git log --follow filename // list commits only

git log --follow -p -- filename // entire history of file modifications

git blame <filename> // show who changed file

Sunday, September 18, 2022

Links, routes, page navigation in React

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';

https://www.loginradius.com/blog/engineering/react-router-basics/

App.js // do not toutch index.js


https://stackoverflow.com/questions/69832748/error-error-a-route-is-only-ever-to-be-used-as-the-child-of-routes-element

CSS buttons styles templates

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_buttons_animate2

https://freefrontend.com/css-button-click-effects/

Saturday, September 17, 2022

Import JavaScript script into React

/hooks/useScript.js

import { useEffect } from 'react';

const useScript = (url) => {
useEffect(() => {
const script = document.createElement('script');

script.src = url;
script.async = true;

document.body.appendChild(script);

return () => {
document.body.removeChild(script);
};
}, [url]);
};

export default useScript;

then

import useScript from '../hooks/useScript';

and call

useScript('/path/to/script.js');

https://stackoverflow.com/questions/34424845/adding-script-tag-to-react-jsx

https://stackoverflow.com/questions/38467574/import-javascript-file-and-call-functions-using-webpack-es6-reactjs

npm i react-helmet --save-dev

<Helmet>

<script src="/path/to/resource.js" type="text/javascript" />

<script>try{Typekit.load({ async: true });}catch(e){}</script>

</Helmet>

https://www.npmjs.com/package/react-helmet

https://www.geeksforgeeks.org/how-to-include-an-external-javascript-library-to-reactjs/

Thursday, September 15, 2022

shows VM214 react_devtools_backend.js:4082

console.log() shows VM214 react_devtools_backend.js:4082 in Chrome.

Console => Gear icon => Settings => Framework Ignone List // not best option

console.info(data) instead console.log(data) // not best option

Leave as it is...

Scroll methods and hooks in React

import React, { useRef, useEffect } from 'react';

const bottomRef = useRef(); // create Ref

useEffect(() => {    bottomRef.current.scrollIntoView({ behavior: 'smooth' });  }); // scroll bottom

https://stackoverflow.com/questions/37620694/how-to-scroll-to-bottom-in-react

window.scrollTo(0, document.body.scrollTop);

window.scrollTo(0, document.body.scrollHeight); // scroll to bottom

window.scrollTo({        top: 0,        behavior: 'smooth',      });

window.scrollTo(0, 0); // scroll to the top of the webpage

window.scrollTo(0, 780); // (x - horizontally, y - vertically)

el.scrollIntoView({ behavior: 'smooth' }

https://medium.com/@remoteupskill/different-ways-of-scrolling-to-a-dom-element-in-react-using-reacts-useref-hook-ec1afff82c43

https://bobbyhadz.com/blog/react-scroll-to-element-on-click

React.useEffect(() => {
window.scrollTo(0, 0);
}, []);

import { useEffect } from 'react'; // import to component

  useEffect(() => {    window.scrollTo(0, 0);  }, []); // inside component function before return

https://stackoverflow.com/questions/33188994/scroll-to-the-top-of-the-page-after-render-in-react-js

    document.getElementById('contact').scrollIntoView({ behavior: 'smooth' });

    const scrollDiv = document.getElementById('contact').offsetTop;

    window.scrollTo({ top: scrollDiv, behavior: 'smooth' });

https://stackoverflow.com/questions/5007530/how-do-i-scroll-to-an-element-using-javascript

document.getElementById("link3").tabIndex = -1;

node.setAttribute('tabindex', '-1')

node.focus()

node.removeAttribute('tabindex')

Getting, using, passing keys in React

If element is unchangable, use hard-coded key => <div key='custom_key'></div>

<div key={`${Object.keys(arr)}`}></div>

<div key={`item-${index}`}></div>

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys

State in React functional components

import { useState } from 'react'; // importing hook useState

function item() { 

const [showMore, setShowMore] = useState(false); // destructuring array from return of useState function => getting/creatin showMore name of piece of state and setShowMore function to update piece of state

// false => default piece of state in function useState(arg)

const handleClick = () => { setShowMore(true) }

const handleClick = () => { setShowMore((prev) => { return prev + 1 }) }

return ()

}

Wednesday, September 14, 2022

JavaScript Array map() method do not work

import data from './data.json';

const URL = `${data.resources.map((el, index) => el.url)}`;

// data +  "resources" + map(el, index) => element + "url"

data.json

{  "resources": [ {      "title": "",      "link": "",      "url": "https://site.com/folder"     } ] }

// add / at the end => /folder/ ===OR=== remove / from the end => /folder

{[...Array(n)].map((el, index) => (
<div key={index} className=''>{el}</div>
))}

// ...Array above can be used to repeat [0] element n times

// remove duplicates within a map function =>

<div class="tags">
  {posts.map(post =>
    [...new Set(post.frontmatter.tags)].map(tag => (
      <Link
        key={tag + `tag`}
        to={`/tags/${kebabCase(tag)}/`}
        className="tag is light"
      >
        {tag}
      </Link>
    ))
  )}
</div>

https://stackoverflow.com/questions/65512907/remove-duplicates-within-a-map-function