Variable is not modified in this loop - no-unmodified-loop-condition from ESLint - vue.js

I have a project where ESLint throws this error from while loop. It does not make sence to me. Error says:
497:14 error 'from' is not modified in this loop no-unmodified-loop-condition
497:22 error 'to' is not modified in this loop no-unmodified-loop-condition
This is the code (look at while cycle):
mediaSettings: (state) => {
const timestamps = [];
const events = [];
state.media.forEach( medium => {
if( !medium.settings.dates ) return;
medium.settings.dates.forEach( dateRange => {
if( !dateRange.date_from || !dateRange.date_to ) return;
const from = new Date( dateRange.date_from );
const to = new Date( dateRange.date_to );
while ( from <= to ) {
if( timestamps.includes(from.getTime()) ) {
from.setDate( from.getDate() + 1 );
continue;
}
events.push({
date: new Date( from.getTime() ), // Need Date clone via new Date().
mediumId: medium.id,
});
from.setDate( from.getDate() + 1 );
};
});
});
return events;
}
What is that? Can somebody tell me plase how to fix it? It does not make sence. This is not an error.

I found clever solution on this page which disables ESLint for some block of code and also a specific ESLint rules. It looks like:
mediaSettings: (state) => {
const timestamps = [];
const events = [];
state.media.forEach( medium => {
if( !medium.settings.dates ) return;
medium.settings.dates.forEach( dateRange => {
if( !dateRange.date_from || !dateRange.date_to ) return;
const from = new Date( dateRange.date_from );
const to = new Date( dateRange.date_to );
/* eslint-disable no-unmodified-loop-condition */
while ( from <= to ) {
if( timestamps.includes(from.getTime()) ) {
from.setDate( from.getDate() + 1 );
continue;
}
events.push({
date: new Date( from.getTime() ), // Need Date clone via new Date().
mediumId: medium.id,
});
from.setDate( from.getDate() + 1 );
};
/* eslint-enable no-unmodified-loop-condition */
});
});
return events;
}

You wouldn't get this error if you are using reassignable variables like this:
...
let from = new Date(dateRange.date_from)
let to = new Date(dateRange.date_to)
while (from <= to) {
if (timestamps.includes(from.getTime())) {
from = from.setDate(from.getDate() + 1)
continue
}
events.push({
date: new Date(from.getTime()), // Need Date clone via new Date().
mediumId: medium.id,
})
from = from.setDate(from.getDate() + 1)
}
...

Related

Message event broken ( quick.db )

So i wanna get started with quick.db for my discord.js bot. I asked someone to help me solve this issue but they seem to be unable to. So if theres anyone here that can help could you tell me whats wrong with my code
module.exports = (client) => client.on('messageCreate', async (message) => {
const prefix = [].concat(client.config.prefix);
const ms = require('ms');
if (
message.author.bot ||
!message.guild ||
!prefix.some((x) => message.content.toLowerCase().startsWith(x))
)
return;
const [cmd, ...args] = message.content
.slice(prefix
.filter((x) => message.content.toLowerCase().startsWith(x))
.sort((a, b) => b.length - a.length)[0].length
)
.trim()
.split(/ +/g);
const command =
client.commands.get(cmd.toLowerCase()) ||
client.commands.find((c) =>
[].concat(c.aliases).includes(cmd.toLowerCase())
);
if (!command) return;
const cd = client.cd.get(`${message.author.id}_${command.name}`);
const left = cd - Date.now();
if (left > 0) {
const msg = await message.channel.send(
`You are on cooldown, please wait **${ms(left)}** to use this command again`
);
return setTimeout(() => msg.delete(), left);
}
if (command.cooldown)
client.cd.set(
`${message.author.id}_${command.name}`,
Date.now() + ms(command.cooldown)
);
try {
await command.run(client, message, args);
} catch (error) {
message.channel.send(error.toString());
}
}); 
the above code is the working one but whenever i use this
module.exports = (client) => client.on('messageCreate', async (message) => {
const ms = require('ms');
const { QuickDB } = require('quick.db');
const db = new QuickDB();
const prefix = db.get(`newprefix_${message.guild.id}`) || config.prefix
if (!prefix) return; 
if (!message.content.startsWith(prefix) || message.author.bot) return;
const [cmd, ...args] = message.content
.slice(prefix
.filter((x) => message.content.toLowerCase().startsWith(x))
.sort((a, b) => b.length - a.length)[0].length
)
.trim()
.split(/ +/g);
const command =
client.commands.get(cmd.toLowerCase()) ||
client.commands.find((c) =>
[].concat(c.aliases).includes(cmd.toLowerCase())
);
if (!command) return;
const cd = client.cd.get(`${message.author.id}_${command.name}`);
const left = cd - Date.now();
if (left > 0) {
const msg = await message.channel.send(
`You are on cooldown, please wait **${ms(left)}** to use this command again`
);
return setTimeout(() => msg.delete(), left);
}
if (command.cooldown)
client.cd.set(
`${message.author.id}_${command.name}`,
Date.now() + ms(command.cooldown)
);
try {
await command.run(client, message, args);
} catch (error) {
message.channel.send(error.toString());
}
});  
it doesn't work, meaning my bot doesn't reply

Get Level Information of non-revit model - NWC

I could not use the extension of level information(Autodesk.AEC.LevelsExtension) directly and I tried to use a workaround which is described below link.
https://forge.autodesk.com/blog/add-data-visualization-heatmaps-rooms-non-revit-model-part-i-nwc
However, it did not work for me. I tried it as in the below code. But, when i tried to print length of the dbIds it returns zero. So, I could not fill the levels. What can be the problem and why the layer searching is not worked?
async function findLevels(model) {
return new Promise((resolve, reject) => {
viewer.model.search(
'Layer',
(dbIds) => {
const levels = [];
const tree = viewer.model.getData().instanceTree;
console.log('Db Ids: ' + dbIds.length);
for( let i=0; i<dbIds.length; i++ ) {
const dbId = dbIds[i];
const name = tree.getNodeName( dbId );
if( name.includes( '<No level>' ) ) continue;
levelsGeo.push({
guid: dbId,
name,
dbId,
extension: {
buildingStory: true,
structure: false,
computationHeight: 0,
groundPlane: false,
hasAssociatedViewPlans: false,
}
});
}
resolve(levelsGeo);
},
reject,
['Icon']
);
});
}

Node.JS Oracle Patch Request not dynamic

I'm trying to dynamically make a patch request for oracle tables through Node.JS
Here's my setup:
In my router.js file I have this:
const express = require('express');
const router = new express.Router();
const employees = require('../controllers/employees.js');
const smiCats = require('../controllers/smi/smiCats.js');
const auth = require('../controllers/auth.js');
router.route('/login/:id?')
.post(auth.getToken);
router.route('/ams/:id?')
.get(auth.verifyToken, employees.get)
.post(auth.verifyToken, employees.post)
.put(auth.verifyToken, employees.put)
.delete(auth.verifyToken, employees.delete)
.patch(auth.verifyToken, employees.patch);
router.route('/smi/cats/:id?')
.get(auth.verifyToken, smiCats.get)
.post(auth.verifyToken, smiCats.post)
.put(auth.verifyToken, smiCats.put)
.patch(auth.verifyToken, smiCats.patch);
module.exports = router;
That then calls my controller that has my patch function & gets sanitized.
//sanitizer
function sanitizeCats(req) {
const cats = {
cat_desc: req.body.cat_desc,
msg_for: req.body.msg_for,
msg_user_owner: req.body.msg_user_owner || 0,
msg_realtor_owner: req.body.msg_realtor_owner || 0
};
return cats;
}
async function patch(req, res, next) {
try {
let category = sanitizeCats(req);
category.cat_id = parseInt(req.params.id, 10);
const success = await smiCats.patch(category);
if (success) {
res.status(204).end();
} else {
res.status(404).end();
}
} catch (err) {
next(err);
}
}
module.exports.patch = patch;
When that gets executed it calls my db_api module, which assembles the sql statement
(THE NEXT CODE SECTION IS WHERE MY QUESTION COMES FROM)
const database = require('../../services/database.js');
const oracledb = require('oracledb');
const patchSql =
`BEGIN
DECLARE
BEGIN
IF nvl(:cat_desc,'zzz') != 'zzz' THEN
UPDATE smi_contact_cats
SET cat_desc = :cat_desc
WHERE cat_id = :cat_id;
END IF;
IF nvl(:msg_for,'zzz') != 'zzz' THEN
UPDATE smi_contact_cats
SET msg_for = :msg_for
WHERE cat_id = :cat_id;
END IF;
IF nvl(:msg_user_owner,-1) > -1 THEN
UPDATE smi_contact_cats
SET msg_user_owner = :msg_user_owner
WHERE cat_id = :cat_id;
END IF;
IF nvl(:msg_realtor_owner,-1) > -1 THEN
UPDATE smi_contact_cats
SET msg_realtor_owner = :msg_realtor_owner
WHERE cat_id = :cat_id;
END IF;
:rowcount := sql%rowcount;
END;
END;`;
async function patch(cats) {
const category = Object.assign({}, cats);
//add binds
category.rowcount = {
dir: oracledb.BIND_OUT,
type: oracledb.NUMBER
};
const result = await database.simpleExecute(patchSql, category);
return result.outBinds.rowcount === 1;
}
module.exports.patch = patch;
This then calls the database function to actually execute & assemble the sql with the bind variables:
const oracledb = require('oracledb');
const dbConfig = require('../config/database.js');
async function initialize() {
const pool = await oracledb.createPool(dbConfig.beta);
}
module.exports.initialize = initialize;
async function close() {
await oracledb.getPool().close();
}
module.exports.close = close;
function simpleExecute(statement, binds = [], opts = {}) {
return new Promise(async (resolve, reject) => {
let conn;
opts.outFormat = oracledb.OBJECT;
opts.autoCommit = true;
try {
conn = await oracledb.getConnection();
const result = await conn.execute(statement, binds, opts);
resolve(result);
} catch (err) {
reject(err);
} finally {
if (conn) { // conn assignment worked, need to close
try {
await conn.close();
} catch (err) {
console.log(err);
}
}
}
});
}
module.exports.simpleExecute = simpleExecute;
So all of this works... but it's not dynamic enough for me to build our company api. How do I make a more dynamic patch request in Node.JS without having to type out every single column & put an nvl around it to check if it's there. As a side not if there's a better way to dynamically sanitize as well, I'm all ears, but the main question is on how to dynamically build the patch request better.
The current code is suboptimal in that is does one update per property. Here's a more dynamic solution...
Given the following:
create table smi_contact_cats (
cat_id number,
cat_desc varchar2(50),
msg_for varchar2(50),
msg_user_owner varchar2(50),
msg_realtor_owner varchar2(50)
);
insert into smi_contact_cats (
cat_id,
cat_desc,
msg_for,
msg_user_owner,
msg_realtor_owner
) values (
1,
'cat_desc orginal value',
'msg_for orginal value',
'msg_user_owner orginal value',
'msg_realtor_owner orginal value'
);
commit;
You can use logic like this. updatableColumns is the whitelist of columns that can be updated. Note that you can comment and uncomment some of the lines toward the bottom to test various input.
const oracledb = require('oracledb');
const config = require('./db-config.js');
async function patch(cat) {
let conn;
try {
const category = Object.assign({}, cat);
const categoryProps = Object.getOwnPropertyNames(category);
const updatableColumns = ['cat_desc', 'msg_for', 'msg_user_owner'];
// Validate that the pk was passed in
if (!categoryProps.includes('cat_id')) {
throw new Error('cat_id is required');
}
// Now remove the pk col from categoryProps
categoryProps.splice(categoryProps.indexOf('cat_id'), 1);
if (categoryProps.length === 0) {
throw new Error('At least one property must be specified');
}
let sql = 'update smi_contact_cats\nset ';
for (let propIdx = 0; propIdx < categoryProps.length; propIdx++) {
// Here's the whitelist check
if (!updatableColumns.includes(categoryProps[propIdx])) {
throw new Error('Invalid "update" column');
} else {
if (propIdx > 0 && propIdx < categoryProps.length) {
sql += ',\n ';
}
sql += categoryProps[propIdx] + ' = :' + categoryProps[propIdx];
}
}
sql += '\nwhere cat_id = :cat_id';
console.log('here is the sql', sql);
conn = await oracledb.getConnection(config);
const result = await conn.execute(
sql,
category,
{
autoCommit: true
}
);
if (result.rowsAffected && result.rowsAffected === 1) {
return category;
} else {
return null;
}
} catch (err) {
console.error(err);
} finally {
if (conn) {
try {
await conn.close();
} catch (err) {
console.error(err);
}
}
}
}
const patchObj = {
cat_id: 1
};
// Comment and uncomment the following to see various dynamic statements
patchObj.cat_desc = 'cat_desc value';
patchObj.msg_for = 'msg_for value';
patchObj.msg_user_owner = 'msg_user_owner value';
// Uncomment the following line to add a column that's not whitelisted
//patchObj.msg_realtor_owner = 'msg_realtor_owner value';
patch(patchObj)
.then(function(cat) {
console.log('Updated succeeded', cat);
})
.catch(function(err) {
console.log(err);
});

How to calculate age of users when they are entered their date of birth in react-native?

How to calculate age of users when they are entered their date of birth in react-native?
I want to check user is more then 18 year or not.When they are entered date of birth .
I am using react-native-datepicker for take user's date of birth.
I am trying to calculate age of user using below code but it not work properly .So please help me .How i can achieve this functionality.
calculate_age = (date) => {
var today = new Date();
var birthDate = new Date(date);
console.log("get bod-->",birthDate) // create a date object directly from `dob1` argument
var age_now = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age_now--;
}
console.log('my age', age_now);
return age_now;
}
onDateChange = (date) => {
this.setState({ date: date }, () => {
console.log(date)
if (this.calculate_age(date) < 18) {
alert("You Are Not Eligable")
} else {
}
})
}
Using 'npm i moment' package.I solved this problem.
onDateChange = (date) => {
this.setState({ date: date }, () => {
if (this.calculate_age(Moment(date,"DD-MM-YYYY").format("YYYY-MM-DD")) <= 17 ) {
this.setState({errmsg:"You must be atleast 18 years of old to join."})
}else{
this.setState({errmsg:" "})
}
})
}
You can make a custom function like this:
const getAge = (dateString)=>{
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
console.log('age: ' + getAge("1980/08/10"));

How I can set expiration date for AsyncStorage - react native

I am using react native async storage it works good but in some cases, I have to set an expiration date for data and refresh my storage I checked
AsyncStorage documentation but there are no options to set expire after a specific time.
only available options are:-
AsyncStorage.removeItem
AsyncStorage really only handles storage and nothing beyond that.
If you want to set an expiration, just put a key in your data for access date and set it to new Date(). Then, when you pull data, do a date check on the expiration key based on when it should expire.
first, I am storing objects, not strings so my solution will be based on object case if anyone uses strings he can append expireAt the object key then he will extract expire date and compare it with the current date
my solution:-
/**
*
* #param urlAsKey
* #param expireInMinutes
* #returns {Promise.<*>}
*/
async getCachedUrlContent(urlAsKey, expireInMinutes = 60) {
let data = null;
await AsyncStorage.getItem(urlAsKey, async (err, value) => {
data = (JSON.parse(value));
// there is data in cache && cache is expired
if (data !== null && data['expireAt'] &&
new Date(data.expireAt) < (new Date())) {
//clear cache
AsyncStorage.removeItem(urlAsKey);
//update res to be null
data = null;
} else {
console.log('read data from cache ');
}
});
//update cache + set expire at date
if (data === null) {
console.log('cache new Date ');
//fetch data
data = fetch(urlAsKey).then((response) => response.json())
.then(apiRes => {
//set expire at
apiRes.expireAt = this.getExpireDate(expireInMinutes);
//stringify object
const objectToStore = JSON.stringify(apiRes);
//store object
AsyncStorage.setItem(urlAsKey, objectToStore);
console.log(apiRes.expireAt);
return apiRes;
});
}
return data;
},
/**
*
* #param expireInMinutes
* #returns {Date}
*/
getExpireDate(expireInMinutes) {
const now = new Date();
let expireTime = new Date(now);
expireTime.setMinutes(now.getMinutes() + expireInMinutes);
return expireTime;
}
You can use this also, improvement from Ahmed Farag Mostafa answers
import AsyncStorage from "#react-native-async-storage/async-storage";
export default class ExpireStorage {
static async getItem(key) {
let data = await AsyncStorage.getItem(key);
data = JSON.parse(data);
if (
data !== null &&
data.expireAt &&
new Date(data.expireAt) < new Date()
) {
await AsyncStorage.removeItem(key);
data = null;
}
return data?.value;
}
static async setItem(key, value, expireInMinutes) {
const data = { value };
if (expireInMinutes) {
const expireAt = this.getExpireDate(expireInMinutes);
data.expireAt = expireAt;
} else {
const expireAt = JSON.parse(await AsyncStorage.getItem(key))?.expireAt;
if (expireAt) {
data.expireAt = expireAt;
} else {
return;
}
}
const objectToStore = JSON.stringify(data);
return AsyncStorage.setItem(key, objectToStore);
}
static async removeItem(key) {
return AsyncStorage.removeItem(key);
}
static getExpireDate(expireInMinutes) {
const now = new Date();
const expireTime = new Date(now);
expireTime.setMinutes(now.getMinutes() + expireInMinutes);
return expireTime;
}
}