Incrementally increasing volume in Bash - bash

I'm making an alarm clock and wanted to start at basically no volume and increase the sound per 2 seconds up one 'notch'/value until a certain predefined point where it won't increase anymore.
As of right now I'm using mplayer (it's a radio station, so I'm running mplayer http://66.225.205.192:80), but I don't care what I use (VLC, etc.))
My full code is
while true; do
mplayer http://66.225.205.192:80
sleep 1
done

Googling for 'mplayer alarm clock' actually yields a lot of pages dealing with this problem and solutions that you can actually use right away, but let's give it a try anyway.
#!/bin/bash
{
for ((volume = 0; volume <= 100; volume += 5)); do
/usr/bin/aumix -v${volume} -w100 >/dev/null
sleep 2
done
} &
mplayer http://66.225.205.192:80
echo "good morning! :-)"
You need to install aumix, which is used here to change the volume (but you could use something else, of course). The block between { } gets run in the background. The aumix command sets the PCM volume to 100% and gradually adjusts the main volume in 5 percent increments every two seconds, once it hits 100% the loop finishes and the background job exits.
I have never used aumix, and you might want to read its man page in case it does not work as expected (this is untested).
mplayer runs in the foreground until you quit it, upon which it makes coffee for you greets you with a warm welcome.
Does that get you started?

Related

stm32f030 doesn't go to sleep

I want to enter the sleep mode with WFI on a stm32f030 (cortex M0).
However my code doesn't seem to work on the stm32f030 but works on an stm32f103.
I think it works because when trying to flash again the f103 (with stlink utility or keil) it doesn't respond and I have to connect under reset which tends to indicate that the cpu is sleeping. But I can connect without problem the f030.
Here is my code:
int main() {
SetupSleep();
__wfi();
while(1){}
}
Here is the content of my SetupSleep() function:
void SetupSleep(void){
SCB->SCR |= (1ul << 1);
SCB->SCR &= ~(1ul << 2);
}
Which according to the page 81 of the f030 programming manual (http://www.st.com/web/en/resource/technical/document/programming_manual/DM00051352.pdf) selects Sleep mode and Sleeponexit.
Does it mean an interrupt occurs that makes the cpu exiting sleep mode ?
It is my first time using the sleep mode so maybe my implementation is not correct.
Instead of manipulating the registers directly, take a look at what the standard peripheral library does. In particular, look at PWR_EnterSleepMode() in stm32f0xx_pwr.c.
At the very least I can see that you're not executing either __WFI() or __WFE() to actually enter sleep mode. There are also the other low power modes: standby and stop that may be of interest to you.

Using pipes in bash to buffer data from a serial device

I have a script that looks something like:
while true; do
read -t10 -d$'\n' input_from_serial_device </dev/ttyS0
# do some costly processing on the string
done
The problem is that it will miss the next input from the serial device because it is burning CPU cycles doing the costly string processing.
I thought I could fix this by using a pipe, on the principle that bash will buffer the input between the two processes:
( while true; do
read -d$'\n' input_from_serial_device </dev/ttyS0
echo $input_from_serial_device
done ) | ( while true; do
read -t10 input_from_first_process
# costly string processing
done )
I firstly want to check that I've understood the pipes correctly and that this will indeed buffer the input between the two processes as I intended. Is this idea correct?
Secondly, if I get the input I'm looking for in the second process, is there a way to immediately kill both processes, rather than exiting from the second and waiting for the next input before exiting the first?
Finally, I realise bash isn't the best way to do this and I'm currently working on a C program, but I'd quite like to get this working as an intermediate solution.
Thank you!
The problem isn't the pipe. It's the serial device.
When you write
while true; do
read -t10 -d$'\n' input_from_serial_device </dev/ttyS0
# use a lot of time
done
the consequence is that the serial device is opened, a line is read from it, and it is then closed. Then it is not opened again until # use a lot of time is done. While a serial device is not open, incoming serial input is thrown away.
If the input is truly coming in faster than it can be processed, then buffering isn't enough. You'll have to throw input away. If, on the other hand, it's dribbling in at an average speed which allows for processing, then you should be able to achieve what you want by keeping the serial device open:
while true; do
read -t10 -r input_from_serial_device
# process input_from_serial_device
done < /dev/ttyS0
Note: I added -r -- almost certainly necessary -- to your read call, and removed -d$'\n', because that is the default.

How high do X11 display numbers go?

The displayno is part of the X11 display name.
I have seen several definitions that explain it is a number from 0 upwards, but I haven't seen any documents that explain if there is a maximum display number.
What is the highest display number? Where is it defined?
The background for this question is that I am trying to understand the Display number allocation algorithm of PyVirtualDisplay. I haven't understood the role of the /tmp/.X*lock files yet, but it looks like the allocation routine will choose always increasing display numbers, suggesting at some stage of repeatedly being invoked it might hit the limit and fall over, especially if it is small.
Short answer: it's not well defined.
Longer answer: it depends on the stream protocol you happen to be using. In TCP it happens to be simply added to the base port number of 6000, which means the server will fail to launch somewhere around display number 59535. Over unix domain sockets it's just an integer appended to the socket name under /tmp/.X11-unix (so if you're launching the server with -nolisten tcp you can have a few billion or so). In DECnet... well, I don't know, but if you ever find yourself in a situation to care, I'm very sorry.
Possibly better answer for posterity: if you're using a sufficiently new X server, you can use the -displayfd <n> argument to tell the server to simply pick an available display number, and write it back to you on that file descriptor. Think that's new in xserver 1.13, which should be out late 2012.
2147483647 which is 2**31 - 1
Xephyr :2147483647
Xephyr :2147483648 # Bad display name
found with brute force:
for ((i=4153577566; i > 0; i -= 10000000 )); do echo $i; Xephyr :$i 2>/dev/null && break; done
for ((i=2153577566; i > 0; i -= 100000 )); do echo $i; Xephyr :$i 2>/dev/null && break; done
for ((i=2147577566; i > 0; i -= 1000 )); do echo $i; Xephyr :$i 2>/dev/null && break; done
...

Self-restarting MathKernel - is it possible in Mathematica?

This question comes from the recent question "Correct way to cap Mathematica memory use?"
I wonder, is it possible to programmatically restart MathKernel keeping the current FrontEnd process connected to new MathKernel process and evaluating some code in new MathKernel session? I mean a "transparent" restart which allows a user to continue working with the FrontEnd while having new fresh MathKernel process with some code from the previous kernel evaluated/evaluating in it?
The motivation for the question is to have a way to automatize restarting of MathKernel when it takes too much memory without breaking the computation. In other words, the computation should be automatically continued in new MathKernel process without interaction with the user (but keeping the ability for user to interact with the Mathematica as it was originally). The details on what code should be evaluated in new kernel are of course specific for each computational task. I am looking for a general solution how to automatically continue the computation.
From a comment by Arnoud Buzing yesterday, on Stack Exchange Mathematica chat, quoting entirely:
In a notebook, if you have multiple cells you can put Quit in a cell by itself and set this option:
SetOptions[$FrontEnd, "ClearEvaluationQueueOnKernelQuit" -> False]
Then if you have a cell above it and below it and select all three and evaluate, the kernel will Quit but the frontend evaluation queue will continue (and restart the kernel for the last cell).
-- Arnoud Buzing
The following approach runs one kernel to open a front-end with its own kernel, which is then closed and reopened, renewing the second kernel.
This file is the MathKernel input, C:\Temp\test4.m
Needs["JLink`"];
$FrontEndLaunchCommand="Mathematica.exe";
UseFrontEnd[
nb = NotebookOpen["C:\\Temp\\run.nb"];
SelectionMove[nb, Next, Cell];
SelectionEvaluate[nb];
];
Pause[8];
CloseFrontEnd[];
Pause[1];
UseFrontEnd[
nb = NotebookOpen["C:\\Temp\\run.nb"];
Do[SelectionMove[nb, Next, Cell],{12}];
SelectionEvaluate[nb];
];
Pause[8];
CloseFrontEnd[];
Print["Completed"]
The demo notebook, C:\Temp\run.nb contains two cells:
x1 = 0;
Module[{},
While[x1 < 1000000,
If[Mod[x1, 100000] == 0, Print["x1=" <> ToString[x1]]]; x1++];
NotebookSave[EvaluationNotebook[]];
NotebookClose[EvaluationNotebook[]]]
Print[x1]
x1 = 0;
Module[{},
While[x1 < 1000000,
If[Mod[x1, 100000] == 0, Print["x1=" <> ToString[x1]]]; x1++];
NotebookSave[EvaluationNotebook[]];
NotebookClose[EvaluationNotebook[]]]
The initial kernel opens a front-end and runs the first cell, then it quits the front-end, reopens it and runs the second cell.
The whole thing can be run either by pasting (in one go) the MathKernel input into a kernel session, or it can be run from a batch file, e.g. C:\Temp\RunTest2.bat
#echo off
setlocal
PATH = C:\Program Files\Wolfram Research\Mathematica\8.0\;%PATH%
echo Launching MathKernel %TIME%
start MathKernel -noprompt -initfile "C:\Temp\test4.m"
ping localhost -n 30 > nul
echo Terminating MathKernel %TIME%
taskkill /F /FI "IMAGENAME eq MathKernel.exe" > nul
endlocal
It's a little elaborate to set up, and in its current form it depends on knowing how long to wait before closing and restarting the second kernel.
Perhaps the parallel computation machinery could be used for this? Here is a crude set-up that illustrates the idea:
Needs["SubKernels`LocalKernels`"]
doSomeWork[input_] := {$KernelID, Length[input], RandomReal[]}
getTheJobDone[] :=
Module[{subkernel, initsub, resultSoFar = {}}
, initsub[] :=
( subkernel = LaunchKernels[LocalMachine[1]]
; DistributeDefinitions["Global`"]
)
; initsub[]
; While[Length[resultSoFar] < 1000
, DistributeDefinitions[resultSoFar]
; Quiet[ParallelEvaluate[doSomeWork[resultSoFar], subkernel]] /.
{ $Failed :> (Print#"Ouch!"; initsub[])
, r_ :> AppendTo[resultSoFar, r]
}
]
; CloseKernels[subkernel]
; resultSoFar
]
This is an over-elaborate setup to generate a list of 1,000 triples of numbers. getTheJobDone runs a loop that continues until the result list contains the desired number of elements. Each iteration of the loop is evaluated in a subkernel. If the subkernel evaluation fails, the subkernel is relaunched. Otherwise, its return value is added to the result list.
To try this out, evaluate:
getTheJobDone[]
To demonstrate the recovery mechanism, open the Parallel Kernel Status window and kill the subkernel from time-to-time. getTheJobDone will feel the pain and print Ouch! whenever the subkernel dies. However, the overall job continues and the final result is returned.
The error-handling here is very crude and would likely need to be bolstered in a real application. Also, I have not investigated whether really serious error conditions in the subkernels (like running out of memory) would have an adverse effect on the main kernel. If so, then perhaps subkernels could kill themselves if MemoryInUse[] exceeded a predetermined threshold.
Update - Isolating the Main Kernel From Subkernel Crashes
While playing around with this framework, I discovered that any use of shared variables between the main kernel and subkernel rendered Mathematica unstable should the subkernel crash. This includes the use of DistributeDefinitions[resultSoFar] as shown above, and also explicit shared variables using SetSharedVariable.
To work around this problem, I transmitted the resultSoFar through a file. This eliminated the synchronization between the two kernels with the net result that the main kernel remained blissfully unaware of a subkernel crash. It also had the nice side-effect of retaining the intermediate results in the event of a main kernel crash as well. Of course, it also makes the subkernel calls quite a bit slower. But that might not be a problem if each call to the subkernel performs a significant amount of work.
Here are the revised definitions:
Needs["SubKernels`LocalKernels`"]
doSomeWork[] := {$KernelID, Length[Get[$resultFile]], RandomReal[]}
$resultFile = "/some/place/results.dat";
getTheJobDone[] :=
Module[{subkernel, initsub, resultSoFar = {}}
, initsub[] :=
( subkernel = LaunchKernels[LocalMachine[1]]
; DistributeDefinitions["Global`"]
)
; initsub[]
; While[Length[resultSoFar] < 1000
, Put[resultSoFar, $resultFile]
; Quiet[ParallelEvaluate[doSomeWork[], subkernel]] /.
{ $Failed :> (Print#"Ouch!"; CloseKernels[subkernel]; initsub[])
, r_ :> AppendTo[resultSoFar, r]
}
]
; CloseKernels[subkernel]
; resultSoFar
]
I have a similar requirement when I run a CUDAFunction for a long loop and CUDALink ran out of memory (similar here: https://mathematica.stackexchange.com/questions/31412/cudalink-ran-out-of-available-memory). There's no improvement on the memory leak even with the latest Mathematica 10.4 version. I figure out a workaround here and hope that you may find it's useful. The idea is that you use a bash script to call a Mathematica program (run in batch mode) multiple times with passing parameters from the bash script. Here is the detail instruction and demo (This is for Window OS):
To use bash-script in Win_OS you need to install cygwin (https://cygwin.com/install.html).
Convert your mathematica notebook to package (.m) to be able to use in script mode. If you save your notebook using "Save as.." all the command will be converted to comments (this was noted by Wolfram Research), so it's better that you create a package (File->New-Package), then copy and paste your commands to that.
Write the bash script using Vi editor (instead of Notepad or gedit for window) to avoid the problem of "\r" (http://www.linuxquestions.org/questions/programming-9/shell-scripts-in-windows-cygwin-607659/).
Here is a demo of the test.m file
str=$CommandLine;
len=Length[str];
Do[
If[str[[i]]=="-start",
start=ToExpression[str[[i+1]]];
Pause[start];
Print["Done in ",start," second"];
];
,{i,2,len-1}];
This mathematica code read the parameter from a commandline and use it for calculation.
Here is the bash script (script.sh) to run test.m many times with different parameters.
#c:\cygwin64\bin\bash
for ((i=2;i<10;i+=2))
do
math -script test.m -start $i
done
In the cygwin terminal type "chmod a+x script.sh" to enable the script then you can run it by typing "./script.sh".
You can programmatically terminate the kernel using Exit[]. The front end (notebook) will automatically start a new kernel when you next try to evaluate an expression.
Preserving "some code from the previous kernel" is going to be more difficult. You have to decide what you want to preserve. If you think you want to preserve everything, then there's no point in restarting the kernel. If you know what definitions you want to save, you can use DumpSave to write them to a file before terminating the kernel, and then use << to load that file into the new kernel.
On the other hand, if you know what definitions are taking up too much memory, you can use Unset, Clear, ClearAll, or Remove to remove those definitions. You can also set $HistoryLength to something smaller than Infinity (the default) if that's where your memory is going.
Sounds like a job for CleanSlate.
<< Utilities`CleanSlate`;
CleanSlate[]
From: http://library.wolfram.com/infocenter/TechNotes/4718/
"CleanSlate, tries to do everything possible to return the kernel to the state it was in when the CleanSlate.m package was initially loaded."

I want to duplicate Folding (use extra cpu-cycles)

I want to use extra-cpu cycles to do some of my own processing, and I was wondering if someone could point me in the right direction as to how to get started on this?
I would suggest writing a program that runs continuously (make sure it blocks occasionally), and then simply setting it to a low priority. The OS Scheduler (Windows/*nix) should handle the rest automatically.
You can use extra CPU cycles by writing a program that runs in the background.
You can check the CPU usage to find out when the computer is idle (but it's not necessarily a good idea), or you can listen for mouse/keyboard activity.
To check CPU usage in C#, use the following code:
float cpuUsage; //Between 0 and 100
using (var cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total")) {
cpu.NextValue(); //First call gives wrong values
cpuUsage = cpu.NextValue();
}
To check for keyboard or mouse activity, you'll need to use a keyboard / mouse hook; see here for instructions.
Write an application. Set its thread priorities to "background". Job done ;)

Resources