Behavior of flatMap with different Schedulers in it - rx-java2

Could you explain why I am getting strange output when I change schedulers of the returned Observable in flatMap? For example, I have
Observable.range(1, 9)
.flatMap {
if (it < 5) {
Observable.just(it)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
} else {
Observable.just(it)
}
}
.subscribe({ println("${it}: ${Thread.currentThread().name}") })
println("END")
Thread.sleep(200)
As output I have different results on each run. E.g.
The first launch
1: RxCachedThreadScheduler-3
2: RxCachedThreadScheduler-3
3: RxCachedThreadScheduler-3
5: main
6: main
7: main
END
4: RxCachedThreadScheduler-6
8: RxCachedThreadScheduler-6
9: RxCachedThreadScheduler-6
The second launch outputs this:
5: main
1: main
2: main
3: main
6: main
7: main
8: main
9: main
END
4: RxCachedThreadScheduler-8

flatMap merges on one of the participating thread non-deterministically, thus even if the inner sources have subscribeOn and/or observeOn defined, there is no guarantee which thread will win at a particular moment to emit items from the sources. Therefore, you have to apply observeOn after flatMap if you want to ensure subsequent event processing happens on the desired thread (until there is another async boundary operator).

Related

How to repeat each test with a delay if a particular Exception happens (pytest)

I have a load of test which I want to rerun if there is a particular exception. The reason for this is that I am running real API calls to a server and sometimes I hit the rate limit for the API, in which case I want to wait and try again.
However, I am also using a pytest fixture to make each test is run several times, because I am sending requests to different servers (the actual use case is different cryptocurrency exchanges).
Using pytest-rerunfailures comes very close to what I need...apart from that I can't see how to look at the exception of the last test run in the condition.
Below is some code which shows what I am trying to achieve, but I don't want to write code like this for every test obviously.
#pytest_asyncio.fixture(
params=EXCHANGE_NAMES,
)
async def client(request):
exchange_name = request.param
exchange_client = get_exchange_client(exchange_name)
return exchange_client
def test_something(client):
test_something.count += 1
### This block is the code I want to
try:
result = client.do_something()
except RateLimitException:
test_something.count
if test_something.count <= 3:
sleep_duration = get_sleep_duration(client)
time.sleep(sleep_duration)
# run the same test again
test_something()
else:
raise
expected = [1,2,3]
assert result == expected
You can use the retry library to wrap your actual code in:
#pytest_asyncio.fixture(
params=EXCHANGE_NAMES,
autouse=True,
)
async def client(request):
exchange_name = request.param
exchange_client = get_exchange_client(exchange_name)
return exchange_client
def test_something(client):
actual_test_something(client)
#retry(RateLimitException, tries=3, delay=2)
def actual_test_something(client):
'''Retry on RateLimitException, raise error after 3 attempts, sleep 2 seconds between attempts.'''
result = client.do_something()
expected = [1,2,3]
assert result == expected
The code looks much cleaner this way.

Obtaining register address in STM32

I have a simple code for preserving and later using register address:
PWMChannel::PWMChannel(TIM_HandleTypeDef *timer, int channel)
{
switch(channel)
{
case 1: ccr = &(timer->Instance->CCR1); break;
case 2: ccr = &(timer->Instance->CCR2); break;
case 3: ccr = &(timer->Instance->CCR3); break;
case 4: ccr = &(timer->Instance->CCR4); break;
case 5: ccr = &(timer->Instance->CCR5); break;
case 6: ccr = &(timer->Instance->CCR6); break;
}
}
Where ccr is a private class member: uint32_t *ccr = nullptr;
It is used to change duty cycle like this: *ccr = duty;
The code above worked just fine some time ago when I was using System Workbench. Recently I switched to CubeIDE. The only issue with porting project to new toolchain was with this member definition - it now required "volatile", so I changed it to: volatile uint32_t *ccr = nullptr;
However the code stopped working. The debugging shows that with channel parameter = 4 the ccr value becomes 0x40. Now, 0x40 is an offset of CCR4 within TIM_TypeDef structure (referenced by Instance), not an actual address of CCR4. If this is how it supposed to be then why it worked before and how do I change the code to make it work again?
OK, I think I figured out what happened.
The object in question is statically initialized. Somehow this initialization happened after MX_TIM1_Init() call (in main.c) when I was building under System Workbench and before that call when I was building under CubeIDE. The "Instance" field is not yet initialized by the time constructor called, so it got wrong register address.
This is not the first time order of initialization bites me... :(
I already have most of the global objects either dynamically allocated or hidden behind functions in singleton pattern. Did not want to do it for this tiny helper object.
If somebody thinks this question is useless, tell me and I'll delete it.

Powershell to get IIS application initialization status

My site has doAppInitAfterRestart set to true and is working, but I'd like to know when the application has completed it's initialization.
Is there a way through powershell and WMI to know when the site's application initialization is completed?
Try below mentioned VB Script code. I have scraped this code from one of my working script , if you see any error, shoot a comment.
iis_con= "localhost"
set WMI_IIS = GetObject( "IIS://" & iis_con & "/W3SVC" )
if WMI_IIS.count = 0 then
' do nothing
else
for each objitem in WMI_IIS
if objitem.class = "IIsWebServer" then
Select Case objItem.serverstate
Case 1: wscript.echo("Starting")
Case 2: wscript.echo("Running")
Case 3: wscript.echo("Stopping")
Case 4: wscript.echo("Stopped")
Case 5: wscript.echo("Pausing")
Case 6: wscript.echo("Paused")
Case 7: wscript.echo("Continuing")
Case Default: wscript.echo("Unknown")
End Select
Next
end if

How can I use goto in a switch statement in Objective-C?

In my code I need to be able to jump (goto) a different case within the same switch statement. Is there a way to do this?
My code is something like this: (There is a lot of code I just left it all out)
switch (viewNumber) {
case 500:
// [...]
break;
case 501:
// [...]
break;
.
.
.
.
.
case 510:
// [...]
break;
default:
break;
}
Thank you for your time!
-Jeff
It's generally very bad practice to unconditionally jump like you're asking.
I think a more readable/maintainable solution would be to place the shared code in a method and have multiple cases call the method.
If you really want to, you can use goto to do something like:
switch(viewNumber) {
case 500:
// [...]
goto jumpLabel;
case 501:
// [...]
break;
case 502:
// [...]
jumpLabel:
// Code that 500 also will execute
break;
default:break;
}
Note: I only provided the code example above to answer your question. I now feel so dirty I might have to buy some Bad Code Offsets.
Instead of using goto, refactor your code so that the two (or more) cases that use common code instead call it in a common method.
Something like:
switch (value) {
case (firstValue):
// ...
break;
case (secondValue):
[self doSharedCodeForSecondAndThirdValues];
break;
case (thirdValue):
[self doSharedCodeForSecondAndThirdValues];
break;
default:
break;
}
// ...
- (void) doSharedCodeForSecondAndThirdValues {
// do stuff here that is common to second and third value cases
}
It wouldn't be the end of the world to use goto, though it is bad practice.
The practical reason for avoiding use of goto is that you have to search through your swtich-case tree to find that goto label.
If your switch logic changes, you'll have a messy situation on your hands.
If you pull out common code to its own method, the code is easier to read, debug and extend.
You should probably try rewrite your code, like a recursive call or just factor out common stuff and call a separate function. But as a fix and quick answer to your question you could put a label before your switch and goto it, like so
switchLabel:
switch(viewNumber) {
case 500: {
viewNumber = 501;
goto switchLabel;
}
}
Not sure of the Objective-C syntax here, but you could also try a variation thereof
int lastView = 0;
while (lastView != viewNumber)
switch(lastView = viewNumber) {
case 500: {
viewNumber = 501;
break;
}
}
which will keep on looping until the viewNumber doesn't change any more. This is still pretty much just a pretty-looking goto though.
And since we're doing gotos you could just goto into another case, as pointed out already. You could also do fancy stuff similar to Duff's device, by putting cases inside of other blocks. But that's just mad.. :)
[I'm making this answer community wiki because this doesn't actually answer the question per se]
As others have said, this is very bad style, and makes for unreadable code...
Alternatives:
Factor the common code into a separate function, and call that in 2 places.
Use fallthroughs, leave off the the break on a case and it falls through to the next one (remember, cases don't have to be in numerical order!)
if you only want part of a case to be done in the other case, protect it with an if:
as in
case 500:
.
.
.
case 501:
if(viewNumber == 501) {
.
.
.
}
.
.
.
break;

Best way to detect an application crash and restart it?

What's the best way to detect an application crash in XP (produces the same pair of 'error' windows each time - each with same window title) and then restart it?
I'm especially interested to hear of solutions that use minimal system resources as the system in question is quite old.
I had thought of using a scripting language like AutoIt (http://www.autoitscript.com/autoit3/), and perhaps triggering a 'detector' script every few minutes?
Would this be better done in Python, Perl, PowerShell or something else entirely?
Any ideas, tips, or thoughts much appreciated.
EDIT: It doesn't actually crash (i.e. exit/terminate - thanks #tialaramex). It displays a dialog waiting for user input, followed by another dialog waiting for further user input, then it actually exits. It's these dialogs that I'd like to detect and deal with.
Best way is to use a named mutex.
Start your application.
Create a new named mutex and take ownership over it
Start a new process (process not thread) or a new application, what you preffer.
From that process / application try to aquire the mutex. The process will block
When application finish release the mutex (signal it)
The "control" process will only aquire the mutex if either the application finishes or the application crashes.
Test the resulting state after aquiring the mutex. If the application had crashed it will be WAIT_ABANDONED
Explanation: When a thread finishes without releasing the mutex any other process waiting for it can aquire it but it will obtain a WAIT_ABANDONED as return value, meaning the mutex is abandoned and therfore the state of the section it was protected can be unsafe.
This way your second app won't consume any CPU cycles as it will keep waiting for the mutex (and that's enterely handled by the operating system)
How about creating a wrapper application that launches the faulty app as a child and waits for it? If the exit code of the child indicates an error, then restart it, else exit.
I think the main problem is that Dr. Watson displays a dialog
and keeps your process alive.
You can write your own debugger using the Windows API and
run the crashing application from there.
This will prevent other debuggers from catching the crash of
your application and you could also catch the Exception event.
Since I have not found any sample code, I have written this
Python quick-and-dirty sample. I am not sure how robust it is
especially the declaration of DEBUG_EVENT could be improved.
from ctypes import windll, c_int, Structure
import subprocess
WaitForDebugEvent = windll.kernel32.WaitForDebugEvent
ContinueDebugEvent = windll.kernel32.ContinueDebugEvent
DBG_CONTINUE = 0x00010002L
DBG_EXCEPTION_NOT_HANDLED = 0x80010001L
event_names = {
3: 'CREATE_PROCESS_DEBUG_EVENT',
2: 'CREATE_THREAD_DEBUG_EVENT',
1: 'EXCEPTION_DEBUG_EVENT',
5: 'EXIT_PROCESS_DEBUG_EVENT',
4: 'EXIT_THREAD_DEBUG_EVENT',
6: 'LOAD_DLL_DEBUG_EVENT',
8: 'OUTPUT_DEBUG_STRING_EVENT',
9: 'RIP_EVENT',
7: 'UNLOAD_DLL_DEBUG_EVENT',
}
class DEBUG_EVENT(Structure):
_fields_ = [
('dwDebugEventCode', c_int),
('dwProcessId', c_int),
('dwThreadId', c_int),
('u', c_int*20)]
def run_with_debugger(args):
proc = subprocess.Popen(args, creationflags=1)
event = DEBUG_EVENT()
while True:
if WaitForDebugEvent(pointer(event), 10):
print event_names.get(event.dwDebugEventCode,
'Unknown Event %s' % event.dwDebugEventCode)
ContinueDebugEvent(event.dwProcessId, event.dwThreadId, DBG_CONTINUE)
retcode = proc.poll()
if retcode is not None:
return retcode
run_with_debugger(['python', 'crash.py'])
I realize that you're dealing with Windows XP, but for people in a similar situation under Vista, there are new crash recovery APIs available. Here's a good introduction to what they can do.
Here is a slightly improved version.
In my test the previous code run in an infinite loop when the faulty exe generated an "access violation".
I'm not totally satisfied by my solution because I have no clear criteria to know which exception should be continued and which one couldn't be (The ExceptionFlags is of no help).
But it works on the example I run.
Hope it helps,
Vivian De Smedt
from ctypes import windll, c_uint, c_void_p, Structure, Union, pointer
import subprocess
WaitForDebugEvent = windll.kernel32.WaitForDebugEvent
ContinueDebugEvent = windll.kernel32.ContinueDebugEvent
DBG_CONTINUE = 0x00010002L
DBG_EXCEPTION_NOT_HANDLED = 0x80010001L
event_names = {
1: 'EXCEPTION_DEBUG_EVENT',
2: 'CREATE_THREAD_DEBUG_EVENT',
3: 'CREATE_PROCESS_DEBUG_EVENT',
4: 'EXIT_THREAD_DEBUG_EVENT',
5: 'EXIT_PROCESS_DEBUG_EVENT',
6: 'LOAD_DLL_DEBUG_EVENT',
7: 'UNLOAD_DLL_DEBUG_EVENT',
8: 'OUTPUT_DEBUG_STRING_EVENT',
9: 'RIP_EVENT',
}
EXCEPTION_MAXIMUM_PARAMETERS = 15
EXCEPTION_DATATYPE_MISALIGNMENT = 0x80000002
EXCEPTION_ACCESS_VIOLATION = 0xC0000005
EXCEPTION_ILLEGAL_INSTRUCTION = 0xC000001D
EXCEPTION_ARRAY_BOUNDS_EXCEEDED = 0xC000008C
EXCEPTION_INT_DIVIDE_BY_ZERO = 0xC0000094
EXCEPTION_INT_OVERFLOW = 0xC0000095
EXCEPTION_STACK_OVERFLOW = 0xC00000FD
class EXCEPTION_DEBUG_INFO(Structure):
_fields_ = [
("ExceptionCode", c_uint),
("ExceptionFlags", c_uint),
("ExceptionRecord", c_void_p),
("ExceptionAddress", c_void_p),
("NumberParameters", c_uint),
("ExceptionInformation", c_void_p * EXCEPTION_MAXIMUM_PARAMETERS),
]
class EXCEPTION_DEBUG_INFO(Structure):
_fields_ = [
('ExceptionRecord', EXCEPTION_DEBUG_INFO),
('dwFirstChance', c_uint),
]
class DEBUG_EVENT_INFO(Union):
_fields_ = [
("Exception", EXCEPTION_DEBUG_INFO),
]
class DEBUG_EVENT(Structure):
_fields_ = [
('dwDebugEventCode', c_uint),
('dwProcessId', c_uint),
('dwThreadId', c_uint),
('u', DEBUG_EVENT_INFO)
]
def run_with_debugger(args):
proc = subprocess.Popen(args, creationflags=1)
event = DEBUG_EVENT()
num_exception = 0
while True:
if WaitForDebugEvent(pointer(event), 10):
print event_names.get(event.dwDebugEventCode, 'Unknown Event %s' % event.dwDebugEventCode)
if event.dwDebugEventCode == 1:
num_exception += 1
exception_code = event.u.Exception.ExceptionRecord.ExceptionCode
if exception_code == 0x80000003L:
print "Unknow exception:", hex(exception_code)
else:
if exception_code == EXCEPTION_ACCESS_VIOLATION:
print "EXCEPTION_ACCESS_VIOLATION"
elif exception_code == EXCEPTION_INT_DIVIDE_BY_ZERO:
print "EXCEPTION_INT_DIVIDE_BY_ZERO"
elif exception_code == EXCEPTION_STACK_OVERFLOW:
print "EXCEPTION_STACK_OVERFLOW"
else:
print "Other exception:", hex(exception_code)
break
ContinueDebugEvent(event.dwProcessId, event.dwThreadId, DBG_CONTINUE)
retcode = proc.poll()
if retcode is not None:
return retcode
run_with_debugger(['crash.exe'])