Running tests for specific method in SAGE - sage

I know there is possible to run tests for specific lines and methods in some languages/frameworks as for example Ruby on Rails. I would like to know if there is some specific syntax to do the same in SAGE math. For example, suppose I have the next code. I would like to run only the EXAMPLES of method1 with something like sage -t module.py:method1
#module.py
def method1():
"""
EXAMPLES::
sage: 5+0
5
"""
return 1
def method2():
"""
EXAMPLES::
sage: 5+2
7
"""
return 2

Related

Is it possible to break 1 line of code into multiple in atom IDE, just like in Rstudio

I am new to using Julia and the atom IDE, and I was wondering if it was possible to somehow just press enter and have the computer run 1 line of code spread over multiple lines, and still have it recognize that it is still the same 1 line of code, just like in Rstudio? (I want this for readability purposes only)
what I mean is something like:
println("Hello
world")
and be able to highlight and run this script without receiving an error message.
Yes. The method differs based on what the line of code contains, or specifically, where you want to break the line.
For a string like you've posted in the question, you have to precede the newline with a \ character, to inform Julia that you're using this newline only for readability, and don't want it to be included in the actual string. (Note: I'll be illustrating these with the command-line REPL that has the julia> prompt, but the same principles apply in the Atom/VS Code based IDE setups too).
julia> println("Hello \
world")
Hello world
Outside of strings, if the current line isn't complete, Julia automatically looks for the continuation in the next line. This means that to break a line into multiple ones, you have to leave all but the final line incomplete:
julia> 1 +
2 +
3 *
4
15
julia> DEPOT_PATH |>
first |>
readdir
16-element Vector{String}:
"artifacts"
"bin"
⋮
julia> 1,
2,
3
(1, 2, 3)
In some cases when you don't have a convenient binary operator to leave hanging like the above, you may have to start your line with an opening parenthesis, so that Julia will know that it's a continuous statement until the closing parenthesis is encountered.
You also have multi-line Strings denoted by """:
julia> println("""This
is
a multi-line \
text""")
This
is
a multi-line text

Can a task depend on multiple ShortCircuitOperator tasks in Airflow?

For instance, can I set up two shorting-tasks in front of another task:
[short_A, short_B] >> task_A
Yes.
When depending on multiple ShortCircuitOperators, you are essentially creating an AND gate.
So if you want task_A to run, you need short_A AND short_B AND ... to return True.
If you want to build an OR gate, you either have to replace the shortcircuit operator with a custom one, or raise AirflowSkipException inside normal python operator tasks.
For instance for python tasks A, B and C:
[A, B] >> C
You want A and B to implement raise AirflowSkipException where you would have set return False in the shorting operator. Finally you need to set the parameter
trigger_rule='none_failed_or_skipped' on C.

"I got stuck while parsing the function definition:": How to properly define an Elm function?

I'm experiment/practicing Elm for the first time and am running into difficulty defining a function. The following:
isDivisible : Int -> Int -> Int -> Bool
isDivisible n x y =
((modBy n x) == 0) && ((modBy n y) == 0)
isDivisible 4 4 2
Results in:
-- PROBLEM IN DEFINITION --------------------------------------- Jump To Problem
I got stuck while parsing the `isDivisible` definition:
5| isDivisible 4 4 2
^
I am not sure what is going wrong exactly, so here is a valid definition (with
an optional type annotation) for reference:
greet : String -> String
greet name =
"Hello " ++ name ++ "!"
Try to use that format!
The Elm interpreter that CodeWars uses lets this pass through; it just says that the output is incorrect for some inputs (like 4 4 2). There are no Google results for "I got stuck while parsing the * definition:" (even though the parser is open-source, go figure). This is my first time in a functional language. What's wrong?
I'm not sure why your isDivisible function takes three numbers, but the syntax error you're seeing does not refer to its definition, but to your call:
isDivisible 4 4 2
In Elm, all your expressions (like the above) need to live within functions. You cannot simply write them at the top level of your file. They need to be used in a context where Elm knows what to do with them.
Elm programs start executing from the main function. The main function might return different things depending on what you want to do, but the simplest use case is to return some HTML.
module Main exposing (main)
import Html exposing (text)
main =
text "Hello World"
Run in ellie
If you compile and open that in your browser, you'll see the text "Hello World" on the screen. Notice we placed our code under the main function, instead of writing them in the file directly.
With that in mind, you could do something like the following to show the output of your call:
main =
if isDivisible 4 4 2 then
text "It is divisible"
else
text "It is NOT divisible"
Run in ellie
If you just want to see the output of your call in the console instead, you can use the Debug.log function, like this:
main =
let
_ =
Debug.log "Is divisible?" (isDivisible 4 4 2)
in
text "Hello World"
Run in Ellie (see LOGS)

Why doesn't time.sleep run in parallel in a Tornado coroutine?

When I run this handler in a simple Tornado app and make two requests to it with curl, it doesn't run in parallel. It prints out "1 2 3 4 5 1 2 3 4 5", when I want it to print "1 1 2 2 3 3 4 4 5 5".
class SleepHandler(RequestHandler):
def get(self):
for i in range(5):
print(i)
time.sleep(1)
What am I doing wrong?
The reason for this is that time.sleep is a blocking function: it doesn’t allow control to return to the IOLoop so that other handlers can be run.
Of course, time.sleep is often just a placeholder in these examples, the point is to show what happens when something in a handler gets slow. No matter what the real code is doing, to achieve concurrency blocking code must be replaced with non-blocking equivalents. This means one of three things:
Find a coroutine-friendly equivalent. For time.sleep, use tornado.gen.sleep instead:
class CoroutineSleepHandler(RequestHandler):
#gen.coroutine
def get(self):
for i in range(5):
print(i)
yield gen.sleep(1)
When this option is available, it is usually the best approach. See the Tornado wiki for links to asynchronous libraries that may be useful.
Find a callback-based equivalent. Similar to the first option, callback-based libraries are available for many tasks, although they are slightly more complicated to use than a library designed for coroutines. These are typically used with tornado.gen.Task as an adapter:
class CoroutineTimeoutHandler(RequestHandler):
#gen.coroutine
def get(self):
io_loop = IOLoop.current()
for i in range(5):
print(i)
yield gen.Task(io_loop.add_timeout, io_loop.time() + 1)
Again, the Tornado wiki can be useful to find suitable libraries.
Run the blocking code on another thread. When asynchronous libraries are not available, concurrent.futures.ThreadPoolExecutor can be used to run any blocking code on another thread. This is a universal solution that can be used for any blocking function whether an asynchronous counterpart exists or not:
executor = concurrent.futures.ThreadPoolExecutor(8)
class ThreadPoolHandler(RequestHandler):
#gen.coroutine
def get(self):
for i in range(5):
print(i)
yield executor.submit(time.sleep, 1)
See the Asynchronous I/O chapter of the Tornado user’s guide for more on blocking and asynchronous functions.

What does LOCAL do in Postscript?

In Thinking in Postscript (pdf), Chapter 5, exercise 3 (pp. 64-65) asks the reader to refactor this code to not store any dictionary entries:
36 750 moveto /Times-Roman 24 selectfont
% works like “show”, leaving current point at proper location
/ushow
% linethickness lineposition (words) ushow -
{ %def
LOCAL begin
/text exch def
/linepos exch def
/linethick exch def
gsave
0 linepos rmoveto
text stringwidth rlineto
linethick setlinewidth stroke
grestore
text show
end
} dup 0 4 dict put def
0.5 -4 (test underlined text) ushow
My question is about LOCAL. Ghostscript runs this code without error, and yet LOCAL is not:
Defined in the exercise
Documented in the Postcript Language Reference, third edition
Documented in PostScript Language Tutorial and Cookbook
What, in PostScript, is LOCAL?
It is nothing defined. The code is a bit sneaky as the code dup 0 4 dict put def will take the executable and replace the LOCAL with the result of 4 dict. The executable block (stuff between {}) is copied mainly because put returns nothing. Since its a reference to the same block your left over with
/ushow {-dict- begin ...rest of the executable...} def
This is all valid because LOCAL is never used anywhere (it is destroyed before its used). It would not matter what you use in place of LOCAL.
As joojaa correctly explains, LOCAL is not defined to anything which is ok since it is replaced before executing. It parses as an executable name during construction of the procedure body (array) and its use here is just to allocate a slot in the array. It could actually be any type, and I've often seen (and written) { 0 begin ...} for the same purpose. Using a name lets you give more semantic information to a human reader of the code. I've also seen it written { DICT begin ... } Here in my matrix functions, I called it STATICDICT, apparently.
There is a convention of using all upper-case for any meta-syntactical tokens like this. It is a nametype token, but meta-syntactically, it refers to a dicttype object to be filled-in later. There's no need (nor even any mechanism) to declare what you're doing for the benefit of the interpreter, but there is much to be gained by preferring DICT over 0. Again, since it will be completely replaced, you could also use a literal name /LOCAL to try to, idunno, relieve the next noob to read your code from the wild-goose-chase of looking for where LOCAL is defined?? To this end, I've also written simply DUMMY for token to-be-filled-in-later. I suppose the choice among these terms is a matter of style or audience or some other intangible quality. sigh... or just a matter of context.
There is another style that works well for making dynamic substitutions in procedure bodies. By placing the dictionary on the dictstack and naming it (within itself, so it's a closed namespace), we can refer to it with an //immediate name
4 dict begin
/mydict currentdict def
/proc {
//mydict begin
...
end
}
and then remove the dictionary before defining.
end def
Thus defining the procedure normally (in the outer-level dictionary (unnamed here, presumably userdict)), but with the dictionary embedded by name, from having been available by that name while the procedure body was scanned.
This can be extended to more procedures sharing the same private dictionary by juggling the dict off of the stack for each definition.
/enddefbegin { currentdict 3 1 roll end def begin } def
4 dict begin
/mydict currentdict def
/proc1 {
//mydict begin
...
end
} enddefbegin
/proc2 {
//mydict begin
...
end
} enddefbegin
end
The enddefbegin end at the end can of course be simplified to end def.
One caveat. The dictionary created this way is recursively contained with itself. Do not try to print it with ghostscript's === operator!
Pg 133 of the "Blue Book" has a slightly easier example of the same technique:
/sampleproc
{ 0 begin
/localvariable 6 def
end
} def
/sampleproc load 0 1 dict put
Here the procedure is defined before it is modified. It's a little easier to wrap your mind around. In the original post, the trickiest part for me was the "dup" because I didn't realize that the array on the stack is not an array precisely, it's an array reference (I was thinking copy-by-value, it functions copy-by-reference), so the "put" in the original code affects the array with the first reference (which is consequently consumed from the stack), and the second is used to define the procedure. It was a Newbie mistake, but maybe other newbies can learn from it:
Stack Progression:
... % fast forward
1. ushow --array-- --array-- 0 4 dict | put def % dict creates a dictionary
2. ushow --array-- --array-- 0 --dict-- | put def % put arrives on stack
3. ushow --array-- --array-- 0 --dict-- put | def % put consumes the array 0 and dict
4. ushow --array-- | def % def arrives on stack
5. ushow --array-- def % def consumes the remaining tokens
6.
Sorry for what is probably incorrect notation, I just stared at this for a while, and figured I might be able to save someone a little stare-time. Please let me know if there are any errors or misleading statements that I should fix.

Resources