I can't figure why my code doesn't wait for the invocation to return a value.
Tried making it into a separate function, still the same error.
It looks like I just can't access .done function.
Main Code
JS:
var connection = new signalR.HubConnectionBuilder().withUrl("/rouletteHub").build();
function HandleBet(event, color){
var amount = parseInt(document.getElementById("amount").value);
var actualPoints = 0;
connection.invoke("GetPtsFromServer").then(function (pts) {
actualPoints = parseInt(pts);
})
console.log(actualPoints);
if (isNaN(amount)){
ErrorNotANumber();
return;
}
if (amount < 0){
ErrorNegativeNumber();
return;
}
//console.log(amount);
//console.log(actualPoints)
if (amount > actualPoints){
NotEnoughPoints();
return;
}
if (amount > 0){
connection.invoke("PlaceBet", color.toString(), amount).then(function () {
PlacedBetSuccess(GetColor2(color), amount);
}, function (err) {
PlacedBetError();
})
}
event.preventDefault();
}
C#:
public int? GetPtsFromServer()
{
if (Context.User?.Identity != null && !Context.User.Identity.IsAuthenticated) return null;
if (Context.User == null) return null;
var dcId = Context.User.Claims.FirstOrDefault(c => c.Type == "urn:discord:id")?.Value;
return DataWrapper.HelpForTypes.GetPts(Convert.ToUInt64(dcId));
}
When using .done instead of .then it throws an error
Console:
Uncaught TypeError: connection.invoke(...).done is not a function
at HandleBet (Roulette:420)
at HTMLButtonElement.<anonymous> (Roulette:469)
JS:
connection.invoke("GetPtsFromServer").done(function (pts) {
actualPoints = parseInt(pts);
});
Fixed by making HandleBet async and inserting await before connection.invoke.
I am setting up a TF2 trading bot that can price check. I get an error when defining a boolean for if it is priced in keys or not.
I have tried just replacing isKeys with data[baseName].prices[qualityId.toString()].Tradable[craftable[isCraftable.toString()][0].currency == "keys" in the if statement but get an error for the closing bracket in the if statement.
var data = {
};
var currencies = {
};
requestify.get('https://backpack.tf/api/IGetPrices/v4?raw=1&since=0&key=5cf17c256780725011449df2')
.then(function(response) {
data = response.getBody().response.items;
console.log(data["Australium Tomislav"].prices["11"].Tradable.Craftable);
}
);
requestify.get('https://backpack.tf/api/IGetCurrencies/v1?key=5cf17c256780725011449df2')
.then(function(response) {
currencies = response.getBody().response.currencies;
}
);
function toRef(keys, high) {
if (high) {
if (currencies.keys.price.value_high != undefined){
return currencies.keys.price.value_high * keys
} else {
return currencies.keys.price.value * keys
}
} else {
return currencies.keys.price.value * keys
}
}
function getPrice(item, high) {
var name = item.market_name;
var quality = item.tags[0].name;
var baseName = name.replace(quality + " ", "");
var qualityId = itemQualities[quality];
var isCraftable = true;
var isKeys = data[baseName].prices[qualityId.toString()].Tradable[craftable[isCraftable.toString()][0].currency == "keys"; // Error here
for (i = 0;i < item.description.length;i++) {
if (item.description[i].value == '( Not Usable in Crafting )') {
isCraftable = false;
}
}
if (high) {
if (isKeys) {
return toRef(data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value_high], true);
} else {
return data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value_high];
}
} else {
if (isKeys) {
return toRef(data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value], false);
} else {
return data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value];
}
}
}
`
G:\BOT\bot.js:106
var isKeys = data[baseName].prices[qualityId.toString()].Tradable[craftable[isCraftable.toString()][0].currency == "keys";
^
SyntaxError: Unexpected token ;
is the error I get
TL;DR: You are missing a ] on the erred line. And you have extra ] on the below if(high){...} lines.
You are missing a square bracket ] in the line,
var isKeys = ... as the other answers suggest.
Now, we don't know the data structure so it can be,
data[baseName]
.prices[qualityId.toString()]
.Tradable[craftable[isCraftable.toString()][0].currency*]*
or
data[baseName]
.prices[qualityId.toString()]
.Tradable[craftable[isCraftable.toString()][0]*]*.currency
But Also,
You have extra Square braces on the lines,
if (high) {
if (isKeys) {
/*--here>>*/return toRef(data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value_high, true);
} else {
/*--here>>*/return data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value_high;
}
} else {
if (isKeys) {
/*--here>>*/ return toRef(data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value, false);
} else {
/*--here>>*/return data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value;
}
}
Again we don't know the exact data structure.
You're missing a square bracket for Tradable
var isKeys = data[baseName].prices[qualityId.toString()].Tradable[craftable[isCraftable.toString()]][0].currency == "keys";
In that line a square-bracket-close (]) is missing.
Your line is:
var isKeys = data[baseName].prices[qualityId.toString()].Tradable[craftable[isCraftable.toString()][0].currency == "keys"; // Error here
You open a bracket at .Tradable[ but it isn't closed until the end of that line.
The compiler expects a ] but finds a ;.
I am not familar with the API you are using but I suppose the following would fix the error:
var isKeys = data[baseName].prices[qualityId.toString()].Tradable[craftable[isCraftable.toString()][0].currency == "keys"]; // << Notice the bracket before your semicolon
I have the current code in PasswordSrvc:
doResetPassword: function (passwordCommand) {
var response = {data : {errors: ""}};
if (passwordCommand.password !== passwordCommand.passwordConfirm) {
response.data.errors = response.data.errors.concat("Passwords do not match!\n");
}
if (passwordCommand.password.length < 6 || passwordCommand.passwordConfirm.length < 6) {
response.data.errors = response.data.errors.concat("Password too short!\n")
}
if (response.data.errors !== "") {
return response;
}
else {
passwordCommand.token = $location.search().token;
return $http.put(apiUrl + 'password/doResetPassword', passwordCommand);
}
}
which is called from:
PasswordSrvc.doResetPassword($scope.passwordCommand).then(function (response){
console.log(JSON.stringify(response));
if (response.data.errors) {
$scope.errorMessage = response.data.errors;
} else {
$location.path('/authority/passwordChanged');
}
});
The problem is that I always get the response as being "undefined" if a validation error occurs and I end up returning from:
if (response.data.errors !== "") {
return response;
}
Why does this happen? How can it be fixed?
I mean, when returning from
else {
passwordCommand.token = $location.search().token;
return $http.put(apiUrl + 'password/doResetPassword', passwordCommand);
}
it works fine and I get whatever I want, but why doesn't it work for the "manually created response"?
Thanks
Hello I'm trying to create an array of errors, and display them at once. Something like this.
if (!first_name) {
var error[] = "Заполните Фамилию";
$('#first_name').addClass('error');
} else {
$('#first_name').removeClass('error');
}
if (!second_name) {
var error[] = 'Заполните Имя';
$('#second_name').addClass('error');
} else {
$('#second_name').removeClass('error');
}
if (!last_name) {
var error[] = 'Заполните Отчество';
$('#last_name').addClass('error');
} else {
$('#last_name').removeClass('error');
}
if (!course) {
var error[] = 'Заполните Курс';
$('#course').addClass('error');
} else {
$('#course').removeClass('error');
}
if (!math && !programming && !english && !history) {
var error[] = 'Заполните хотябы один предмет';
$('#math,#programming,#english,#history').addClass('error');
} else {
$('#math,#programming,#english,#history').removeClass('error');
}
and then
if(error.length > 0) {
$(".errors").html(error);
}
But i'm getting an error Uncaught SyntaxError: Unexpected token ]
What am i doing wrong?
Two main problems - the error array was being repeatedly and incorrectly declared, and the display of the resulting array was being handled incorrectly. Here's a fix for both problems....
var error = []; // initialise empty array
if (!first_name) {
error.push( "Заполните Фамилию");
$('#first_name').addClass('error');
} else {
$('#first_name').removeClass('error');
}
if (!second_name) {
error.push( 'Заполните Имя');
$('#second_name').addClass('error');
} else {
$('#second_name').removeClass('error');
}
if (!last_name) {
error.push('Заполните Отчество');
$('#last_name').addClass('error');
} else {
$('#last_name').removeClass('error');
}
if (!course) {
error.push( 'Заполните Курс');
$('#course').addClass('error');
} else {
$('#course').removeClass('error');
}
if (!math && !programming && !english && !history) {
error.push( 'Заполните хотябы один предмет');
$('#math,#programming,#english,#history').addClass('error');
} else {
$('#math,#programming,#english,#history').removeClass('error');
}
// you will need to join the elements together somehow before displaying them
if (error.length > 0) {
var data = error.join( '<br />');
$(".errors").html(data);
}
You might also want to look at using the toggleClass function instead of add/remove, but that's up to you
All of these lines contain syntax errors:
var error[] = ...
because error[] is not a valid JavaScript identifier. Remove the []s. The closest valid variable name would be error instead of error[].
This kind of error is made painfully evident when you run your code through a JavaScript linter tool.
You are confusing JavaScript with PHP.
This is incorrect way to declare an array:
var error[] = 'Заполните Отчество';
rather:
var error = new Array();
or
var error = [];
To append values into an array using javascript :
var error = [];
error.push('Error 1');
error.push('Error 2');
Then, to display them :
$('.errors').html(
error.join('<br/>') // "Error 1<br/>Error 2"
);
Doc : push, join.
You can display all error message at once like that
var error=''
if (!first_name) {
error += "Заполните Фамилию.<br />";
$('#first_name').addClass('error');
} else {
$('#first_name').removeClass('error');
}
if (!second_name) {
error += 'Заполните Имя<br />';
$('#second_name').addClass('error');
} else {
$('#second_name').removeClass('error');
}
if (!last_name) {
error += 'Заполните Отчество<br />';
$('#last_name').addClass('error');
} else {
$('#last_name').removeClass('error');
}
if (!course) {
error += 'Заполните Курс<br />';
$('#course').addClass('error');
} else {
$('#course').removeClass('error');
}
if (!math && !programming && !english && !history) {
error +='Заполните хотябы один предмет<br />';
$('#math,#programming,#english,#history').addClass('error');
} else {
$('#math,#programming,#english,#history').removeClass('error');
}
if (error != '') {
$(".errors").html(error);
return false;
}
error is a one variable where i stored all the error and display at once on the screen.
I have searched high and low on the Interwebs, and found some really awesome JS code editors with syntax highlighting and indentation and more... but none seem to have support for Smarty template tags yet.
A new Smarty mode for CodeMirror would be the best, but I'll use a different editor if I need to.
I did find this blog post... but it is VERY simple, and I would like to still support mixed HTML/CSS/JS highlighting, like the PHP mode for CodeMirror.
I just thought I would check with the SO hive mind before embarking on rolling my own CodeMirror mode. If I do make a new mode (and get anywhere with it) I'll post it here.
Thanks!
I made some tries to get a mixed mode with smarty and although my work is not perfect, so far it works well enough for me. I started from de htmlmixedmode to add a smarty mode :
CodeMirror.defineMode("smartymixed", function(config, parserConfig) {
var htmlMode = CodeMirror.getMode(config, {name: "xml", htmlMode: true});
var smartyMode = CodeMirror.getMode(config, "smarty");
var jsMode = CodeMirror.getMode(config, "javascript");
var cssMode = CodeMirror.getMode(config, "css");
function html(stream, state) {
var style = htmlMode.token(stream, state.htmlState);
if (style == "tag" && stream.current() == ">" && state.htmlState.context) {
if (/^script$/i.test(state.htmlState.context.tagName)) {
state.token = javascript;
state.localState = jsMode.startState(htmlMode.indent(state.htmlState, ""));
state.mode = "javascript";
}
else if (/^style$/i.test(state.htmlState.context.tagName)) {
state.token = css;
state.localState = cssMode.startState(htmlMode.indent(state.htmlState, ""));
state.mode = "css";
}
}
return style;
}
function maybeBackup(stream, pat, style) {
var cur = stream.current();
var close = cur.search(pat);
if (close > -1) stream.backUp(cur.length - close);
return style;
}
function javascript(stream, state) {
if (stream.match(/^<\/\s*script\s*>/i, false)) {
state.token = html;
state.localState = null;
state.mode = "html";
return html(stream, state);
}
return maybeBackup(stream, /<\/\s*script\s*>/,
jsMode.token(stream, state.localState));
}
function css(stream, state) {
if (stream.match(/^<\/\s*style\s*>/i, false)) {
state.token = html;
state.localState = null;
state.mode = "html";
return html(stream, state);
}
return maybeBackup(stream, /<\/\s*style\s*>/,
cssMode.token(stream, state.localState));
}
function smarty(stream, state) {
style = smartyMode.token(stream, state.localState);
if ( state.localState.tokenize == null )
{ // back to anything from smarty
state.token = state.htmlState.tokens.pop();
state.mode = state.htmlState.modes.pop();
state.localState = state.htmlState.states.pop(); // state.htmlState;
}
return(style);
}
return {
startState: function() {
var state = htmlMode.startState();
state.modes = [];
state.tokens = [];
state.states = [];
return {token: html, localState: null, mode: "html", htmlState: state};
},
copyState: function(state) {
if (state.localState)
var local = CodeMirror.copyState(
( state.token == css ) ? cssMode : (( state.token == javascript ) ? jsMode : smartyMode ),
state.localState);
return {token: state.token, localState: local, mode: state.mode,
htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};
},
token: function(stream, state) {
if ( stream.match(/^{[^ ]{1}/,false) )
{ // leaving anything to smarty
state.htmlState.states.push(state.localState);
state.htmlState.tokens.push(state.token);
state.htmlState.modes.push(state.mode);
state.token = smarty;
state.localState = smartyMode.startState();
state.mode = "smarty";
}
return state.token(stream, state);
},
compareStates: function(a, b) {
if (a.mode != b.mode) return false;
if (a.localState) return CodeMirror.Pass;
return htmlMode.compareStates(a.htmlState, b.htmlState);
},
electricChars: "/{}:"
}
}, "xml", "javascript", "css", "smarty");
CodeMirror.defineMIME("text/html", "smartymixed");
The switch to smarty mode is made in token function only but ...
You also have to patch the other basic modes ( css , javascript & xml ) to stop them on the { character so you can fall back in the token function to test it against a regexp ( { followed by a non blank character ).
This may help. I wrote a Smarty mode for CodeMirror2 this weekend. See:
http://www.benjaminkeen.com/misc/CodeMirror2/mode/smarty/
I've also forked the CodeMirror project with my change here:
https://github.com/benkeen/CodeMirror2
All the best -
Ben
[EDIT: this is now part of the main script. I'll be shortly adding a Smarty/HTML/CSS/JS mode].
The second part of the answer : a patch in benjamin smarty file to be able to leave it and fall back in smartymixedmode. So here is the patched verson of mode/smarty/smarty.js
CodeMirror.defineMode("smarty", function(config, parserConfig) {
var breakOnSmarty = ( config.mode == "smartymixed" ) ? true : false; // we are called in a "smartymixed" context
var keyFuncs = ["debug", "extends", "function", "include", "literal"];
var last;
var regs = {
operatorChars: /[+\-*&%=<>!?]/,
validIdentifier: /[a-zA-Z0-9\_]/,
stringChar: /[\'\"]/
}
var leftDelim = (typeof config.mode.leftDelimiter != 'undefined') ? config.mode.leftDelimiter : "{";
var rightDelim = (typeof config.mode.rightDelimiter != 'undefined') ? config.mode.rightDelimiter : "}";
function ret(style, lst) { last = lst; return style; }
function tokenizer(stream, state) {
function chain(parser) {
state.tokenize = parser;
return parser(stream, state);
}
if (stream.match(leftDelim, true)) {
if (stream.eat("*")) {
return chain(inBlock("comment", "*" + rightDelim));
}
else {
state.tokenize = inSmarty;
return ( breakOnSmarty == true ) ? "bracket" : "tag";
}
}
else {
// I'd like to do an eatWhile() here, but I can't get it to eat only up to the rightDelim string/char
stream.next();
return null;
}
}
function inSmarty(stream, state) {
if (stream.match(rightDelim, true)) {
state.tokenize = ( breakOnSmarty ) ? null : tokenizer;
return ( breakOnSmarty == true ) ? ret("bracket", null) : ret("tag", null);
}
var ch = stream.next();
if (ch == "$") {
stream.eatWhile(regs.validIdentifier);
return ret("variable-2", "variable");
}
else if (ch == ".") {
return ret("operator", "property");
}
else if (regs.stringChar.test(ch)) {
state.tokenize = inAttribute(ch);
return ret("string", "string");
}
else if (regs.operatorChars.test(ch)) {
stream.eatWhile(regs.operatorChars);
return ret("operator", "operator");
}
else if (ch == "[" || ch == "]") {
return ret("bracket", "bracket");
}
else if (/\d/.test(ch)) {
stream.eatWhile(/\d/);
return ret("number", "number");
}
else {
if (state.last == "variable") {
if (ch == "#") {
stream.eatWhile(regs.validIdentifier);
return ret("property", "property");
}
else if (ch == "|") {
stream.eatWhile(regs.validIdentifier);
return ret("qualifier", "modifier");
}
}
else if (state.last == "whitespace") {
stream.eatWhile(regs.validIdentifier);
return ret("attribute", "modifier");
}
else if (state.last == "property") {
stream.eatWhile(regs.validIdentifier);
return ret("property", null);
}
else if (/\s/.test(ch)) {
last = "whitespace";
return null;
}
var str = "";
if (ch != "/") {
str += ch;
}
var c = "";
while ((c = stream.eat(regs.validIdentifier))) {
str += c;
}
var i, j;
for (i=0, j=keyFuncs.length; i<j; i++) {
if (keyFuncs[i] == str) {
return ret("keyword", "keyword");
}
}
if (/\s/.test(ch)) {
return null;
}
return ret("tag", "tag");
}
}
function inAttribute(quote) {
return function(stream, state) {
while (!stream.eol()) {
if (stream.next() == quote) {
state.tokenize = inSmarty;
break;
}
}
return "string";
};
}
function inBlock(style, terminator) {
return function(stream, state) {
while (!stream.eol()) {
if (stream.match(terminator)) {
state.tokenize = ( breakOnSmarty == true ) ? null : tokenizer;
break;
}
stream.next();
}
return style;
};
}
return {
startState: function() {
return { tokenize: tokenizer, mode: "smarty", last: null };
},
token: function(stream, state) {
var style = state.tokenize(stream, state);
state.last = last;
return style;
},
electricChars: ""
}
});
CodeMirror.defineMIME("text/x-smarty", "smarty");
The 1st line check if we are called by the smartymixed mode and tests are made on this contition, allowing smarty mode to run as before.