How to throw a specific Exception in Julia - exception

I am doing test driven development in Julia.
The test expects a certain exception to be thrown.
How do I throw the expected exception?
I'm looping through a string and counting the occurrence of specific letters.
Any letter than 'A','C','G',or'T' should result in an exception
Running Julia version 1.2.0.
I have tried these alternatives:
throw(DomainError())
throw(DomainError)
throw("DomainError")
I expected those to work based on this resource:
https://scls.gitbooks.io/ljthw/content/_chapters/11-ex8.html
Here is a link to the problem I am trying to solve:
https://exercism.io/my/solutions/781af1c1f9e2448cac57c0707aced90f
(Heads up: That link may be unique to my login)
My code:
function count_nucleotides(strand::AbstractString)
Counts = Dict()
Counts['A'] = 0
Counts['C'] = 0
Counts['G'] = 0
Counts['T'] = 0
for ch in strand
# println(ch)
if ch=='A'
Counts['A'] += 1
# Counts['A'] = Counts['A'] + 1
elseif ch=='C'
Counts['C'] += 1
elseif ch=='G'
Counts['G'] += 1
elseif ch=='T'
Counts['T'] += 1
else
throw(DomainError())
end
end
return Counts
end
The test:
#testset "strand with invalid nucleotides" begin
#test_throws DomainError count_nucleotides("AGXXACT")
end
My error report, see the lines with: Expected and Thrown.
strand with invalid nucleotides: Test Failed at /Users/username/Exercism/julia/nucleotide-count/runtests.jl:18
Expression: count_nucleotides("AGXXACT")
Expected: DomainError
Thrown: MethodError
Stacktrace:
[1] top-level scope at /Users/shane/Exercism/julia/nucleotide-count/runtests.jl:18
[2] top-level scope at /Users/juliainstall/buildbot/worker/package_macos64/build/usr/share/julia/stdlib/v1.2/Test/src/Test.jl:1113
[3] top-level scope at /Users/username/Exercism/julia/nucleotide-count/runtests.jl:18
Test Summary: | Fail Total
strand with invalid nucleotides | 1 1
ERROR: LoadError: Some tests did not pass: 0 passed, 1 failed, 0 errored, 0 broken.

The MethodError comes from the call to DomainError -- there are no zero-argument constructor for this exception type. From the docs:
help?> DomainError
DomainError(val)
DomainError(val, msg)
The argument val to a function or constructor is outside the valid domain.
So there are one constructor which takes the value that was out of the domain, and one that, in addition, takes an extra message string. You could e.g. do
throw(DomainError(ch))
or
throw(DomainError(ch, "this character is bad"))

Related

Cannot index into null array from function returned variable, or issues accessing regex data returned

I'm not sure if I'm returning the value from the function incorrectly, but when I try to access it's info, it has the above error,
Cannot index into a null array
I've tried a couple different ways, and I'm not sure if I'm not returning this correctly from the function, or if I'm just accessing the info returned incorrectly. Looking at Cannot index into null array, it looks like for him, some of his array had null values. But when I print my info to screen before I exit the function, it has info. How do I return the value found in the function such that I can loop through the contents in my main code and use one of the strings in the object? This is a continuation of parsing repeated pattern.
#parse data out of cpp code and loop through to further process
#function
Function Get-CaseContents{
[cmdletbinding()]
Param ( [string]$parsedCaseMethod, [string]$parseLinesGroupIndicator)
Process
{
# construct regex
$fullregex = [regex]"_stprintf[\s\S]*?_T\D*", # Start of error message, capture until digits
"(?<sdkErr>\d+)", # Error number, digits only
"\D[\s\S]*?", # match anything, non-greedy
"(?<sdkDesc>\((.+?)\))", # Error description, anything within parentheses, non-greedy
"([\s\S]*?outError\s*=(?<sdkOutErr>\s[a-zA-Z_]*))", # Capture OutErr string and parse out part after underscore later
"[\s\S]*?", # match anything, non-greedy
"(?<sdkSeverity>outSeverity\s*=\s[a-zA-Z_]*)", # Capture severity string and parse out part after underscore later
'' -join ''
# run the regex
$Values = $parsedCaseMethod | Select-String -Pattern $fullregex -AllMatches
# Convert Name-Value pairs to object properties
$result = foreach ($match in $Values.Matches){
[PSCustomObject][ordered]#{
sdkErr = $match.Groups['sdkErr']
sdkDesc = $match.Groups['sdkDesc']
sdkOutErr = $match.Groups['sdkOutErr']
sdkSeverity = ($match.Groups['sdkSeverity'] -split '_')[-1] #take part after _
}
}
#Write-Host "result:" $result -ForegroundColor Green
$result
return $Values
...
#main code
...
#call method to get case info (sdkErr, sdkDesc, sdkOutErr, sdkSeverity)
$ValuesCase = Get-CaseContents -parsedCaseMethod $matchFound -parseLinesGroupIndicator "_stprintf" #need to get returned info back
$result = foreach ($match in $ValuesCase.Matches){
[PSCustomObject][ordered]#{
sdkErr = $match.Groups['sdkErr']
sdkDesc = $match.Groups['sdkDesc']
sdkOutErr = $match.Groups['sdkOutErr']
sdkSeverity = ($match.Groups['sdkSeverity'] -split '_')[-1] #take part after _
} #result
} #foreach ValuesCase
The example of string sent to the function to parse is:
...
case kRESULT_STATUS_Undefined_Opcode:
_stprintf( outDevStr, _T("8004 - (Comm. Err 04) - %s(Undefined Opcode)"), errorStr);
outError = INVALID_PARAM;
outSeverity = CCA_WARNING;
break;
case kRESULT_STATUS_Comm_Timeout:
_stprintf( outDevStr, _T("8005 - (Comm. Err 05) - %s(Timeout sending command)"), errorStr);
outError = INVALID_PARAM;
outSeverity = CCA_WARNING;
break;
case kRESULT_STATUS_TXD_Failed:
_stprintf( outDevStr, _T("8006 - (Comm. Err 06) - %s(TXD Failed--Send buffer overflow.)"), errorStr);
outError = INVALID_PARAM;
outSeverity = CCA_WARNING;
break;
...
Another thing I tried is (but it also had the index into null array issue):
foreach($matchRegex in $ValuesCase.Matches)
{
$sdkOutErr = $matchRegex.Groups['sdkOutErr']
Write-Host sdkOutErr -ForegroundColor DarkMagenta
}
Ultimately, I need to grab $sdkOutErr to further process. I'll need to use the other variables too in the returned object, but this is the first one I need. I love the way the output is formatted in the function, but probably don't know how to return the info and use what is returned. I'm not sure what to search for to figure out the issue other than the error message, which leads me to believe I'm returning the info wrong. I don't think I need to return $result, because I think that's just a string with the values in the $values.Matches in the function. I need to access the values returned as I mentioned.
I checked, and the contents sent to the function is not blank.
I tried returning $results, and it looks like this when I write-Host, which would be difficult to access each sdkOutErr:
#{sdkErr=1000; sdkDesc=(Out of Memory); sdkOutErr= NO_MEMORY; sdkSeverity=FATAL} #{sdkErr=1002; sdkDesc=(Failed to load DLL); sdkOutErr= OTHER_ERROR; sdkSeverity=FATAL} #{sdkErr=1003; sdkDesc=(Failed to load DLL); sdk
OutErr= OTHER_ERROR; sdkSeverity=FATAL} #{sdkErr=1004; sdkDesc=(Failed to open); sdkOutErr= OTHER_ERROR; sdkSeverity=FATAL} #{sdkErr=1005; sdkDesc=(Unable to access the specified profile); sdkOutErr= OTHER_ERROR; sdkSeverity=
FATAL} #{sdkErr=100 ...
How can I return this from the function so that it's not a null array/index, and the data is accessible if I use a foreach loop (or two) in the main code to get the sdkOutErr (to start).
I'm fairly new to (complicated)powershell and I have a feeling I need a map inside the array in my function, but I'm not sure.
Before I returned the function Values or results, it was printing something like this out. Once I added in main $ValuesCase=Get-CaseContents... (returning $values from function), or $parsedCase = Get-CaseContents... (returning $results from function), it stopped showing this on the screen:
sdkErr sdkDesc sdkOutErr sdkSeverity
------ ------- --------- -----------
1000 (Out of Memory) NO_MEMORY FATAL
1002 (Failed to load DLL) OTHER_ERROR FATAL
1003 (Failed to load DLL) OTHER_ERROR FATAL
1004 (Failed to open) OTHER_ERROR FATAL
I tried returning $results, and it looks like this when I write-Host, which would be difficult to access each sdkOutErr:
Getting all the sdkOutErr values is not as difficult as you might imagine:
$results.sdkOutErr # this will output the `sdkOutErr` value from each object in the array
Or, outside the function:
(Get-CaseContents -parsedCaseMethod $matchFound -parseLinesGroupIndicator "_stprintf").sdkOutErr
Another option, which might perform better if the result set is large, is to use ForEach-Object to grab just the sdkOutErr values:
$fullResults = Get-CaseContents -parsedCaseMethod $matchFound -parseLinesGroupIndicator "_stprintf"
$sdkOutErrValuesOnly = $fullResults |ForEach-Object -MemberName sdkOutErr

incremental search method script errors

I wrote my very first octave script which is a code for the incremental search method for root finding but I encountered numerous errors that I found hard to understand.
The following is the script:
clear
syms x;
fct=input('enter your function in standard form: ');
f=str2func(fct); % This built in octave function creates functions from strings
Xmax=input('X maximum= ');
Xinit=input('X initial= ');
dx=input('dx= ');
epsi=input('epsi= ');
N=10; % the amount by which dx is decreased in case a root was found.
while (x<=Xmax)
f1=f(Xinit);
x=x+dx
f2=f(x);
if (abs(f2)>(1/epsi))
disp('The function approches infinity at ', num2str(x));
x=x+epsi;
else
if ((f2*f1)>0)
x=x+dx;
elseif ((f2*f1)==0)
disp('a root at ', num2str );
x=x+epsi;
else
if (dx < epsi)
disp('a root at ', num2str);
x=x+epsi;
else
x=x-dx;
dx=dx/N;
x=x+dx;
end
end
end
end
when running it the following errors showed up:
>> Incremental
enter your function in standard form: 1+(5.25*x)-(sec(sqrt(0.68*x)))
warning: passing floating-point values to sym is dangerous, see "help sym"
warning: called from
double_to_sym_heuristic at line 50 column 7
sym at line 379 column 13
mtimes at line 63 column 5
Incremental at line 3 column 4
warning: passing floating-point values to sym is dangerous, see "help sym"
warning: called from
double_to_sym_heuristic at line 50 column 7
sym at line 379 column 13
mtimes at line 63 column 5
Incremental at line 3 column 4
error: wrong type argument 'class'
error: str2func: FCN_NAME must be a string
error: called from
Incremental at line 4 column 2
Below is the flowchart of the incremental search method:
The problem happens in this line:
fct=input('enter your function in standard form: ');
Here input takes the user input and evaluates it. It tries to convert it into a number. In the next line,
f=str2func(fct)
you assume fct is a string.
To fix the problems, tell input to just return the user's input unchanged as a string (see the docs):
fct=input('enter your function in standard form: ', 's');

python missing one required positional argument?

I am defining a function and trying to print the result of this function however i am getting the error message:
temp_of_seawater() missing 1 required positional argument: 'd'
Relevant code:
def temp_of_seawater(l, d):
temp_of_seawater = ((gradient * d) + temp_surfacelevel_1)
return temp_of_seawater(d)
print("The temperature at your given latitude and depth is:",
temp_of_seawater(d) , "\u00b0""C")

failwith causes an error when used in a calculation expression - FParsec

I use a function:
let identifier kind =
(many1Satisfy2L isLetter
(fun c -> isLetter c || isDigit c) "identifier"
>>= fun s -> preturn s) >>= fun s -> identifierKind s kind
The kind argument is of this type:
type KindOfIdentifier =
| Data
| Type
| Module
And here is my function that analyzes the kind argument:
let private identifierKind (id: string) kind =
match kind with
| KindOfIdentifier.Data ->
if id.ToUpper() = id && id.Length > 1 then preturn id
elif System.Char.IsUpper id.[0] = false then preturn id
else failwith "Error 1"
| KindOfIdentifier.Module ->
if System.Char.IsUpper id.[0] then preturn id
else failwith "Error 2"
| KindOfIdentifier.Type ->
preturn id
I would therefore like to analyze an identifier to verify whether it meets the criteria of the identifier type. If identifying it does not meet the criterion, I return an error with failwith.
But, when I use this parser (identify) with a deliberate error in my text to be analyzed, to check if everything works, I get a long error:
(Sorry, I'm French, so there's a little french in the error message ^^.)
How to prevent all this, and only display the error message in the classic way with FParsec?
The failwith function throws a .NET exception - a catasprophic failure that is supposed to indicate that the program broke in an unexpected way. Or, in other words, in an exceptional way - hence the name "exception". This is not what you're trying to do.
What you're trying to do here is to indicate to FParsec that the current parsing attempt has failed, and possibly provide an explanation of what exactly happened.
To do this, you need to create an error-producing instance of Parser - the same type that is returned by preturn.
While preturn creates a successful instance of Parser, there is another function that creates an error-producing instance. This function is called fail. Just use it:
| KindOfIdentifier.Data ->
if id.ToUpper() = id && id.Length > 1 then preturn id
elif System.Char.IsUpper id.[0] = false then preturn id
else fail "Error 1"

Bitcoind JSON comment error

Trying to add a comment (in json) to a transaction but keep getting this error: "error: value is type obj, expected int"
bitcoind move acc1 acc2 0.00000002 '{"test":"hi"}'
I was missing the minconf=1 arg value (ie. needed a 1):
bitcoind move acc1 acc2 0.00000002 1 '{"test":"hi"}'