Issue: This method is supposed to accomplish the following:
IF the user is NOT in a specific room already found inside joinedRooms then join them and make the room tab above active. (this part works fine as shown below as the if statement)
ELSE (which means the user is already joined to said room), then just take them to the active tab above.
Here is where I am confused. The code below in my eyes SHOULD work. However, it isnt, it seems to always run the IF statement regardless. What is the incorrect syntax being used.
methods: {
joinRoom(room) {
if (room != this.$store.state.rooms.joinedRooms) {
this.$store.dispatch(RoomTypes.JOIN_ROOM, room);
this.$store.dispatch(RoomTypes.CURRENT_ROOM, room);
this.$emit('onClose')
}
else if (room === this.$store.state.rooms.joinedRooms ) {
this.$emit('onClose')
}
}
},
EDIT: What I am realizing thanks to a comment below is I need to check if the room is part of the array joinedRooms How would I accomplish this
Thanks to #CherryDT, I was able to realize I needed to use includes as part of the if statement. The code should look as follows
methods: {
joinRoom(room) {
if (!this.$store.state.rooms.joinedRooms.includes(room)) {
this.$store.dispatch(RoomTypes.JOIN_ROOM, room);
this.$store.dispatch(RoomTypes.CURRENT_ROOM, room);
this.$emit('onClose')
}
else if (this.$store.state.rooms.joinedRooms.includes(room)) {
this.$store.dispatch(RoomTypes.CURRENT_ROOM, room);
this.$emit('onClose')
}
}
},
Related
I am not getting an efficient way to check below mentioned condition.
What I want to achieve is that-
There are some processes that need to be done if their corresponding boolean is true suggesting to start the process. So I want to check if a particular condition is done only if it should be started.
There are some boolean variables
var shouldStartProcessA
var shouldStartProcessB
var shouldStartProcessC
var isADone
var isBDone
var isCDone
if (shouldStartProcessA && shouldStartProcessB && shouldStartC) {
if (isADone && isBDone && isCDone) {
// Every process completed
}
}
if (shouldStartProcessA && shouldStartProcessB) {
if (isADone && isBDone) {
// Every process completed
}
}
if (shouldStartProcessA && shouldStartC) {
if (isADone && isCDone) {
// Every process completed
}
}
if (shouldStartProcessB && shouldStartC) {
if (isBDone && isCDone) {
// Every process completed
}
}
if (shouldStartProcessA) {
if (isADone) {
// Every process completed
}
}
if (shouldStartProcessB) {
if (isBDone) {
// Every process completed
}
}
if (shouldStartProcessC) {
if (isCDone) {
// Every process completed
}
}
This type of validating condition grows exponentially by introducing every other boolean. I am struggling to find a straightforward implementation to check these conditions.
Instead of doing things this way, I'd recommend a data structure that allows you to add tasks and check their state. There are a lot of ways to do that, but the basic idea is you can iterate over all the items and use functions like all to confirm they're all in the appropriate state. That way you don't have to hand-wire everything together
You could use a Map and add tasks to it, initially mapping them to false and setting that to true when they're completed. Or create a Set and add your tasks to that (I'm assuming you want one of each at most), and remove them / move them to a "done" list when they complete. That kind of idea. You could create an enum class to represent your tasks if you want, so each one is its own instance (e.g. Process.A, like having a dedicated, fixed variable) and you can easily use those in your logic
If you really want variables for each process, instead of a data structure, I'd still recommend rolling each pair into a single state, something like this:
enum class State {
UNUSED, PENDING, DONE
}
var processA = State.UNUSED
var processB = State.PENDING
// etc
// you can easily check them like this:
// create a list of all the variables you want to check - we're using references
// to the properties themselves (with the ::), not the current value!
val allProcesses = listOf(::processA, ::processB)
// now you have that collection, you can easily iterate over them all
// and work out what's what - we need to use get() to get the current values
val allFinished = allProcesses
.filterNot { it.get() == State.UNUSED } // ignore unused processes
.all { it.get() == State.DONE } // check ALL the required ones are DONE
You could write that check there as a single all condition, but the point is to show you you can be flexible with it, and build up your logic by filtering out the stuff you're not interested in, if you create a useful set of states
If you really do want to (or have to) stick with the current "pairs of variables" setup, you can do something similar:
// wiring them up again, creating a list of Pairs so we can iterate over them easily
val allProcesses = listOf(
::shouldStartProcessA to ::isADone,
::shouldStartProcessB to ::isBDone,
::shouldStartProcessC to ::isCDone
)
// gotta check 'em all - only returns true if that ALL meet the condition
val allComplete = allProcesses.all { (shouldStart, isDone) ->
// the get() syntax is awkward, but basically for everything we're checking
// if it either doesn't need to start, or it does but it's also done
!shouldStart.get() || (shouldStart.get() && isDone.get())
}
so adding new processes is just a case of adding their variables to the list of pairs, and they get included in the checking
You don't need the property reference stuff (::/.get()) if you create the lists right before you check them, but if you want to define them once in advance (and the property values can change after that) then that's how you'd do it. Otherwise you can just do the normal shouldStartProcessA to isADone etc, which is probably fine for most cases - I'm showing the reference stuff as a more general example for handling this kind of thing
I suppose, you should create two lists of Boolean and add variables consequently.
val list1 = listOf(shouldStartProcessA, shouldStartProcessB, shouldStartC)
val list2 = listOf(isADone, isBDone, isCDone)
Then iterate over both lists and check that items in corresponding positions have the same values.
var n = 0
for (i in list1.indices) {
if (list1[i] == list2[i]) {
n++
} else {
n = 0
break
}
}
if (n > 0) {
// Every process completed
}
It always worked before, but it is no longer working.
I have a rate limiting logic, but even if I clear all rate limiting data, it still happens. Only with a specific user.
I created another account on FaunaDB for testing purposes and a new database. If I restore the old database data to that new database, everything works!
So I recreated the entire database on the old FaunaDB account and the problem persists.
Is anyone experiencing something similar?
Is there any information in cache?
Login(Match(Index("accounts_by_email"), "email#email.com"), {
password: "secret",
})
/* returns
Error: [
{
"position": [],
"code": "authentication failed",
"description": "The document was not found or provided password was incorrect."
}
]
*/
The password is not incorrect. It works on the other FaunaDB account with the data restored.
./fdm -source path=backup -dest key={admin_key}
Yes, that was a temporary problem. I experienced it was well at a certain moment in my own Fwitter example. Our uniqueness detection didn't play well with code that created/updated/deleted things in one complex FQL flow which the code is doing :). I ticketed that and it should be fixed in the meantime.
It's good to know that the rate limiting in there was a bit me experimenting with events. It can also be written much simpler, I guess I was a bit to deep zoned and to be fair.. I just joined FaunaDB back then. I'm working on a skeleton app that will contain that simpler version. In the meantime here is the code:
Simpler rate limiting
import { rateLimiting } from '../../fauna-queries/helpers/errors'
import faunadb from 'faunadb'
/*
* Ideally we limit the amount of calls that come to Login.
*/
const q = faunadb.query
const {
If,
Epoch,
Match,
Index,
Collection,
Let,
Var,
Paginate,
Select,
TimeDiff,
Or,
GTE,
Abort,
Create,
IsEmpty,
Count,
LT,
Do,
Now,
Subtract
} = q
function AddRateLimiting(action, FqlQueryToExecute, Identifier, calls, perMilliseconds) {
const ExecuteAndCreateLog = Do(
Create(Collection('logs'), {
data: {
action: action,
identity: Identifier
}
}),
FqlQueryToExecute
)
return Let(
{
logsPage: Paginate(Match(Index('logs_by_action_and_identity_ordered_by_ts'), action, Identifier), {
size: calls
})
},
If(
Or(IsEmpty(Var('logsPage')), LT(Count(Select(['data'], Var('logsPage'))), calls)),
// If no logs exist yet, create one.
ExecuteAndCreateLog,
Let(
{
// the page looks like { data: [timestamp1, timestamp2,...]},
// we will retrieve the last timestamp of that page. If the pagesize would be 3, it would be the oldest of these 3 events.
// since the index is ordered from new to old.
timestamp: Select(['data', Subtract(calls, 1)], Var('logsPage')),
// transform the Fauna timestamp to a Time object
time: Epoch(Var('timestamp'), 'microseconds'),
// How long ago was that event in ms
ageInMs: TimeDiff(Var('time'), Now(), 'milliseconds')
},
If(
GTE(Var('ageInMs'), perMilliseconds),
// Then great we execute
ExecuteAndCreateLog,
// Else.. Abort! Rate-limiting in action
Abort(rateLimiting)
)
)
)
)
}
Blocking after faulty logins
I also separated blocking three faulty logins since I was kinda abusing that rate-limiting system for it. A few undefines in this code of course, it's just meant to give you an idea of how it looks for more info, keep an eye out for the skeletons + blogs to come out.
// Let's wrap some other functionality around the login.
const BlockThreeFaultyLogins = Do(
If(
GTE(Count(Match(Index('logs_by_action_and_identity'), 'faulty_login', email)), MAX_LOGIN_ATTEMPTS),
// Abort if exceeded
Abort(tooManyFaultyLogins),
// Else, just continue as usual!
Let(
{
login: LoginFQL
},
Do(
If(
Equals(false, Var('login')),
// if the login is faulty, we'll add a log entry
Create(Collection('logs'), {
data: {
action: 'faulty_login',
identity: email
}
}),
// Else, we will clean up the faulty_login logs
q.Map(
Paginate(Match(Index('logs_by_action_and_identity'), 'faulty_login', email)),
Lambda(['logRef'], Delete(Var('logRef')))
)
),
Var('login')
)
)
)
)
I have userDto, contains programs, which contains actual field. Actual program can be only one. I need to get it. Than, I run this:
userDto.programs.sortedBy { it.created }.findLast { it.actual }?
Okay, but I want to foresee case, when findLast returns null, & throw exception. Please, advice, how to do it?
UPD:
ProgramType.valueOf(userDto.programs
.sortedBy { it.created }
.findLast { it.actual }
//check here
!!.programType!!).percentage
You are pretty close actually :)! What you could do is:
userDto.programs.sortedBy { it.created }.findLast { it.actual } ?: throw RuntimeException()
Or if you're trying to actually avoid throwing an error(couldn't really tell with the way question is asked), you could just do an error check like this:
userDto.programs.sortedBy { it.created }.findLast { it.actual }?.let{
//rest of your code goes here
}
Hope this helps, cheers!
I will try my best to explain the problem i have.
here is a sample code
auth.js
static authenticate(email,password,callbackIsLogged)
{
//some logic
if(passwordCorrect)
{
callbackIsLogged(true);
}
else
{
callbackIsLogged(false);
}
}
login.js
loginButtonClicked()
{
Authcontroller.authenticate(email,password,function(loginState)
{
if(loginState)
{
alert('correect');
//proceed withlogin.
}
else
{
alert('error');
}
});
}
the problem i have is weired.
lets look at a sample scenario where this bug happens.
if i login with correct username and password for the first time when the app opens everything goes according to plan.
But if i enter the incorrect password at the first time and the second time enter the correct password the callback function will get called twice with boolean value true and false.
It seems like the static function somehow hold the previous callbacks and execute them.
hope you undestood my question. how to fix this.
thanks.
how would it be possible to bypass functions that are not existing in DM
such that the main code would still run? Try/catch does not seem to work, e..g
image doSomething(number a,number b)
{
try
{
whateverfunction(a,b)
}
catch
{
continue
}
}
number a,b
doSomething(a,b)
Also conditioning wont work, e.g..
image doSomething(number a,number b)
{
if(doesfunctionexist("whateverfunction"))
{
whateverfunction(a,b)
}
}
number a,b
doSomething(a,b)
thanks in advance!
As "unknown" commands are caught by the script-interpreter, there is no easy way to do this. However, you can construct a workaround by using ExecuteScriptCommand().
There is an example tutorial to be found in this e-book, but in short, you want to do something like the following:
String scriptCallStr = "beep();\n"
scriptCallStr = "MyUnsaveFunctionCall();\n"
number exitVal
Try { exitVal = ExecuteScriptString(scriptCallStr ); }
Catch { exitVal = -1; break; }
if ( -1 == exitVal )
{
OKDialog("Sorry, couldn't do:\n" + scriptCallStr )
}
else
{
OKDialog( "All worked. Exit value: " + exitVal )
}
This works nicely and easy for simple commands and if your task is only to "verify" that a script could run.
It becomes clumsy, when you need to pass around parameters. But even then there are ways to do so. (The 'outer' script could create an object and pass the object-ID per string. Similarly, the 'inner' script can do the same and return the script-object ID as exit-value.)
Note: You can of course also put doesfunctionexist inside the test-script, if you do only want to have a "safe test", but don't actually want to execute the command.
Depending on what you need there might also be another workaround solution: Wrapper-functions in a library. This can be useful if you want to run the same script on different PCs with some of which having the functionality - most likely some microscope - while others don't.
You can make your main-script use wrapper methods and then you install different versions of the wrapper method script scripts as libraries.
void My_SpecialFunction( )
{
SpecialFunction() // use this line on PCs which have the SpecialFunction()
DoNothing() // use alternative line on PCs which don't have the SpecialFunction()
}
My_SpecialFunction( )
I have used this in the past where the same functionality (-stage movement-) required different commands on different machines.