Struggling with the ifelse function in R - function

Can someone please explain me what I am doing wrong. I don't understand the behaviour of the ifelse function in R. I expected that the ifelse function would return the whole list ids_match. However, these are the results I get with RStudio Version 1.3.1093 in the Console Window:
cond1 = FALSE
cond2 = FALSE
cond3 = TRUE
ids_match = list(1, 2, 3)
ifelse(cond1 & cond2 & cond3, ids_match[1], ids_match)
[[1]]
[1] 1
ifelse(TRUE, ids_match[1], ids_match)
[[1]]
[1] 1
ifelse(FALSE, ids_match[1], ids_match)
[[1]]
[1] 1
ifelse(FALSE, "TRUE", "FALSE")
[1] "FALSE"
ifelse(TRUE, "TRUE", "FALSE")
[1] "TRUE"`

According to ?ifelse:
Usage: ifelse(test, yes, no)
Description:
‘ifelse’ returns a value with the same shape as ‘test’ which is
filled with elements selected from either ‘yes’ or ‘no’ depending
on whether the element of ‘test’ is ‘TRUE’ or ‘FALSE’.
Now, since (cond1 & cond2 & cond3) is a single boolean variable (i.e. length(cond1 & cond2 & cond3) == 1), your response will also have length of 1.
Also see related discussion here.

Related

MarkLogic - false is true

let $d := doc('/test/a-false.json')
return ($d, if ($d/a) then 'false is true' else 'false is false')
The result:
{"a":false}
false is true
Really?
StackOverflow's robot was not contented with the above, so I will add some meaningless text that you don't have to read, even though I think the above is more than adequate at describing the problem. Long live our mechanical overlords.
In your example $d/a is a boolean node, a MarkLogic extension, part of the set of node types added to represent JSON in XDM.
The EBV of such a node is true if it exists. Which might be surprising for a boolean node with the value false. What you see here is the answer to the question: "Does such a node exists?" For the question "Is its value false?," use fn:data().
Relevant expressions:
let $d := fn:doc('/test/a-false.json')
return (
$d,
$d/a,
fn:data($d/a),
if ( $d/a ) then 'false exists' else 'false does not exist',
if ( fn:data($d/a) ) then 'false is true' else 'false is not true'
)
Result:
{"a":false}
fn:doc("/test/a-false.json")/boolean-node("a")
false
false exists
false is not true

Postgres : can't make JSONB_PATH_EXISTS work correctly

I'm struggling with JSONB_PATH_EXISTS Postgres function
I'm using PG 12 and following this documentation : https://www.postgresql.org/docs/12/functions-json.html
With the following request (test it on DBFiddle: https://dbfiddle.uk/?rdbms=postgres_12&fiddle=d5aa984182852438c6f71cf5fa70324e) :
select
json
from (
select '{
"fields": {
"foo": true,
"number": 3,
"listnb": [3, 4],
"listenb2": ["3", "4"],
"txt": "hello how are you",
"listtxt": ["hello","how","are", "you", "3"],
"nullval": null
}
}'::jsonb as json
) t
where 1=1
-- Works with 'strict'
AND JSONB_PATH_EXISTS(json -> 'fields' -> 'listtxt', 'strict $ ? (#.type() == "array")')
-- Doesn't work without 'strict'. Why ?
--AND JSONB_PATH_EXISTS(json -> 'fields' -> 'listtxt', '$ ? (#.type() == "array")')
-- Can't add a nested condition on an array element value (syntax error)
--AND JSONB_PATH_EXISTS(json -> 'fields' -> 'listtxt', 'strict $ ? (#.type() == "array" && #[*] ? (# == "how"))')
;
#1 - I can't get type() function work without strict mode
It could be related to the lax mode unwrapping arrays automatically, but the documentation explicitly states that it is not done when type() function is called :
The lax mode facilitates matching of a JSON document structure and path expression if the JSON data does not conform to the expected schema. [...] Automatic unwrapping is not performed only when:
The path expression contains type() or size() methods that return the type and the number of elements in the array, respectively.
[...]
So I don't understand why we have a difference in the result
#2 I can't get the nested condition work (3rd AND in the sample request)
According to the examples in the documentation, the syntax looks OK but I have a syntax error that I don't understand.
Thank you for your help
If you pass the complete JSON value to the function, then the following works:
where jsonb_path_exists(json, '$ ? (#.fields.listtxt.type() == "array")')
However I would probably simply use jsonb_typeof() without a path query
where jsonb_typeof(json -> 'fields' -> 'listtxt') = 'array'

Substring question on mips assembly language

Please help as soon as possible...
Write a MIPS assembly language program that prompts the user to input two strings (each should be no longer than 50 characters including the null terminator). Your program should determine whether the second string is a substring of the first. If it is, then your program should print out the first index in which the second string appears in the first. For example, if the first string is “Hello World” and the second string is “lo”, then the program should print out 3, i.e. the starting index of “lo” in “Hello World.” If the second string is not contained in the first string, then your program should print out -1.
To be able to understand what you have to implement at assembly level, the first thing you should do, is understanding the high-level algorithm. Why?
It's easier for you to see all the cases and edge-cases in time!
To look back at what have I been trying to do again? in the middle of programming the Assembly version.
To quickly see which variables you (certainly) need.
I wrote following program (forgive me, python has been a while for me):
def is_in_string_1(string, substring):
"""
aaba: a, b, ab, ba, aba (last one will fail)
"""
length = len(string)
sublength = len(substring)
if (sublength == 0):
return True
j = 0
for i in range(0, length):
if string[i] != substring[j]:
j = 0
else:
j += 1
if j == sublength:
return True
return False
def is_in_string_2(string, substring):
"""
aaba: a, b, ab, ba, aba
"""
length = len(string)
sublength = len(substring)
for i in range(0, length + 1 - sublength): # string: aabc; substring: c; length: 4; sublength: 1; indexes: 0,1,2,3;
is_substring = True
for j in range(0, sublength): # for the sake of the algorithm, no slicing here
if string[i+j] != substring[j]:
is_substring = False
break
if is_substring:
return True
return False
stringTuples = [
("aaa", "aa"),
("aaa", "aaa"),
("aaa", "aab"),
("abc", "bc"),
("abc", "a"),
("abc", "abc"),
("aaa", ""),
("aaa", "b")
]
for stringTuple in stringTuples:
print(
stringTuple[0],
stringTuple[1],
':',
is_in_string_1(stringTuple[0], stringTuple[1]),
is_in_string_2(stringTuple[0], stringTuple[1]),
sep='\t'
)
I first thought I could optimize the standard solution (is_in_string_2), leaving out the second for-loop (is_in_string_1), but after some thinking I already found out it would fail (the edge-case wasn't even in any of my test-data!) - so I left it as an example for how important it is that you use a correct algorithm.
The program produces the following output:
aaa aa : True True
aaa aaa : True True
aaa aab : False False
abc bc : True True
abc a : True True
abc abc : True True
aaa : True True
aaa b : False False
aaba aba : False True
Notice how all output was correct, except for the last line, where the first algorithm is wrong.
Before you continue:
You have to make your own len() function in MIPS; note that all string are (if I remember correctly) null terminated, so you'll have to count all non-null characters of a string, or in other words, count how many characters precede the null-terminator.
You should use j, $ra and jr calls to go to a "function" or subroutines. (Search)
While in one, you can call other functions using the stack. (Search)

RMySQL - dbWriteTable() writes TRUE logical as 0

When using dbWriteTable() in the RMySQL package, logical values are written as 0 regardless of value. I would expect that TRUE values would return a 1:
# Setup
# con is a valid MySQLConnection object
> df <- data.frame(string = 'Testing Logical Values',
t_lgl = TRUE,
f_lgl = FALSE,
stringsAsFactors = FALSE)
> df
string t_lgl f_lgl
1 Testing Logical Values TRUE FALSE
> class(df[,2])
[1] "logical"
# Test
# This schema has no tables until dbWriteTable() is called
> dbWriteTable(con,'test_table',df)
[1] TRUE
# Result
> dbReadTable(con,'test_table')
string t_lgl f_lgl
1 Testing Logical Values 0 0
> class(dbReadTable(con,'test_table')[,2])
[1] "integer"
Shouldn't the t_lgl value return 1 since it was TRUE and passed to dbWriteTable() as a logical?
The RMySQL package is being phased out in favour of RMariaDB.
Using RMariaDB I am able to successfully write logical values to a MySQL database like this:
con <- dbConnect(RMariaDB::MariaDB(), group = "my-db")
dbWriteTable(con, "test", data.frame(a=T, b=F), overwrite = T)

Function default arguments and named values

Let's say I have an R function in which the arguments can be a one of a few predefined named values (one of which is the default) or a custom character vector. How should I implement this without relying on magic value names or another flag?
#allow use of predefined subsets or pass their own list
bratPack<-function(members='CORE',...){
if (members=='CORE')
members<-c('Emilio Estevez','Anthony Michael Hall','Rob Lowe','Andrew McCarthy','Demi Moore','Judd Nelson','Molly Ringwald','Ally Sheedy')
else if (members=='ALL')
members<-c('Emilio Estevez','Anthony Michael Hall','Rob Lowe','Andrew McCarthy','Demi Moore','Judd Nelson','Molly Ringwald','Ally Sheedy','James Spader','Robert Downey, Jr.','Jon Cryer', 'John Cusack', 'Kevin Bacon', 'Jami Gertz', 'Mary Stuart Masterson', 'Matthew Broderick', 'Sean Penn', 'Kiefer Sutherland')
...
}
From your example we have the choice of "CORE" and "ALL". If those are the two options, then we specify them in the function definition for the argument 'members'. E.g.:
foo <- function(x, members = c("CORE", "ALL")) {
## do something
}
That function definition sets up the allowed values for argument 'members', with a default of "CORE" as this is the first named option.
The code that one uses within the function body is match.arg(), as #Joris has already mentioned, but because we have set the function up as above, we can simply the usage to just match.arg(members).
So we can write foo as:
foo <- function(x, members = c("CORE", "ALL")) {
## evaluate choices
members <- match.arg(members)
## do something
print(members)
}
Which we use like this:
> foo()
[1] "CORE"
> foo(members = "CORE")
[1] "CORE"
> foo(members = "ALL")
[1] "ALL"
> foo(members = "3rdRate")
Error in match.arg(members) : 'arg' should be one of “CORE”, “ALL”
Notice the behaviour when we supply an string not included in the set of options. We get an intuitive error message, all because we set up the options in the function arguments.
I'd use some constant dataframe somewhere in the package:
.mdata <- data.frame(
CORE= c(TRUE,FALSE,TRUE),
OLD = c(TRUE,TRUE,FALSE),
ALL = c(TRUE,TRUE,TRUE),
row.names=c("John Doe", "Jan Janssen", "Piet Peters")
)
bratPack<-function(members='CORE',...){
m.tmp <- try(
match.arg(members,names(.mdata),several.ok=T),
silent=T)
if(!is(m.tmp,"try-error"))
members <- rownames(.mdata)[.mdata[[members]]]
print(members)
}
> bratPack('CORE')
[1] "John Doe" "Piet Peters"
> bratPack('Jan Janssen')
[1] "Jan Janssen"
> bratPack(c("John Doe","Dick Dickers"))
[1] "John Doe" "Dick Dickers"