Setting quality in JIMP always gives the same result - jimp

When I set the quality for a PNG or JPEG in JIM (number from 1 - 99) I always get the same result. I don't see any difference in between quality or the final size. Here is my code:
function lossy(buffer, quality){
return new Promise(function(resolve, reject){
Jimp.read(buffer, function(err, image) {
let extension = image.getExtension();
if(image){
image.quality(quality)
.getBase64(extension, (err, data) => {
if(data){
resolve(data)
}
if(err){
console.log(err)
}
})
}
if(err){
reject(err)
}
});
})
}
Thank you for the advice!

Related

The method 'addItem' was called on null

I have a problem with that situation. Can you help me ? I'm taking this error message.
Exception has occurred.
NoSuchMethodError (NoSuchMethodError: The method 'addItem' was called on null.
Receiver: null
Tried calling: addItem("{\"name\":\"example\",\"isCompleted\":false,\"isArchived\":false}"))
I'm using addItem here;
floatingActionButton: FloatingActionButton(
backgroundColor: Color(0xff655c56),
onPressed: () async {
String itemName = await showDialog(
context: context,
builder: (BuildContext context) => ItemDialog());
if (itemName.isNotEmpty) {
var item =
Item(name: itemName, isCompleted: false, isArchived: false);
_itemService.addItem(item.toJson());
setState(() {});
}
},
And I define addItem here;
Future<List<Item>> fetchItems() async {
final response = await http.get(_serviceUrl);
if (response.statusCode == 200) {
Iterable items = json.decode(response.body);
return items.map((item) => Item.fromJson(item)).toList();
} else {
throw Exception('something went wrong');
}
}
Future<Item> addItem(String itemJson) async{
final response = await http.post(_serviceUrl, headers: {
'content-type':'application/json'
},body: itemJson);
if(response.statusCode==201){
Map item= json.decode(response.body);
return Item.fromJson(item);
}
else {
throw Exception('something went wrong');
}
}
}
HELPPPP!
fluter up to date btw
It seems that you try call addItem method on _itemService that not assigned to anything. But for more clear answer please share all codes relate this issue.

AWS Lamda/API Gateway Every Second Call Results in Internal Server Error

I'm need to 'Nodejs' and 'Serveless'. I've created a 'Serverless' API and deployed to AWS. Everything works as expected. The issue i have and i can't seem to find anything about this is, on every second call i get an internal server error. the first call is, returns data as expected.
I've deployed to AWS only in a dev stage. I'm wondering if there is some configuration i'm missing or something?
If you need the 'Serverless' config or code examples i can provide.
Thanks.
ANSWER
I think there was an issue with the DB call not returning data in time for the callback, therefore i was finding inconsistent results.
So basically what i did was create a Database class returning Promises like so...
'use strict';
const mysql = require('mysql');
/**
* Database
*/
class Database {
constructor(config) {
if (!this.dbConnection) {
console.log('connect to DB');
this.dbConnection = mysql.createPool(config);
this.dbConnection.on('connection', (connection) => {
console.info('Connection Made!');
});
}
}
query(sql, args) {
return new Promise((resolve, reject) => {
this.dbConnection.query(sql, args, (err, rows) => {
if (err) {
reject(err);
}
resolve(rows);
})
});
}
close() {
return new Promise((resolve, reject) => {
this.dbConnection.end((error) => {
if (error) {
reject(error);
}
resolve();
});
});
}
}
module.exports = Database;
So when i made my query there was a result ready for the callback.
'use strict';
const Database = require('./lib/Database');
const {successResponse, errorResponse} = require('./lib/response');
const CategoryResource = require('./resource/Category');
module.exports.list = (event, context, callback) => {
let sql = 'SELECT * FROM categories AS c WHERE c.company_id = ? AND c.parent_id IS NULL AND c.status = 1 LIMIT ?, ?;';
const company = parseInt(event.queryStringParameters.company);
let page = 1;
let limit = 20;
if (null != event.queryStringParameters) {
if ('page' in event.queryStringParameters) {
page = parseInt(event.queryStringParameters.page);
}
if ('limit' in event.queryStringParameters) {
limit = parseInt(event.queryStringParameters.limit);
}
}
let start = (page - 1) * limit;
if (isNaN(company)) {
callback(null, errorResponse(400, 'Company ID Required', 'Parameter company_id is required.', []));
return;
}
let Category = new Database();
let categoryResource = [];
Category
.query(sql, [company, start, limit])
.then(response => {
Category.close();
response.forEach((category) => {
categoryResource.push(CategoryResource(category));
});
callback(null, successResponse(200, {
"total": response.length,
"perPage": limit,
"currentPage": page,
"data": categoryResource
}));
})
.catch((error) => {
callback(null, errorResponse(error.code, error.sqlMessage, error.sql, {
code: error.errno,
field: error.sqlMessage,
message: error.sqlMessage
}));
Category.close();
});
};
I hope that helps anyone that may have run into the same issue.
If every other time you get an internal server error, that means your code is syntactically sound but has some sort of logic error. It's impossible to help without example code, but some of the more common errors I've seen that only sometimes occur can be:
race conditions (if you're doing parallel access of the same array, for example)
array access errors (length+1 instead of length-1, less-than-zero, or your iterators are jumping someplace in memory they shouldn't)
simply mentioning the wrong variable (putting an i instead of a j, for example)
Unfortunately, without specific examples, the best we can offer is wild speculation and personal experience. Have you tried looking at AWS's CloudWatch and what it says about your execution? There should be some errors logged in there too.
I think there was an issue with the DB call not returning data in time for the callback, therefore i was finding inconsistent results.
So basically what i did was create a Database class returning Promises like so...
'use strict';
const mysql = require('mysql');
/**
* Database
*/
class Database {
constructor(config) {
if (!this.dbConnection) {
console.log('connect to DB');
this.dbConnection = mysql.createPool(config);
this.dbConnection.on('connection', (connection) => {
console.info('Connection Made!');
});
}
}
query(sql, args) {
return new Promise((resolve, reject) => {
this.dbConnection.query(sql, args, (err, rows) => {
if (err) {
reject(err);
}
resolve(rows);
})
});
}
close() {
return new Promise((resolve, reject) => {
this.dbConnection.end((error) => {
if (error) {
reject(error);
}
resolve();
});
});
}
}
module.exports = Database;
So when i made my query there was a result ready for the callback.
'use strict';
const Database = require('./lib/Database');
const {successResponse, errorResponse} = require('./lib/response');
const CategoryResource = require('./resource/Category');
module.exports.list = (event, context, callback) => {
let sql = 'SELECT * FROM categories AS c WHERE c.company_id = ? AND c.parent_id IS NULL AND c.status = 1 LIMIT ?, ?;';
const company = parseInt(event.queryStringParameters.company);
let page = 1;
let limit = 20;
if (null != event.queryStringParameters) {
if ('page' in event.queryStringParameters) {
page = parseInt(event.queryStringParameters.page);
}
if ('limit' in event.queryStringParameters) {
limit = parseInt(event.queryStringParameters.limit);
}
}
let start = (page - 1) * limit;
if (isNaN(company)) {
callback(null, errorResponse(400, 'Company ID Required', 'Parameter company_id is required.', []));
return;
}
let Category = new Database();
let categoryResource = [];
Category
.query(sql, [company, start, limit])
.then(response => {
Category.close();
response.forEach((category) => {
categoryResource.push(CategoryResource(category));
});
callback(null, successResponse(200, {
"total": response.length,
"perPage": limit,
"currentPage": page,
"data": categoryResource
}));
})
.catch((error) => {
callback(null, errorResponse(error.code, error.sqlMessage, error.sql, {
code: error.errno,
field: error.sqlMessage,
message: error.sqlMessage
}));
Category.close();
});
};
I hope that helps anyone that may have run into the same issue.

Getting 'method not exist' error for PeristedModel.findOrCreate()

I am trying to use the method Model.findOrCreate in loopback using the mongodb connector
Country.findOrCreate({where: {iso2a: iso2a}}, {
"iso2a": iso2a,
"polygon": polygon
}, function(err, obj){
if(err){
console.log("Error finding and/or creating:", err);
}else{
obj.iso2a = iso2a;
obj.polygon = polygon;
obj.save(function(err, obj){
if(err){
console.log("Error saving");
}else{
console.log("Success saving");
}
});
}
});
But I keep getting the error that the function does not exists...
I guess I am doing something pretty basic wrong, ohh yeah and I checked that the model is "loaded".
Thanks.
I've read the docs here for PersistedModel.findOrCreate(where, data, callback). Now you see the first argument only accepts where clause, so you don't have to specify it explicitly. Here's the corrected code:
Country.findOrCreate(
{ iso2a: iso2a }, //adding where clause is not required.
{
"iso2a": iso2a,
"polygon": polygon
},
function(err, obj) {
if(err) {
console.log("Error finding and/or creating:", err);
} else {
obj.iso2a = iso2a;
obj.polygon = polygon;
obj.save(function(err, obj) {
if(err) {
console.log("Error saving");
} else {
console.log("Success saving");
}
});
}
});
Hope it solves your problem.

search a string in another file and replace it with another string in node js

I have searched enough for this matter and found most of the answers for java same problem but for me the problem arise in a node js program.
I want to search for,
.made-easy-theme{
color:black;
}
in a css file and replace its 'black' with another color which I recieve from the client side of the program. Here is what I have tried, I have tried 3 ways, but none of them are working.
First concept I have tried is,
var main = 'temp/' + userId + '/templates/' + appId + '/css/main.css';
var color = req.body.color;
function replaceThemecolor(color) {
fs.readFile(main, 'utf-8',
function (err, data) {
if (err) {
return console.log(err)
}
else {
var str = '.made-easy-theme{color:black;}';
if (str.search("black") != -1) {
var result = data.replace(/black/g, themecolor.color);
fs.writeFile(mainCss, result, 'utf-8', function (err) {
if (err) return console.log(err);
});
}
console.log(result);
}
});
}
});
The second concept I have tried is,
fs.readFile(main, 'utf-8',
function (err, data) {
if (err) {
return console.log(err)
}
else {
var ex = '.made-easy-theme{color:black;}'.includes('black');
if (ex == true) {
var result = data.replace(/black/g, color);
fs.writeFile(main, result, 'utf-8', function (err) {
if (err) return console.log(err);
});
console.log(result);
}
}
The third concept I have tried is,
else if (data.indexOf('.made-easy-theme{color:black;}') > 0) {
console.log(data);
var result = data.replace('black', themecolor.color);
fs.writeFile(mainCss, result, 'utf-8', function (err) {
if (err) return console.log(err);
});
};
Noone of these are working for me, please help to resolve this problem
I have found the answer
function replaceThemecolor(color) {
fs.readFile(main, 'utf-8',
function (err, data) {
var searchStr = ".made-easy-theme{color:black}";
var result = searchStr.replace(new RegExp('black', ''), color);
fs.writeFile(main, result, 'utf-8', function (err) {
if (err) return console.log(err);
});
});
}
but the problem is that it clears the full content of the css file and replace only the
.made-easy-theme{
color:black;
}
the other content which was in the css file is erased. I want to keep them and replce what I want to replace
Here is a way to do it, although not the best way. This code is coupled, makes bad use of string concatenation, doesn't do enough error checking and should probably use a file stream. But it will give you an idea.
Plus, it's just a dangerous thing to do.
var fs = require('fs');
var infile = 'test.css';
var outfile = 'temp.css';
var flag = false;
var color = 'green';
var out = '';
fs.open(infile, 'r', function(err, fd){
changeLine(fd);
});
function changeLine(fd){
var buf = new Buffer(1024);
buf.fill(0);
fs.read(fd, buf, 0, 1024, null, function(err, bytesRead, buffer){
if(bytesRead === 0){
writeCSS(out);
return;
}
var str = buffer.toString('utf8', 0, bytesRead);
if(/made-easy-theme/.exec(str)){
flag = true;
}
if (/color:/.exec(str) && flag){
str = str.replace('black', color);
flag = false;
}
out += str;
changeLine(fd);
});
}
function writeCSS(str){
fs.writeFile(outfile, str, function(err, written, buffer){
fs.rename(outfile, infile);
});
}

fs.writefile only execute in last function in node js

My program has three functions shown below,
var userId = req.userId;
var appId = req.body.appId;
var main = 'temp/' + userId + '/templates/' + appId + '/css/main.css';
var color = req.body.color;
var font = req.body.font;
var fontSize = req.body.fontSize;
replaceThemecolor(color);
replaceFont(font);
replaceFontSize(fontSize);
function replaceThemecolor(color) {
fs.readFile(main, 'utf-8', function (err, data) {
var regex =/(\.made-easy-themeColor\s*{[^}]*color\s*:\s*)([^\n;}]+)([\s*;}])/;
var result = data.replace(regex, "$1" + color + "$3");
console.log(color);
fs.writeFile(main, result, 'utf-8', function (err) {
if (err) return console.log(err);
});
});
}
function replaceFont(font) {
fs.readFile(main, 'utf-8', function (err, data) {
var regex =/(\.made-easy-themeFont\s*{[^}]*font-family\s*:\s*)([^\n;}]+)([\s*;}])/;
var result = data.replace(regex, "$1" + font + "$3");
console.log(font);
fs.writeFile(main, result, 'utf-8', function (err) {
if (err) return console.log(err);
});
console.log(result);
})
}
function replaceFontSize(fontSize) {
fs.readFile(main, 'utf-8', function (err, data) {
var regex =/(\.made-easy-themeFontSize\s*{[^}]*font-size\s*:\s*)([^\n;}]+)([\s*;}])/;
var result1 = data.replace(regex, "$1" + fontSize + "em" + "$3");
console.log(fontSize);
fs.writeFile(main, result1, 'utf-8', function (err) {
if (err) return console.log(err);
});
});
}
In here only the last function executes all the time, when I execute them seperately they work well, but the problem arise when all the funtions execute at once. Is it a problem with fs.writeFile function? I want to execute three of this functions together, is there a way to do this? All the functions here work well when they execute seperately.
Your file functions are async. You cannot run them at the same time because they will conflict and one will overwrite the changes of the other. You must run one, then when it finishes, run the other.
Or, even better, only read the file once, the process the data with all your changes, then write it once.
If you were going to run them sequentially, then you would need to pass a callback to each of your functions that is called when it is done so then you know when to start the next function.
But, I think a better solution is to pass an array of replace instructions and just process all of them on one read and write of the file. I will work on a code example for that.
Here's a way to do all the updates in one read/write of the file and uses promises to know when the operation is done:
function updateFile(filename, replacements) {
return new Promise(function(resolve, reject) {
fs.readFile(filename, 'utf-8', function(err, data) {
if (err) {
reject(err);
} else {
// now cycle through and do all the replacements
for (var i = 0; i < replacements.length; i++) {
data = data.replace(replacements[i].regex, replacements[i].replacer);
}
fs.writeFile(filename, data, 'utf-8', function(err) {
if (err) {
reject(err);
} else {
resolve();
}
});
}
});
});
}
updateFile(main, [{regex: /(\.made-easy-themeColor\s*{[^}]*color\s*:\s*)([^\n;}]+)([\s*;}])/, replacer: "$1" + color + "$3"},
{regex: /(\.made-easy-themeFont\s*{[^}]*font-family\s*:\s*)([^\n;}]+)([\s*;}])/, replacer: "$1" + font + "$3"},
{regex: /(\.made-easy-themeFontSize\s*{[^}]*font-size\s*:\s*)([^\n;}]+)([\s*;}])/, replacer: "$1" + fontSize + "em$3"}]).then(function() {
// update done successfully
}, function(err) {
// error
});
With some more work, you could probably abstract out just the keywords from the regular expressions too so you only need to pass in the keywords, but I'll leave that to another time.
And here's a simplified version:
function updateFile(filename, replacements) {
return new Promise(function(resolve, reject) {
fs.readFile(filename, 'utf-8', function(err, data) {
var regex, replaceStr;
if (err) {
reject(err);
} else {
// now cycle through and do all the replacements
for (var i = 0; i < replacements.length; i++) {
regex = new Regex("(\\" + replacements[i].rule + "\\s*{[^}]*" + replacements[i].target + "\\s*:\\s*)([^\\n;}]+)([\\s*;}])");
replaceStr = "$1" + replacements[i].replacer + "$3";
data = data.replace(regex, replaceStr);
}
fs.writeFile(filename, data, 'utf-8', function(err) {
if (err) {
reject(err);
} else {
resolve();
}
});
}
});
});
}
updateFile(main, [
{rule: ".made-easy-themeColor", target: "color", replacer: color},
{rule: ".made-easy-themeFont", target: "font-family", replacer: font},
{rule: ".made-easy-themeFontSize", target: "font-size", replacer: fontSize + "em"}
], function() {
// update done successfully
}, function(err) {
// error
});
And, you don't have to use the promise at all if you don't want to know when it's all done or be able to return errors (which I wouldn't recommend, but the code is simpler).
function updateFile(filename, replacements) {
fs.readFile(filename, 'utf-8', function(err, data) {
var regex, replaceStr;
if (err) { return; }
// now cycle through and do all the replacements
for (var i = 0; i < replacements.length; i++) {
regex = new Regex("(\\" + replacements[i].rule + "\\s*{[^}]*" + replacements[i].target + "\\s*:\\s*)([^\\n;}]+)([\\s*;}])");
replaceStr = "$1" + replacements[i].replacer + "$3";
data = data.replace(regex, replaceStr);
}
fs.writeFile(filename, data, 'utf-8');
});
}
updateFile(main, [
{rule: ".made-easy-themeColor", target: "color", replacer: color},
{rule: ".made-easy-themeFont", target: "font-family", replacer: font},
{rule: ".made-easy-themeFontSize", target: "font-size", replacer: fontSize + "em"}
], function() {
// update done successfully
}, function(err) {
// error
});
Notice how easy it would be to add more replacements. You simply add one more line to the array you pass updateFile().
Node.js is inherently asynchronous. As such, you're doing three read operations in quick succession, and then trying to write to a file that's already file locked, or at the very least, when it was read, did not contain the write changes. I'd use something more like async's series or waterfall methods to solve this.
var async = require("async");
var userId = req.userId;
var appId = req.body.appId;
var main = 'temp/' + userId + '/templates/' + appId + '/css/main.css';
var color = req.body.color;
var font = req.body.font;
var fontSize = req.body.fontSize;
async.series({
replaceThemecolor: function(callback) {
fs.readFile(main, 'utf-8', function(err, data) {
var regex = /(\.made-easy-themeColor\s*{[^}]*color\s*:\s*)([^\n;}]+)([\s*;}])/;
var result = data.replace(regex, "$1" + color + "$3");
console.log(color);
fs.writeFile(main, result, 'utf-8', function(err) {
callback(err);
});
});
},
replaceFont: function(callback) {
fs.readFile(main, 'utf-8', function(err, data) {
var regex = /(\.made-easy-themeFont\s*{[^}]*font-family\s*:\s*)([^\n;}]+)([\s*;}])/;
var result = data.replace(regex, "$1" + font + "$3");
console.log(font);
fs.writeFile(main, result, 'utf-8', function(err) {
callback(err);
});
})
},
replaceFontSize: function(callback) {
fs.readFile(main, 'utf-8', function(err, data) {
var regex = /(\.made-easy-themeFontSize\s*{[^}]*font-size\s*:\s*)([^\n;}]+)([\s*;}])/;
var result1 = data.replace(regex, "$1" + fontSize + "em" + "$3");
console.log(fontSize);
fs.writeFile(main, result1, 'utf-8', function(err) {
callback(err);
});
});
}
}, function(err, results) {
// results is empty, but now the operation is done.
});