text:
# Asynchronous Programming

When a program needs to interact with the outside world, for example communicating with another machine over the internet, operations in the program may need to happen in an unpredictable order. Say your program needs to download a file. We would like to initiate the download operation, perform other operations while we wait for it to complete, and then resume the code that needs the downloaded file when it is available. This sort of scenario falls in the domain of asynchronous programming, sometimes also referred to as concurrent programming (since, conceptually, multiple things are happening at once).

To address these scenarios, Julia provides Tasks (also known by several other names, such as symmetric coroutines, lightweight threads, cooperative multitasking, or one-shot continuations). When a piece of computing work (in practice, executing a particular function) is designated as a Task, it becomes possible to interrupt it by switching to another Task. The original Task can later be resumed, at which point it will pick up right where it left off. At first, this may seem similar to a function call. However there are two key differences. First, switching tasks does not use any space, so any number of task switches can occur without consuming the call stack. Second, switching among tasks can occur in any order, unlike function calls, where the called function must finish executing before control returns to the calling function.

## Basic Task operations

You can think of a Task as a handle to a unit of computational work to be performed. It has a create-start-run-finish lifecycle. Tasks are created by calling the Task constructor on a 0-argument function to run, or using the @task macro:

julia> t = @task begin; sleep(5); println("done"); end
Task (runnable) @0x00007f13a40c0eb0

@task x is equivalent to Task(()->x).

This task will wait for five seconds, and then print done. However, it has not started running yet. We can run it whenever we're ready by calling schedule:

julia> schedule(t);

If you try this in the REPL, you will see that schedule returns immediately. That is because it simply adds t to an internal queue of tasks to run. Then, the REPL will print the next prompt and wait for more input. Waiting for keyboard input provides an opportunity for other tasks to run, so at that point t will start. t calls sleep, which sets a timer and stops execution. If other tasks have been scheduled, they could run then. After five seconds, the timer fires and restarts t, and you will see done printed. t is then finished.

The wait function blocks the calling task until some other task finishes. So for example if you type

julia> schedule(t); wait(t)

instead of only calling schedule, you will see a five second pause before the next input prompt appears. That is because the REPL is waiting for t to finish before proceeding.

It is common to want to create a task and schedule it right away, so the macro @async is provided for that purpose –- @async x is equivalent to schedule(@task x).

## Communicating with Channels

In some problems, the various pieces of required work are not naturally related by function calls; there is no obvious "caller" or "callee" among the jobs that need to be done. An example is the producer-consumer problem, where one complex procedure is generating values and another complex procedure is consuming them. The consumer cannot simply call a producer function to get a value, because the producer may have more values to generate and so might not yet be ready to return. With tasks, the producer and consumer can both run as long as they need to, passing values back and forth as necessary.

Julia provides a Channel mechanism for solving this problem. A Channel is a waitable first-in first-out queue which can have multiple tasks reading from and writing to it.

Let's define a producer task, which produces values via the put! call. To consume values, we need to schedule the producer to run in a new task. A special Channel constructor which accepts a 1-arg function as an argument can be used to run a task bound to a channel. We can then take! values repeatedly from the channel object:

julia> function producer(c::Channel)
put!(c, "start")
for n=1:4
put!(c, 2n)
end
put!(c, "stop")
end;

julia> chnl = Channel(producer);

julia> take!(chnl)
"start"

julia> take!(chnl)
2

julia> take!(chnl)
4

julia> take!(chnl)
6

julia> take!(chnl)
8

julia> take!(chnl)
"stop"

One way to think of this behavior is that producer was able to return multiple times. Between calls to put!, the producer's execution is suspended and the consumer has control.

The returned Channel can be used as an iterable object in a for loop, in which case the loop variable takes on all the produced values. The loop is terminated when the channel is closed.

julia> for x in Channel(producer)
println(x)
end
start
2
4
6
8
stop

Note that we did not have to explicitly close the channel in the producer. This is because the act of binding a Channel to a Task associates the open lifetime of a channel with that of the bound task. The channel object is closed automatically when the task terminates. Multiple channels can be bound to a task, and vice-versa.

While the Task constructor expects a 0-argument function, the Channel method that creates a task-bound channel expects a function that accepts a single argument of type Channel. A common pattern is for the producer to be parameterized, in which case a partial function application is needed to create a 0 or 1 argument anonymous function.

For Task objects this can be done either directly or by use of a convenience macro:

function mytask(myarg)
...
end

taskHdl = Task(() -> mytask(7))
# or, equivalently
taskHdl = @task mytask(7)

To orchestrate more advanced work distribution patterns, bind and schedule can be used in conjunction with Task and Channel constructors to explicitly link a set of channels with a set of producer/consumer tasks.

### More on Channels

A channel can be visualized as a pipe, i.e., it has a write end and a read end :

• Multiple writers in different tasks can write to the same channel concurrently via put! calls.

• Multiple readers in different tasks can read data concurrently via take! calls.

• As an example:

# Given Channels c1 and c2,
c1 = Channel(32)
c2 = Channel(32)

# and a function foo which reads items from c1, processes the item read
# and writes a result to c2,
function foo()
while true
data = take!(c1)
[...]               # process data
put!(c2, result)    # write out result
end
end

# we can schedule n instances of foo to be active concurrently.
for _ in 1:n
@async foo()
end
• Channels are created via the Channel{T}(sz) constructor. The channel will only hold objects of type T. If the type is not specified, the channel can hold objects of any type. sz refers to the maximum number of elements that can be held in the channel at any time. For example, Channel(32) creates a channel that can hold a maximum of 32 objects of any type. A Channel{MyType}(64) can hold up to 64 objects of MyType at any time.

• If a Channel is empty, readers (on a take! call) will block until data is available.

• If a Channel is full, writers (on a put! call) will block until space becomes available.

• isready tests for the presence of any object in the channel, while wait waits for an object to become available.

• A Channel is in an open state initially. This means that it can be read from and written to freely via take! and put! calls. close closes a Channel. On a closed Channel, put! will fail. For example:

julia> c = Channel(2);

julia> put!(c, 1) # put! on an open channel succeeds
1

julia> close(c);

julia> put!(c, 2) # put! on a closed channel throws an exception.
ERROR: InvalidStateException("Channel is closed.",:closed)
Stacktrace:
[...]
• take! and fetch (which retrieves but does not remove the value) on a closed channel successfully return any existing values until it is emptied. Continuing the above example:

julia> fetch(c) # Any number of fetch calls succeed.
1

julia> fetch(c)
1

julia> take!(c) # The first take! removes the value.
1

julia> take!(c) # No more data available on a closed channel.
ERROR: InvalidStateException("Channel is closed.",:closed)
Stacktrace:
[...]

Consider a simple example using channels for inter-task communication. We start 4 tasks to process data from a single jobs channel. Jobs, identified by an id (job_id), are written to the channel. Each task in this simulation reads a job_id, waits for a random amount of time and writes back a tuple of job_id and the simulated time to the results channel. Finally all the results are printed out.

julia> const jobs = Channel{Int}(32);

julia> const results = Channel{Tuple}(32);

julia> function do_work()
for job_id in jobs
exec_time = rand()
sleep(exec_time)                # simulates elapsed time doing actual work
# typically performed externally.
put!(results, (job_id, exec_time))
end
end;

julia> function make_jobs(n)
for i in 1:n
put!(jobs, i)
end
end;

julia> n = 12;

julia> @async make_jobs(n); # feed the jobs channel with "n" jobs

julia> for i in 1:4 # start 4 tasks to process requests in parallel
@async do_work()
end

julia> @elapsed while n > 0 # print out results
job_id, exec_time = take!(results)
println("$job_id finished in$(round(exec_time; digits=2)) seconds")
global n = n - 1
end
4 finished in 0.22 seconds
3 finished in 0.45 seconds
1 finished in 0.5 seconds
7 finished in 0.14 seconds
2 finished in 0.78 seconds
5 finished in 0.9 seconds
9 finished in 0.36 seconds
6 finished in 0.87 seconds
8 finished in 0.79 seconds
10 finished in 0.64 seconds
12 finished in 0.5 seconds
11 finished in 0.97 seconds
0.029772311

## More task operations

Task operations are built on a low-level primitive called yieldto. yieldto(task, value) suspends the current task, switches to the specified task, and causes that task's last yieldto call to return the specified value. Notice that yieldto is the only operation required to use task-style control flow; instead of calling and returning we are always just switching to a different task. This is why this feature is also called "symmetric coroutines"; each task is switched to and from using the same mechanism.

yieldto is powerful, but most uses of tasks do not invoke it directly. Consider why this might be. If you switch away from the current task, you will probably want to switch back to it at some point, but knowing when to switch back, and knowing which task has the responsibility of switching back, can require considerable coordination. For example, put! and take! are blocking operations, which, when used in the context of channels maintain state to remember who the consumers are. Not needing to manually keep track of the consuming task is what makes put! easier to use than the low-level yieldto.

In addition to yieldto, a few other basic functions are needed to use tasks effectively.

## Tasks and events

Most task switches occur as a result of waiting for events such as I/O requests, and are performed by a scheduler included in Julia Base. The scheduler maintains a queue of runnable tasks, and executes an event loop that restarts tasks based on external events such as message arrival.

The basic function for waiting for an event is wait. Several objects implement wait; for example, given a Process object, wait will wait for it to exit. wait is often implicit; for example, a wait can happen inside a call to read to wait for data to be available.

In all of these cases, wait ultimately operates on a Condition object, which is in charge of queueing and restarting tasks. When a task calls wait on a Condition, the task is marked as non-runnable, added to the condition's queue, and switches to the scheduler. The scheduler will then pick another task to run, or block waiting for external events. If all goes well, eventually an event handler will call notify on the condition, which causes tasks waiting for that condition to become runnable again.

A task created explicitly by calling Task is initially not known to the scheduler. This allows you to manage tasks manually using yieldto if you wish. However, when such a task waits for an event, it still gets restarted automatically when the event happens, as you would expect.


text:
Change the chapter
Question
How much pressure is transmitted in the hydraulic system considered in Example 11.6? Express your answer in pascals and in atmospheres. Example 11.6 Consider the automobile hydraulic system shown in Figure 11.13. A force of 100 N is applied to the brake pedal, which acts on the cylinder—called the master—through a lever. A force of 500 N is exerted on the master cylinder. Pressure created in the master cylinder is transmitted to four so-called slave cylinders. The master cylinder has a diameter of 0.500 cm, and each slave cylinder has a diameter of 2.50 cm.
Question Image
$2.5\times 10^{7}\textrm{ Pa}$
$2.5\times 10^{7}\textrm{ Pa} \times \dfrac{1 \textrm{ atm}}{1.013\times 10^{5}\textrm{ N/m}^2} = 147\textrm{ atm}$
Note: I forgot to express the answer in atmospheres in the video, but it's shown here in the final answer.
Solution Video

# OpenStax College Physics Solution, Chapter 11, Problem 24 (Problems & Exercises) (1:07)

Rating

No votes have been submitted yet.

Quiz Mode

Why is this button here? Quiz Mode is a chance to try solving the problem first on your own before viewing the solution. One of the following will probably happen:

1. You get the answer. Congratulations! It feels good! There might still be more to learn, and you might enjoy comparing your problem solving approach to the best practices demonstrated in the solution video.
2. You don't get the answer. This is OK! In fact it's awesome, despite the difficult feelings you might have about it. When you don't get the answer, your mind is ready for learning. Think about how much you really want the solution! Your mind will gobble it up when it sees it. Attempting the problem is like trying to assemble the pieces of a puzzle. If you don't get the answer, the gaps in the puzzle are questions that are ready and searching to be filled. This is an active process, where your mind is turned on - learning will happen!
If you wish to show the answer immediately without having to click "Reveal Answer", you may . Quiz Mode is disabled by default, but you can check the Enable Quiz Mode checkbox when editing your profile to re-enable it any time you want. College Physics Answers cares a lot about academic integrity. Quiz Mode is encouragement to use the solutions in a way that is most beneficial for your learning.

## Calculator Screenshots

Video Transcript
This is College Physics Answers with Shaun Dychko. We need to find the pressure in this hydraulic break system. So we can find the pressure anywhere... you know, in the slave cylinders or in the master cylinder because the pressure is the same throughout— that's what Pascal's principle says— and so we'll consider the pressure created by the master cylinder because we have information about it. We know that 500 newtons ends up being applied to this master cylinder and the diameter is 0.500 centimeters which we convert to meters by noticing that the prefix 'centa' means times 10 to the minus 2. So pressure is force divided by that area and it's a circular cross-section here— this cylinder is circular— and so the area is π times its radius squared and its radius is half its diameter so I have written d over 2 here and squared and then this works out to 4 times the force divided by π times the diameter squared. That's 4 times 500 newtons divided by π times 0.500 times 10 to the minus 2 meters squared which is 2.5 times 10 to the 7 pascals.

format: plain


text:
# Affiliate fees are tough all over

On Monday, Apple sent out an email to people in its iTunes/App Store affiliate program to inform them that

We have completely updated our Affiliate Resources site, making it much easier for you to find the information you need. Check out the updated site and learn more about how to optimize your affiliate placements.

which is both dull and unlikely to be true. But further down there was news that piqued a lot of interest and was undoubtedly true:

Starting on May 1st 2017, commissions for all app and in-app content will be reduced from 7% to 2.5% globally.

Nothing starts the week better than seeing a revenue stream cut by 65%.

The Apple corner of the internet erupted with tweets and posts about the change. All expressed disappointment, but John Voorhees’s unexpressed disappointment in his short article at MacStories was the most poignant. John’s the developer of Blink, a very nice iOS app for automatically generating Apple affiliate links. So not only is MacStories losing a source of income from its app recommendations, but Blink has lost some of its appeal to prospective users—why even bother with affiliate links when we’re now looking at the double whammy1 of low app prices and low commission rates?

But Apple’s not the only online seller to cut commissions. A couple of months ago Amazon changed its commission structure, and I was a little surprised when none of the stories about Apple’s cut mentioned that.

Amazon has a byzantine commission structure, with significantly different rates for different classes of merchandise. Given that this is Amazon, I assume the rates are based on detailed analytics regarding price, profit margin, popularity, competition, and several things I haven’t thought of because I’m not a brilliant online retailer. Here’s the current rate table from Amazon’s affiliate policies page.2

Up until a couple of months ago, that commission structure also included something they called “other products,” a class of merchandise whose commission varied with the number of sales. Your rate went up the more sales you made per month. Here’s how that worked:

This table is no longer on Amazon’s web site; I pulled it from the Wayback Machine’s February 24, 2017 archive of the policy page.

Ebooks were covered by this variable rate table, but as of March they have a fixed commission rate of 4%. I have a particular interest in this because I often tweet out affiliate links to ebooks that Amazon has put on sale and that I think my Twitter followers would be interested in. No matter what the commission rate, you don’t make much money on $2 books, but even I’ve seen the effect of the rate change. In February, I got credit for$421.13 of ebook sales and my commission was $29.58. In March, I got credit for$106.88 of ebook sales (25% of February) and my commission was only $4.29 (15% of February). My economic well-being doesn’t depend on affiliate links. The only reason I use them is to offset the costs of web hosting, domain registration, and my FastMail account.3 But others will be harder hit by these changes, and I hope they find new ways to keep going. I still think small web sites are the truest expression of the promise of the internet. 1. It’s actually a triple whammy because the commission payment rules pretty much guarantee that some of your affiliate earnings will never be paid, a situation I wrote about a couple of years ago. 2. Amazon uses the word associate rather than affiliate, but I’m going to stick with the more common term here. 3. Yes, you see what I did there. # PDF page counts and metadata I deal with lots of PDFs at work, and sometimes I want to report on the total number of pages I’ve reviewed on a given project. I’ve used various ad hoc methods to collect and sum up these page counts but have never come up with an automated technique. When there’s deadline pressure to get a report out, there’s no time—or it seems like there’s no time—to put together a decent automated solution. Today I decided to make time. There are several ways to get the number of pages in a PDF. You can open it in Preview and see the page count in the title bar. You can do a Get Info on the file. If you have PDFtk installed, you can run it from the command line using the dump_data operation. That’ll get you a crapload of info on the file (over 2,000 lines for the file I’m using as an example), but you can limit it to just the number of pages by filtering the output.1 $ pdftk File\ 3.pdf dump_data | grep NumberOfPages
NumberOfPages: 420

I decided to use one of the command-line tools Apple provides to access the metadata used by Spotlight. These tools all begin with “md,” and the one that can output the page count is mdls (metadata list).

Like pdftk, mdls will, by default, spit out a lot of information on a file.

$mdls File\ 3.pdf _kMDItemOwnerUserID = 501 kMDItemContentCreationDate = 2017-04-26 01:29:28 +0000 kMDItemContentModificationDate = 2017-04-26 01:29:42 +0000 kMDItemContentType = "com.adobe.pdf" kMDItemContentTypeTree = ( "com.adobe.pdf", "public.item", "com.adobe.pdf", "public.data", "public.composite-content", "public.content" ) kMDItemDateAdded = 2017-04-26 01:29:28 +0000 kMDItemDisplayName = "File 3.pdf" kMDItemEncodingApplications = ( "Pixel Translations (PIXPDF 58.5.1.1422)" ) kMDItemFSContentChangeDate = 2017-04-26 01:29:42 +0000 kMDItemFSCreationDate = 2017-04-26 01:29:28 +0000 kMDItemFSCreatorCode = "" kMDItemFSFinderFlags = 0 kMDItemFSHasCustomIcon = (null) kMDItemFSInvisible = 0 kMDItemFSIsExtensionHidden = 0 kMDItemFSIsStationery = (null) kMDItemFSLabel = 0 kMDItemFSName = "File 3.pdf" kMDItemFSNodeCount = (null) kMDItemFSOwnerGroupID = 20 kMDItemFSOwnerUserID = 501 kMDItemFSSize = 41753844 kMDItemFSTypeCode = "" kMDItemKind = "Portable Document Format (PDF)" kMDItemLastUsedDate = 2017-04-26 01:42:08 +0000 kMDItemLogicalSize = 41753844 kMDItemNumberOfPages = 420 kMDItemPageHeight = 807.36 kMDItemPageWidth = 606 kMDItemPhysicalSize = 41754624 kMDItemSecurityMethod = "None" kMDItemUseCount = 1 kMDItemUsedDates = ( "2017-04-25 05:00:00 +0000" ) kMDItemVersion = "1.4"  The only line we want is the one that starts with kMDItemNumberOfPages. We can limit the output to just that line by using the -name option and get rid of the label with the -raw option: $ mdls -name kMDItemNumberOfPages -raw File\ 3.pdf
420

The thing about -raw is that it doesn’t put a newline after the output, which is sometimes good and sometimes bad. We’ll deal with that in a bit.

Now we’re ready to build a shell script, called pdfpages, that does the following:

1. Prints a usage string if you don’t give it any arguments.
2. Prints just the number of pages in the file if you give it one argument.
3. Prints the number of pages and the name for each file and the grand total of pages if you give it more than one argument.

To demonstrate:

$pdfpages Usage: pdfpages <files>$ pdfpages File\ 3.pdf
420

$pdfpages *.pdf 330 File 1.pdf 532 File 2.pdf 420 File 3.pdf 1282 Total  Here’s the source code for pdfpages: bash: 1: #!/bin/bash 2: 3: if [$# == 0 ]; then
4:    echo "Usage: pdfpages <files>"
5:  elif [ $# == 1 ]; then 6: echo mdls -name kMDItemNumberOfPages -raw "$1"
7:  else
8:    sum=0
9:    for f in "$@"; do 10: count=mdls -name kMDItemNumberOfPages -raw "$f"
11:      echo -e "$count\t$f"
12:      (( sum += count ))
13:    done
14:    echo -e "$sum\tTotal" 15: fi  Recall that $# provides the number of arguments to the script, so Lines 3 and 5 test for the no argument and one argument conditions, respectively. Line 4 is the usage message printed if there are no arguments. Line 6 runs when there’s one argument and is basically what we showed above. Putting the mdls command in backticks runs it and feeds the output to echo, which adds the trailing newline and prevents the next command prompt from appearing on the same line as the output.2

Lines 8–14 handle the case of more than one argument. We start by initializing the running sum in Line 8. Then we loop through all the arguments with the for on Line 9. For each file, Line 10 runs the mdls command and puts the output in the variable count. Line 11 prints the page count and file name for the current file, and Line 12 increments the running sum.3 When the loop is finished, Line 14 prints out the total.

Throughout the script, please note the use of double quotes around the $@, $1, and $f variables. This keeps the script from shitting the bed when file paths include spaces. This is about as complicated a shell script as I would ever want to write. If I find myself wanting to add features, I’ll probably rewrite it as a Python script using the subprocess module to run the mdls command. After writing pdfpages, I wondered how it would have worked on a older project in which I gave up trying to count all the PDF pages I was sent because there were just too many spread over too many files. Getting the number of PDF files (just over 1,000) in a nested folder structure was easy using standard tools: find . -iname *.pdf | wc -l  Now I could get the number of pages in those files with find . -iname *.pdf -print0 | xargs -0 pdfpages  It chugged away for about half a minute and told me I’d been given nearly 16,000 pages to review. Maybe it was better I didn’t know. 1. Don’t write to tell me I should be using ack or ag or rg or any of the other grep replacements that have sprung up in recent years. This is just an example and speed really doesn’t matter here. ↩ 2. This seems more complicated than necessary, but I’m not enough of a shell scripter to know a better way. Unlike the grep situation above, suggestions for improvement here are welcome. ↩ 3. There are other ways to increment the sum. I chose this one because it struck me as weird. How often do you see shell variables dereferenced without a dollar sign. This line reminds me of how perverse shell scripting syntax can be. ↩ # Cleaning out old Reminders As I read my RSS feed during lunch today, I came across this post by Dan Moren at Six Colors, in which he complains, rightly, that Apple’s Reminders apps—Mac and iOS—have no automated or manual way to clean out old completed tasks. It would be great if… Apple provided an option to have those completed tasks automatically deleted after a certain amount of time—30 days would work great for me—and even better if it allowed you to choose the interval. Given that Reminders has a fairly decent AppleScript dictionary, I figured it’d be fairly easy to write a script that would do what Dan wanted. And it was. First, though, I should mention that there’s been very little testing of this script. I made up a bunch of fake reminders in different lists, and wrote the script initially to delete all completed tasks that were more than 5 minutes old. That worked, so I think the 30-day revision should also work. But you may want to think about backups before implementing this. Also, are you sure you want to delete all your old completed reminders? Maybe some of them would be good to have around to prove—to yourself, at least—what you did and when you did it. End of caveats. Let’s look at the script, which I’ve named “Purge Old Reminders.” applescript: 1: set monthago to (current date) - (30 * days) 2: 3: tell application "Reminders" 4: set myLists to name of every list 5: repeat with thisList in myLists 6: tell list thisList 7: delete (every reminder whose completion date is less than monthago) 8: end tell 9: end repeat 10: end tell  Line 1 determines the date 30 days ago and saves it in the variable monthago. Line 4 gets the names of all your Reminders lists and puts them in the variable myLists. Lines 5–9 then loop through all your lists, deleting all the reminders with a completion date that falls before monthago. That’s it. If you want to change how old a completed reminder has to be before it gets purged, change the (30 * days) part in Line 1 to whatever you prefer. If you don’t want all your lists purged, change Line 4 to something like set myLists to {"Groceries", "Hardware", "Packing"}  where the braces enclose a comma-separated list of the names of the lists you want to purge with the names in double quotes. You can, of course, just run this script by hand whenever you get the hankering to purge your old completed reminders, but the cool thing is to set up a system to run it periodically. The standard way to run scripts periodically in macOS is to use the launchd system. If you want to go that way, I’d suggest you get a copy of LaunchControl, a$10 app that makes the creation and scheduling of launchd services relatively painless. Or you can read Nathan Grigg’s excellent launchd tutorial, which you should probably do even if you do buy LaunchControl. Either way, you’ll end up with a plist file that looks something like this:

xml:
1:  <?xml version="1.0" encoding="UTF-8"?>
2:  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3:  <plist version="1.0">
4:  <dict>
5:    <key>Label</key>
6:    <string>com.leancrew.purge</string>
7:    <key>ProgramArguments</key>
8:    <array>
9:      <string>/usr/bin/osascript</string>
10:      <string>/Users/drdrang/Dropbox/bin/Purge Old Reminders.scpt</string>
11:    </array>
12:    <key>StartCalendarInterval</key>
13:    <array>
14:      <dict>
15:        <key>Hour</key>
16:        <integer>6</integer>
17:        <key>Minute</key>
18:        <integer>6</integer>
19:      </dict>
20:    </array>
21:  </dict>
22:  </plist>

Lines 8–11 run the AppleScript via the osascript command. You’ll need to change the path in Line 10 to wherever you have Purge Old Reminders stored. Lines 14–19 set the script to run every morning at 6:06. Change lines 16 and 18 to set the hour and minute you prefer. Save it to your ~/Library/LaunchAgents folder and follow Nathan’s instructions to use launchctl to load it.

If you own Keyboard Maestro, you can avoid launchd by creating a macro with a timed trigger to run the script.

I’m not sure how Keyboard Maestro handles macros that got triggered when it wasn’t on, so you may want to change it to a time that you’re likely to be at your computer. Frankly, it’s no big deal if the script doesn’t run for a few days.

There used to be a simple way to run scripts periodically using Calendar, but Apple has either deleted that function or hidden it well. I suspect there are other methods using other third-party apps, but I don’t want to recommend anything I haven’t used myself.

Update 04/25/2017 10:59 AM
I have Reminders open all the time, so I didn’t think about the script possibly needing to quit the app after it’s done. But Vítor Galvão did, so here’s an update with his changes. This version checks to see if Reminders is already running in Line 1; if it isn’t, it quits in Line 11 after deleting the old completed reminders.

applescript:
1:  set remindersOpen to application "Reminders" is running
2:  set monthAgo to (current date) - (30 * days)
3:
4:  tell application "Reminders"
5:    set myLists to name of every list
6:    repeat with thisList in myLists
7:      tell list thisList
8:        delete (every reminder whose completion date is less than monthago)
9:      end tell
10:    end repeat
11:    if not remindersOpen then quit
12:  end tell

Thanks, Vítor!

# One-off text filtering in BBEdit

After my recent appearance with David and Katie on the Mac Power Users podcast and a Twitter conversation with Eddie Smith, I’ve been thinking about text transformations in BBEdit. In addition to the single-stage text transformations in its menu, BBEDit has a couple of ways to perform complex text transformations:

1. Text Filters (née Unix Filters), which run a script saved in a special Text Filters folder1 and accessed through the submenu.
2. Text Factories, which are like Unix pipelines in that they allow you to create a single command that sends the text through a series of successive simple transformations. The main difference between Text Factories and pipelines is that a factories are built up graphically, very much like Automator workflows.

Both Filters and Factories take the selected text (or the entire current document if no text is selected), perform the transformation, and replace the text with their output. This is very much in the Unix tradition of command line text tools except that the current selection (or document) takes the place of standard input and standard output.2

Filters require a certain amount of premeditation; you have to create a script and save it to a particular folder. They’re really most useful for transformations you intend to run often. Factories can be more of an ad hoc solution (although they also can be saved in the Text Filters folder for frequent use) and are therefore more suited than Filters are for one-off transformations.

Factories are a great way for people who don’t have much experience programming or using the command line to automate BBEdit’s Text menu commands in powerful ways. If, however, you’re used to using Unix command line tools to build up transformations, you may find the graphical method of creating Factories somewhat slow. There’s often a lot of clicking needed to put together a Factory and choose the necessary options for each step. You may wish for the ability to just type out a pipeline of commands and send the text through it.

And when I say “you,” of course I mean “me.” Although I’m far from a Unix wizard, I do find myself thinking of transformations in terms of command-line utilities rather than Text Factory actions. If only BBEdit would let me just type out a pipeline to run the selected text through. Surprisingly, it’s not all that hard to give it that ability.

Here’s a shell script, called Any Filter, that I have saved in BBEdit’s Text Filters folder. It’s available to me from the submenu and I have it bound to the ⇧⌃⌥⌘F key combination.

bash:
1:  #!/bin/bash
2:
3:  cmd=osascript -e 'get text returned of \
4:      (display dialog "Filter command" \
6:        buttons {"Cancel", "Filter"} \
7:        default button "Filter")'
8:  eval \$cmd

As you can see, most of Any Filter is an AppleScript command that displays a dialog box asking for and collecting the command. The final line is just the execution of that command. Because this is saved as a Text Filter, BBEdit knows to feed it the selected text (or the entire current document) and replace that text with Any Filter’s output.

Here’s how Any Filter works in practice. Suppose I have a bunch of text I want to hard wrap to 40 characters per line and then number each line. For reasons I don’t understand, BBEdit’s command isn’t available as a Text Factory action, so we’ll use the fmt command to do our work. First, we select the text.

Then we run Any Filter and enter the fmt command with a width option of 40 and pipe that through the nl command with the options to use a two-digit, zero-padded number and a colon separator.

When we’re done, the original selected text has been replaced with a hard-wrapped and numbered version.

Is this easier than first running and then ? I suppose that depends on what you’re used to. I find commands like sort and fmt easier to use than their menu equivalents because I’ve been using them a long time. They’re what I think of first when I need to filter some text.

1. Where this folder is depends on your setup. By default, the Text Filters folder is at ~/Library/Application Support/BBEdit/Text Filters, but if you’re a Dropbox user, you may have moved it to ~/Dropbox/Application Support/BBEdit/Text Filters as described here


text:
## 1.2 Some facts about distributions

We will make use of several parametric distributions. Some notation and facts are introduced as follows:

• $$\mathcal{N}(\mu,\sigma^2)$$ stands for the normal distribution with mean $$\mu$$ and variance $$\sigma^2$$. Its pdf is $$\phi_\sigma(x-\mu):=\frac{1}{\sqrt{2\pi}\sigma}e^{-\frac{(x-\mu)^2}{2\sigma^2}}$$, $$x\in\mathbb{R}$$, and satisfies that $$\phi_\sigma(x-\mu)=\frac{1}{\sigma}\phi\left(\frac{x-\mu}{\sigma}\right)$$ (if $$\sigma=1$$ the dependence is omitted). Its cdf is denoted as $$\Phi_\sigma(x-\mu)$$. $$z_\alpha$$ denotes the upper $$\alpha$$-quantile of a $$\mathcal{N}(0,1)$$, i.e., $$z_\alpha=\Phi^{-1}(1-\alpha)$$. Some uncentered moments of $$X\sim\mathcal{N}(\mu,\sigma^2)$$ are

\begin{align*} \mathbb{E}[X]&=\mu,\\ \mathbb{E}[X^2]&=\mu^2+\sigma^2,\\ \mathbb{E}[X^3]&=\mu^3+3\mu\sigma^2,\\ \mathbb{E}[X^4]&=\mu^4+6\mu^2\sigma^2+3\sigma^4. \end{align*}

The multivariate normal is represented by $$\mathcal{N}_p(\boldsymbol{\mu},\boldsymbol{\Sigma})$$, where $$\boldsymbol{\mu}$$ is a $$p$$-vector and $$\boldsymbol{\Sigma}$$ is a $$p\times p$$ symmetric and positive matrix. The pdf of a $$\mathcal{N}(\boldsymbol{\mu},\boldsymbol{\Sigma})$$ is $$\phi_{\boldsymbol{\Sigma}}(\mathbf{x}-\boldsymbol{\mu}):=\frac{1}{(2\pi)^{p/2}|\boldsymbol{\Sigma}|^{1/2}}e^{-\frac{1}{2}(\mathbf{x}-\boldsymbol{\mu})'\boldsymbol{\Sigma}^{-1}(\mathbf{x}-\boldsymbol{\mu})}$$, and satisfies that $$\phi_{\boldsymbol{\Sigma}}(\mathbf{x}-\boldsymbol{\mu})=|\boldsymbol{\Sigma}|^{-1/2}\phi\left(\boldsymbol{\Sigma}^{-1/2}(\mathbf{x}-\boldsymbol{\mu})\right)$$ (if $$\boldsymbol{\Sigma}=\mathbf{I}$$ the dependence is omitted).

• The lognormal distribution is denoted by $$\mathcal{LN}(\mu,\sigma^2)$$ and is such that $$\mathcal{LN}(\mu,\sigma^2)\stackrel{d}{=}\exp(\mathcal{N}(\mu,\sigma^2))$$. Its pdf is $$f(x;\mu,\sigma):=\frac{1}{\sqrt{2\pi}\sigma x}\allowbreak e^{-\frac{(\log x-\log\mu)^2}{2\sigma^2}}$$, $$x>0$$. Note that $$\mathbb{E}[\mathcal{LN}(\mu,\sigma^2)]=e^{\mu+\frac{\sigma^2}{2}}$$

• The exponential distribution is denoted as $$\mathrm{Exp}(\lambda)$$ and has pdf $$f(x;\lambda)=\lambda e^{-\lambda x}$$, $$\lambda,x>0$$.

• The gamma distribution is denoted as $$\Gamma(a,p)$$ and has pdf $$f(x;a,p)=\frac{a^p}{\Gamma(p)} x^{p-1}e^{-a x}$$, $$a,p,x>0$$, where $$\Gamma(p)=\int_0^\infty x^{p-1}e^{-ax}\,\mathrm{d}x$$. It is known that $$\mathbb{E}[\Gamma(a,p)]=\frac{p}{a}$$ and $$\mathbb{V}\mathrm{ar}[\Gamma(a,p)]=\frac{p}{a^2}$$.

• The inverse gamma distribution, $$\mathrm{IG}(a,p)\stackrel{d}{=}\Gamma(a,p)^{-1}$$, has pdf $$f(x;a,p)=\frac{a^p}{\Gamma(p)} x^{-p-1}e^{-\frac{a}{x}}$$, $$a,p,x>0$$. It is known that $$\mathbb{E}[\mathrm{IG}(a,p)]=\frac{a}{p-1}$$ and $$\mathbb{V}\mathrm{ar}[\mathrm{IG}(a,p)]=\frac{a^2}{(p-1)^2(p-2)}$$.

• The binomial distribution is denoted as $$\mathrm{B}(n,p)$$. Recall that $$\mathbb{E}[\mathrm{B}(n,p)]=np$$ and $$\mathbb{V}\mathrm{ar}[\mathrm{B}(n,p)]=np(1-p)$$. A $$\mathrm{B}(1,p)$$ is a Bernouilli distribution, denoted as $$\mathrm{Ber}(p)$$.

• The beta distribution is denoted as $$\beta(a,b)$$ and its pdf is $$f(x;a,b)=\frac{1}{\beta(a,b)}x^{a-1}(1-x)^{1-b}$$, $$0<x<1$$, where $$\beta(a,b)=\frac{\Gamma(a)\Gamma(b)}{\Gamma(a+b)}$$. When $$a=b=1$$, the uniform distribution $$\mathcal{U}(0,1)$$ arises.

• The Poisson distribution is denoted as $$\mathrm{Pois}(\lambda)$$ and has pdf $$\mathbb{P}[X=x]=\frac{x^\lambda e^{-\lambda}}{x!}$$, $$x=0,1,2,\ldots$$. Recall that $$\mathbb{E}[\mathrm{Pois}(\lambda)]=\mathbb{V}\mathrm{ar}[\mathrm{Pois}(\lambda)]=\lambda$$.


text:
# 【转】面试官心得

1.自我介绍

其实我想要的不是姓名，年龄，工作经历这些，拜托这些简历上都有我不是文盲，我是想知道你的优点，特长这些信息，你可以很自豪的告诉我你擅长数据库，解决过****等无数难题就可以了。

2.我们公司会有自己的一套框架，你是否很快速的接受它，如果不能适应改怎么办

我想知道的是你的学习能力和适应能力，并且如果你对框架有你独到的见解，我会加分的

3.能不能够加班，或者出差，如果加班没有工资的话是否能接受

这个我想要知道的是，一是否能吃苦耐劳，与公司同进退，二是看你的应变能力，我不想听简单的能与不能，其实是想看你的应变，你能否处理好这件事，三如果你什么情况都能接受，我也不会要你的，记住什么都能接受是对自己水平的不自信。

4.是否有职业规划

如果没有这个的话，我会认为你不想在在这个行业干出一些成绩，只想混日子。

5.继续上面的问题，如果你选择技术方面发展，我会问，怎么才算是合格的程序员，什么样的代码是好代码，如果选择管理方面发展，我会问，你过去开发程序的过程是怎么样的。

这个纯粹是了解下你目前的能力，我觉得这个已经大概可以展现你部分的能力了。

剩下还有5到技术问题，这个就不方便透露了，但是我会分为三个级别，初级，你答上来我会认为你合格，中级我会为你加分，高级我会为你加薪就是这么简单。

希望会对大家有所帮助。

# openfire 插件开发

JiveGlobals.getHomeDirectory()

Log.getLogDirectory()

Plugin Structure

myplugin/
|- plugin.xml      <- Plugin definition file
|- changelog.html  <- Optional changelog file for plugin
|- logo_small.gif  <- Optional small (16x16) icon associated with the plugin (can also be a .png file)
|- logo_large.gif  <- Optional large (32x32) icon associated with the plugin (can also be a .png file)
|- classes/        <- Resources your plugin needs (i.e., a properties file)
|- lib/            <- Libraries your plugin needs
|- src/
|- database    <- Optional database scripts for your plugin
|- java        <- Java source code for your plugin
|   |- com
|       |- mycompany
|           |- *.java
|- web
|- images/    <- Any images your JSP pages need (optional)
|- WEB-INF
|- web.xml    <- Optional file where custom servlets can be registered

ant plugin -Dplugin=myplugin

openfire提供离线消息发送，但是不提供历史消息存储。因此需要写插件来保存历史记录。

# [转csdn文章]学习HTML5不可错过的12家国外网站(组图)

### 学习HTML5不可错过的12家国外网站(组图)

2011-04-21 23:43 | 25977次阅读 | 来源：CSDN编译 【已有60条评论】发表评论

[CSDN编译]HTML5是近十年来Web开发标准最巨大的飞跃。和以前的版本不同，HTML5并非仅仅用来表示Web内容，它的新使命是将 Web带入一个成熟的应用平台，在HTML5平台上，视频、音频、图象、动画以及同电脑的交互都被标准化。对于广大开发人员和设计者，究竟该如何入手 HTML5及获取相关的国外最新资源。以下是广大HTML5技术爱好者学习和参考相关技术不可错过的12家外网，它们或是采用HTML5技术开发出的案例，或是HTML5相关的学习资源，供国内的开发人员参阅。

(1)HTML5 Labs

HTML5实验室，这里有HTML5标准、范型和应用规范的最新内容。

(2)HTML5 – Wikipedia

(3)Apple – HTML5

(5)Dive into HTML5 by Mark Pilgrim

(6)HTML 5 Cheat Sheet (PDF) – Smashing Magazine(关于HTML5资料的PDF文档精华 )

(7)HTML5 Rocks(需翻墙)

HTML5 Rocks的内容包括了HTML5的演示、视频、如何使用HTML5的API、基础进阶教程等等。

(8)World’s Biggest PacMan

(9)HTML5 Gallery

(10)HTML5 Demos

(11)W3Schools HTML5

# it-e-08 Real-Time Operating System

A "Real-Time Operating System" or "RTOS" is an operating system that has been
developed for real-time applications. Typically used for embedded applications. Note that this type of operating system does not necessarily have high throughput — the specialized scheduling algorithm and a high clock-interrupt rate can both interfere with throughput. An early example of a large-scale real-time operating system was the so-called "control program" developed by American Airlines and IBM for the Sabre Airline Reservations System. Debate exists about what actually constitutes real-time.
Scheduling

Continue reading it-e-08 Real-Time Operating System

# 【转】webqq实现

2010-12-09 11:37    总点击量：160     总评论数：2

谁说腾讯不创新？WEB2.QQ就是个挺强悍的反击。咋一看到时我不禁摸摸头，难道这就是传说中的QQ OS？

【总体体验】

【架构鸟瞰】跨平台：

class= “javascriptEnabled win win6_1 firefox firefox3_6 gecko gecko20100914_0 flash flash10_0″

JavaScript：

web2.qq用的是jQuery，加上一些如JSON、基础交互的实现。 web2.qq用的是jQuery的一个子集，加上基础UI组件、所使用到的交互等功能模块。

jet核心 sizzle选择器 xhr/ajax 基础动画、拖曳、贴齐、弹窗、窗口大小调整等交互。嗯，好像也没看出WEB2.QQ里有多少动画。 尺寸、swf、css、数据等等一堆杂七杂八的小东西

【加载问题】

HTML的流量大小基本可以忽略，主要重量在JS上面。从这点上看，跨浏览器的脚本已经成为WEB开发的难点与重点。 首次载入页面的JS预加载：jet.all.js库80K，webqq.main.js库100K。而且，只有JET放在了head里加载，而webqq.main.js是放在div#desktop后面加载的，所以，时间线上到把页面展示出来并可以点击“登录键”，只有100K左右的HTML/CSS/JS，剩下的都是应用栏及任务栏等的加载，然后就是那一堆图片的加载与默认应用的加载。 永远不会进行自动登录。一是保证了网页沙箱上的安全性，二也不会让浏览器一次承担500K以上的加载负担，保证了体验的平滑过渡。相信用户也都能接受没有自动登录功能的WEBQQ。 点击登录后再次加载不超过300K的JS。这里俺有点困惑，因为真的需要300K来实现主要的QQ功能么？毕竟很多的应用其实都是基于网页实现，并不要求直接脚本实现。估计，这里还是有优化空间的。 所有控件使用独立的JS。模块化的体现。中间或许难免会有重造轮子的事情，但却是大型团队开发所难以避免的。 腾讯一惯强大的服务器支撑能力。这点其实非常重要，否则加上每次加载的延迟与缓慢的速度，甚至偶尔还来个404什么的，体验绝对不会是现在这个样子。 CSS文件上的加载基本与JS相对应，也就是一个JS一个CSS。同理，模块化的开发。会造成冗余但却足够实用和敏捷。 貌似没启用GZIP？有可能是会对服务器端性能造成影响？粗略估计，使用了GZIP后首次加载的180K的JS会变成50K左右，不过，有没这个必要呢？ 【展望】

#2发表时间：2010-12-9 16:38:05 引用 回复

Web QQ算是web应用的尝试，此文也仅仅写了一些界面的东西，而且WebQQ还有一个Sliverlight版本

Web QQ的核心应该是消息服务这块，不知怎么实现的。下面贴一个网上的分析：

Web QQ的原理大概如下：

# 云计算

http://www.hudong.com/wiki/%E4%BA%91%E8%AE%A1%E7%AE%97

(2) 虚拟化。云计算支持用户在任意位置、使用各种终端获取应用服务。所请求的资源来自“云”，而不是固定的有形的实体。应用在“云”中某处运行，但实际上用户无需了解、也不用担心应用运行的具体位置。只需要一台笔记本或者一个手机，就可以通过网络服务来实现我们需要的一切，甚至包括超级计算这样的任务。

(3) 高可靠性。“云”使用了数据多副本容错、计算节点同构可互换等措施来保障服务的高可靠性，使用云计算比使用本地计算机可靠。

(4) 通用性。云计算不针对特定的应用，在“云”的支撑下可以构造出千变万化的应用，同一个“云”可以同时支撑不同的应用运行。

(5) 高可扩展性。“云”的规模可以动态伸缩，满足应用和用户规模增长的需要。

(6) 按需服务。“云”是一个庞大的资源池，你按需购买；云可以象自来水，电，煤气那样计费。

(7) 极其廉价。由于“云”的特殊容错措施可以采用极其廉价的节点来构成云，“云”的自动化集中式管理使大量企业无需负担日益高昂的数据中心管理成本，“云”的通用性使资源的利用率较之传统系统大幅提升，因此用户可以充分享受“云”的低成本优势，经常只要花费几百美元、几天时间就能完成以前需要数万美元、数月时间才能完成的任务。

SaaS
SaaS是Software-as-a- service(软件即服务)的简称，它是一种通过Internet提供软件的模式，用户无需购买软件，而是向提供商租用基于Web的软件，来管理企业经营活动。“相对于传统的软件，SaaS解决方案有明显的优势，包括较低的前期成本，便于维护，快速展开使用。这些优势导致SaaS在中国市场增长明显。”Springboard中国区软件行业研究经理刘经纬(JingweiLiu)说，“随着企业IT预算持续受到严格的审查和企业减少雇用技术人员，我们可以在未来的几个月中看到中国市场对SaaS解决方案有明显的需求。”
PaaS

IaaS
IaaS (Infrastructure as a Service) 基础设施即服务。消费者通过 Internet 可以从完善的计算机基础设施获得服务。这类服务称为基础设施即服务（Infrastructure asaService，IaaS）。基于Internet 的服务（如存储和数据库）是 IaaS的一部分。
IaaS最大优势在于它允许用户动态申请或释放节点，按使用量计费。运行IaaS的服务器规模达到几十万台之多，用户因而可以认为能够申请的资源几乎是无限的。而IaaS是由公众共享的，因而具有更高的资源使用效率。

1、特权用户访问若使用云计算，你的机密数据将由贵公司外面的人员来处理，所以可想而知：不是贵公司的员工完全可以访问这些数据。

2、法规遵从在《萨班斯－奥克斯利法案》当道的时代，公司有责任实施严格的数据监控和归档级别。即便一家公司与外部的云计算服务提供商签订了合同，这些法规仍要求这家公司负有责任。云计算服务提供商应当提交审计和安全方面的证书，确保对方能够履行约定的承诺。 “如果云计算提供商不愿意或者没能力做到遵从法规，这表明客户只能用它们来处理最不重要的功能。”

3、数据位置若使用云计算，你不知道自己的数据到底存放在什么地方。服务器可能建在马来西亚加拿大或者美国的新泽西州，说不定同时建在上述三个地方。

4、数据隔离当然，云计算提供商会使用SSL来保护传输中的数据，但当贵公司的数据位于存储设备中时，可能与其他公司的数据共用一只 “虚拟保管箱”。贵公司的数据与别人的数据经过适当隔离吗？提供商可能会夸耀自己的加密技术如何强大、安全。你会听到密钥长度有多长、采用哪种深奥的加密算法。不过，如果你的数据能够被提供商读取，那么可以这么认为：数据也会被别人读取。

5、可用性从理论上来说，如果你使用云计算服务提供商，没有必要担心自己的数据会消失――这些提供商很容易采用冗余机制把你的数据复制到众多地方，这样万一系统崩溃，仍可以高枕无忧。但你的员工能不能随时访问完成工作所需的数据呢？比方说，要是虚拟管道受到堵塞会怎样？要是提供商自身出现的某种内部故障导致你无法访问自己的关键数据，又会怎样？忠告：“公司应当为任何重要的IT工作负载确定服务级别方面的要求，并且需要提供商签订服务级别协议，从而确保合同里面写明惩罚条款，以防出现服务级别协议未得到遵守的情况。”

6、灾难恢复

7、调查支持 开展内部的法律调查向来就不是容易的事，因为这需要清查可能散布在实体位置和虚拟位置的大批文档。如果你使用云计算服务提供商，那么开展这种调查更是困难重重：许多客户的数据也许散布在地点不断变化的一系列数据中心。

8、存活能力你的提供商会被收购吗？或者更糟糕的是，会破产吗？如果是这样，对方需要多久才能把数据交还给你、而且采用的格式让你可以导入到另一家提供商的基础设施上？

9、降低风险方面的支持 你的员工开始使用外部提供商时，会经历一个学习过程。这家提供商提供的界面用起来多容易？提供商是否帮助你的管理人员设置监控政策？又采取了哪些措施来防范恶意软件网络钓鱼

PS:

# it-e-09 Application software

Application software might be described as end-user software. Application software performs
useful work on general-purpose tasks such as word processing and cost estimating. There are
certain general-purpose programs that are widely used in nearly all career areas. They are: word
processing, electronic spreadsheets, graphic programs and so on. They are also called basic tools
and have some common features.
Insert Point

The insert point or cursor shows you where you can enter data next. Typically ,
it is a blinking vertical bar on the screen. You can move it around using a mouse or the directional
arrow keys on many keyboards.

Almost all software packages have menus. Typically, the menus are displayed in a
menu bar at the top of the screen. When one of these is selected, a pull-down menu appears. This
is a list of commands associated with the selected menu.
Help

For most applications, one of the menus on the menu bar is Help. When selected, the
locate reference information about specific commands, and central options to move around.
Button Bars

Button bars typically are below the menu bar. They contain icons or graphic
representations for commonly used commands. This offers the user a graphic approach to
selecting commands. It is an example of a graphic user interface in which graphic objects rather
than menus can be used to select commands.
Dialog Box Dialog boxes frequently appear after selecting a command from a pull-down
Scroll Bars Scroll bars are usually located on the right and/or the bottom of the screen.
They enable you to display additional information not currently visible on the screen.
WYSIWYG Pronounced "wizzy-wig", WYSIWYG stands for "What You See Is What You
Get." This means that the image on the screen display looks the same as the final printed document.
Application programs without WYSIWYG cannot always display an exact representation of the
final printed document. The WYSIWYG feature allows the user to preview the document's
appearance before it is printed out.
Function Keys

Function keys are labeled F1, F2, and so on. These keys are positioned
along the left side or along the top of the keyboard. They are used for commands or tasks that are
performed frequently, such as underlining. These keys do different things in different software
packages.
Now let's introduce respectively the most common used application software: word processing,
Word processing software is used to create, edit, save, and print documents. Documents can
be any kind of text material. With word processing, you view the words you type on a monitor
instead of on a piece of paper. After you finish your typing, save your words on diskettes or hard
disk, and print the results on paper.
The beauty of this method is that you can make changes or corrections before printing out
the document. Even after your document is printed out, you can easily go back and make changes.
You can then print it out again. Want to change a report from double spaced to single spaced?
Alter the width of the margins on the left and right? Delete some paragraphs and add some others
from yet another document? A word processor allows you to do all these with ease. Indeed,
deleting, inserting, and replacing—the principal correcting activities—can be done just by
pressing keys on the keyboard. Popular word processing software are Word , WPS and so on.
They have some common features.
Word Wrap and the Enter Key One basic word processing feature is word wrap. When
you finish a line, a word processor decides for you and automatically moves the insertion point to
the next lines. To begin a new paragraph or leave a blank line, you press the Enter key.
Search and Replace A search or find command allows you to locate any character, word,
or phrase in your document. When you search, the insertion point moves to the first place the
item appears. If you want, the program will continue to search for all other locations where the
item appears. The replace command automatically replaces the word you search for with another
word. The search and replace commands are useful for finding and fixing errors.
Cut, Copy, and Paste With a word processor, you select the portion of text to be moved by
highlighting it. Using either the menu or button bar, choose the command to cut the selected text.
The selected text disappears from your screen. Then move the insertion point to the new location
and choose the paste command to reinsert the text into the document. In a similar manner, you
can copy selected portions of text from one location to another.

A spreadsheet is an electronic worksheet used to organize and manipulate
numbers and display options for analysis. Spreadsheets are used by financial analysts, accountants,
contractors, and others concerned with manipulating numeric data. Spreadsheets allow you to try
out various "what-if" kinds of possibilities. That is a powerful feature. You can manipulate numbers
by using stored formulas and calculate different outcomes.
A spreadsheet has several parts. The worksheet area of the spreadsheet has letters for
column headings across the top. It also has numbers for row headings down the left side. The
intersection of a column and row is called a cell. The cell holds a single unit of information. The
position of a cell is called the cell address. For example, "A1" is the cell address of the first
position on a spreadsheet, the topmost and leftmost position. A cell pointer—also known as the
cell selector—indicates where data is to be entered or changed in the spreadsheet. The cell
pointer can be moved around in much the same way that you move the insertion pointer in a
word processing program. Excel is the most common spreadsheet software. It has some common
Format Label is often used to identify information in a worksheet, it is usually a word or
symbol. A number in cell is called a value. Labels and values can be displayed or formatted in
different ways. A label can be centered in the cell or positioned to the left or right. A value can be

displayed to show decimal places, dollars, or percent. The number of decimal positions can be
altered, and the width of columns can be changed.
Formulas One of the benefits of spreadsheets is that you can manipulate data through the
use of formulas. Formulas are instructions for calculations. They make connections between
numbers in particular cells.
Functions

Functions are built-in formulas that perform calculations automatically.
Recalculation

Recalculation or what-if analysis is one of the most important features of
recalculate automatically. Thus you can substitute one value for another in the cells affected by
your formula and recalculate the results. For more complex problems, recalculation enables you
to store long, complicated formulas and many changing values and quickly produce alternatives.

# it-e-10 Software Development Kit

A "Software Development Kit", or "SDK" for short, is typically a set of development tools
that allows a software engineer to create applications for a certain software package, software
framework, hardware platform, computer system, operating system or similar. It may be something
as simple as an application programming interface in the form of some files to interface to a
particular programming language, or include sophisticated hardware to communicate with a certain
embedded system. Common tools include debugging aids and other utilities. SDKs also
frequently include sample code and supporting technical notes or other supporting documentation
to help clarify points from the primary reference material. A software engineer typically receives
the SDK from the target system developer. Oftentimes, the SDK can be downloaded directly via
the Internet. Many SDKs are provided for free to encourage developers to use the system or
language. Sometimes this is used as a marketing tool. For example, "Foo Products" might
provide the "Widget SDK" for free to encourage people to use it. Thus, more people will be
encouraged to buy more of their widgets since they can program them for free. SDKs may have
attached licenses that make them unsuitable for building software intended to be developed under
an incompatible license. For example, a proprietarySDK will likely be incompatible with Free
software development. And a GPL licensed SDK will "likely" be incompatible with proprietary
software development. LGPL SDKs are typically safe for proprietary development. An SDK for
an operating system add-on (for instance, QuickTime for Mac OS) may include the add-on

software itself, to be used for development purposes, if not necessarily for redistribution. An

interesting situation arises here between platforms where it is possible to develop applications

that can at least start up on a system configuration without the add-on installed, and use a

Gestalt-style run-time "environment query" to determine if the add-on is present, and ones where
the application will simply fail to start. In other words, it is possible to build a single binary that
will run on configurations with and without the add-on present, albeitoperating with reduced
functionality in the latter situation.

Continue reading it-e-10 Software Development Kit

# java json xpath jsonpath

jsonpath和xpath语法不通http://goessner.net/articles/JsonPath/

XPath
JSONPath
Description

/
$the root object/element . @ the current object/element / . or [] child operator .. n/a parent operator // .. recursive descent. JSONPath borrows this syntax from E4X. * * wildcard. All objects/elements regardless their names. @ n/a attribute access. JSON structures don't have attributes. [] [] subscript operator. XPath uses it to iterate over element collections and for predicates. In Javascript and JSON it is the native array operator. | [,] Union operator in XPath results in a combination of node sets. JSONPath allows alternate names or array indices as a set. n/a [start:end:step] array slice operator borrowed from ES4. [] ?() applies a filter (script) expression. n/a () script expression, using the underlying script engine. () n/a grouping in Xpath XPath has a lot more to offer (Location pathes in not abbreviated syntax, operators and functions) than listed here. Moreover there is a remarkable difference how the subscript operator works in Xpath and JSONPath. Square brackets in XPath expressions always operate on the node set resulting from the previous path fragment. Indices always start by 1.With JSONPath square brackets operate on the object or array addressed by the previous path fragment. Indices always start by 0. |2007-08-18| e3#JSONPath examples Let's practice JSONPath expressions by some more examples. We start with a simple JSON structure built after an XML example representing a bookstore (original XML file). { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99 }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": 8.99 }, { "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99 } ], "bicycle": { "color": "red", "price": 19.95 } } } XPath JSONPath Result /store/book/author$.store.book[*].author
the authors of all books in the store

//author
$..author all authors /store/*$.store.*
all things in store, which are some books and a red bicycle.

/store//price
$.store..price the price of everything in the store. //book[3]$..book[2]
the third book

//book[last()]
$..book[(@.length-1)]$..book[-1:]
the last book in order.

//book[position()<3]
$..book[0,1]$..book[:2]
the first two books

//book[isbn]
$..book[?(@.isbn)] filter all books with isbn number //book[price<10]$..book[?(@.price<10)]
filter all books cheapier than 10

//*
\$..*
all Elements in XML document. All members of JSON structure

Continue reading java json xpath jsonpath

# it-e-11 Introduction to computer network

Computer network is a system connecting two or more computers. A computer network allows
user to exchange data quickly, access and share resources including equipments, application software,
and information.
Data communications systems are the electronic systems that transmit data over communications
lines from one location to another. You might use data communications through your microcomputer
to send information to a friend using another computer. You might work for an organization whose
computer system is spread throughout a building, or even throughout the country or world. That is, all
the parts—input and output units, processor, and storage devices—are in different places and linked
by communications. Or you might use telecommunications lines—telephone lines—to tap into
information located in an outside data bank. You could then transmit it to your microcomputer for
To attach to a network, a special-purpose hardware component is used to handle all the
transmission. The hardware is called a network adapter card or network interface card (NIC), it is
a printed circuit board plugged into a computer's bus, and a cable connects it to a network
medium.
Communications networks differ in geographical size. There are three important types:
LANs, MANs, and WANs.
Local Area Networks

Networks with computers and peripheral devices in close physical
proximity—within the same building, for instance—are called local area networks (LANs).
Linked by cable-telephone, coaxial, or fiber optic. LANs often use a bus form organization. In a
LAN, people can share different equipments, which lower the cost of equipments. LAN may be
linked to other LANs or to larger networks by using a network gateway. With the gateway, one
LAN may be connected to the LAN of another LAN of another office group. It may also be
connected to others in the wide world, even if their configurations are different. Alternatively, a
network bridge would be used to connect networks with the same configurations.
There is a newly development for LANs: WLAN. A wireless LAN (WLAN) is a flexible
data communication system implemented as an extension to, or as an alternative for, a wired
LAN within a building or campus. Using electromagnetic waves, WLANs transmit and receive
data over the air, minimizing the need for wired connections. Thus, WLANs combine data
connectivity with user mobility, and, through simplified configuration, enable movable LANs.
Over the recent several years, WLANs have gained strong popularity in a number of vertical
markets, including the health-care, retail, manufacturing, warehousing, and academic arenas.
[1]These industries have profited from the productivity gains of using hand-held terminals and
notebook computers to transmit real-time information to centralized hosts for processing. Today

WLANs are becoming more widely recognized as a general-purpose connectivity alternative for
Applications for Wireless LANs [2]Wireless LANs frequently augment rather than replace
wired LAN networks—often providing the final few meters of connectivity between a backbone
network and the mobile user. The following list describes some of the many applications made
possible through the power and flexibility of wireless LANs:
Doctors and nurses in hospitals are more productive because hand-held or notebook
computers with wireless LAN capability deliver patient information instantly.
Consulting or accounting audit engagement teams or small workgroups increase productivity
with quick network setup.
and changes with wireless LANs, thereby reducing the cost of LAN ownership.
Training sites at corporations and students at universities use wireless connectivity to
Network managers installing networked computers in older buildings find that wireless
LANs are a cost-effective network infrastructure solution.
Retail store owners use wireless networks to simply frequent network reconfiguration.
Trade show and branch office workers minimize setup requirements by installing preconfigured
wireless LANs needing no local MIS support.
Warehouse workers use wireless LANs to exchange information with central databases and
increase their productivity.
Network managers implement wireless LANs to provide backup for mission-critical
applications running on wired networks.
Senior executives in conference rooms make quicker decisions because they have real-time
information at their fingertips.
The increasingly mobile user also becomes a clear candidate for a wireless LAN. Portable
access to wireless networks can be achieved using laptop computers and wireless NICs. This
enables the user to travel to various locations–meeting rooms, hallways, lobbies, cafeterias,
classrooms, etc.–and still have access to their networked data. Without wireless access, the user
would have to carry clumsy cabling and find a network tap to plug into.
Metropolitan Area Networks

These networks are used as links between office buildings in
a city. Cellular phone systems expand the flexibility of MAN by allowing links to car phones and
portable phones.
Wide Area Networks

Wide area networks are countrywide and worldwide networks.
Among other kinds of channels, they use microwave relays and satellites to reach users over long
distances. One of the most widely used WANs is Internet, which allows users to connect to other
users and facilities worldwide.

Continue reading it-e-11 Introduction to computer network

## Pagination

Total views.

Powered by Hydejack v6.6.1


text:
# Fraction to decimal

Write the fraction 3/22 as a decimal.

Result

x =  0.13636

#### Solution:

$x=3/22=\dfrac{ 3 }{ 22 } \doteq 0.1364 \doteq 0.13636$

Our examples were largely sent or created by pupils and students themselves. Therefore, we would be pleased if you could send us any errors you found, spelling mistakes, or rephasing the example. Thank you!

Leave us a comment of this math problem and its solution (i.e. if it is still somewhat unclear...):

Be the first to comment!

Tips to related online calculators
Need help calculate sum, simplify or multiply fractions? Try our fraction calculator.

## Next similar math problems:

1. Fraction and a decimal
Write as a fraction and a decimal. One and two plus three and five hundredths
2. Mixed2improper
Write the mixed number as an improper fraction. 166 2/3
3. Zdeněk
Zdeněk picked up 15 l of water from a 100-liter full-water barrel. Write a fraction of what part of Zdeněk's water he picked.
4. Write 2
Write 791 thousandths as fraction in expanded form.
5. Withdrawal
If I withdrew 2/5 of my total savings and spent 7/10 of that amount. What fraction do I have in left in my savings?
6. Lengths of the pool
Miguel swam 6 lengths of the pool. Mat swam 3 times as far as Miguel. Lionel swam 1/3 as far as Miguel. How many lengths did mat swim?
7. In fractions
An ant climbs 2/5 of the pole on the first hour and climbs 1/4 of the pole on the next hour. What part of the pole does the ant climb in two hours?
8. Pizza 4
Marcus ate half pizza on monday night. He than ate one third of the remaining pizza on Tuesday. Which of the following expressions show how much pizza marcus ate in total?
9. Equation 20
In given equation: 8/9-4/5=2/9+x, find x
10. Scouts 4
4/7 of the students in a school are boys. If 3/8 of the boys are scouts, how many scouts are there in a school of 1878 students?
11. Hussein
Hussein owns 450000. He spent at the bookstore 2 over 9 to buy some books and tales. He paid 3 over 5 of his money to buy his math book. Then he paid his money to buy stories diagram ; a. Calculate the remaining amount of money with Hussein? b. Hussein
12. A baker
A baker has 5 1/4 pies in her shop. She cut the pies in pieces that are each 1/8 of a whole pie. How many pieces of pie does she have?
13. Pizza 5
You have 2/4 of a pizza and you want to share it equally between 2 people how much pizza does each person get?
14. Fractions 4
How many 2/3s are in 6?
15. Passenger boat
Two-fifths of the passengers in the passenger boat were boys. 1/3 of them were girls and the rest were adult. If there were 60 passengers in the boat, how many more boys than adult were there?
16. Pie II
Vili ate three pieces of pie. If it pieces is 1/8 how much pie did he eat?
17. Cakes
On the bowl were a few cakes. Jane ate one-third of them, Dana ate a quarter of those cakes that remained. a) What part (of the original number of cakes) Dana ate? b) At least how many cakes could be (initially) on thebowl?


text:
Fractal Related Discussion > Noob's Corner

(Question) Pascal Code for the Mandelbrot (math only)

(1/2) > >>

mash:
Hi everyone,
I am searching for a simple code to start drawing a mandelbrot set.
I was out of programming for several years and my last math-related work was in the eighties.
I want to join in into programming and start from scratch.
I have set up a program, that can paint on the screen, display math functions and the like. But I am struggling at getting a mandelbrot set displayed.
I have found two simple sources that didn't really work out.
I want to display it in general and then by varying one parameter zoom in or by varying another parameter and you can "move" left, right, up, down etc.
I can handle all the UI stuff, just looking for a starting point in maths.
Thank you
Pascal Code preferred, but I can read other code too

Sabine62:
Hello and welcome, Mash!

Found this for you on http://rosettacode.org/wiki/Mandelbrot_set#Pascal
Maybe a starting point for you to study?

Mind you, I have no Pascal interpreter here, so no guarantees ;)

--- Code: ---program mandelbrot;

{$IFDEF FPC} {$MODE DELPHI}
{$ENDIF} const ixmax = 800; iymax = 800; cxmin = -2.5; cxmax = 1.5; cymin = -2.0; cymax = 2.0; maxcolorcomponentvalue = 255; maxiteration = 200; escaperadius = 2; type colortype = record red : byte; green : byte; blue : byte; end; var ix, iy : integer; cx, cy : real; pixelwidth : real = (cxmax - cxmin) / ixmax; pixelheight : real = (cymax - cymin) / iymax; filename : string = 'new1.ppm'; comment : string = '# '; outfile : textfile; color : colortype; zx, zy : real; zx2, zy2 : real; iteration : integer; er2 : real = (escaperadius * escaperadius); begin {$I-}
assign(outfile, filename);
rewrite(outfile);
if ioresult <> 0 then
begin
{$IFDEF FPC} writeln(stderr, 'Unable to open output file: ', filename); {$ELSE}
writeln('ERROR: Unable to open output file: ', filename);
{\$ENDIF}
exit;
end;

writeln(outfile, 'P6');
writeln(outfile, ' ', comment);
writeln(outfile, ' ', ixmax);
writeln(outfile, ' ', iymax);
writeln(outfile, ' ', maxcolorcomponentvalue);

for iy := 1 to iymax do
begin
cy := cymin + (iy - 1)*pixelheight;
if abs(cy) < pixelheight / 2 then cy := 0.0;
for ix := 1 to ixmax do
begin
cx := cxmin + (ix - 1)*pixelwidth;
zx := 0.0;
zy := 0.0;
zx2 := zx*zx;
zy2 := zy*zy;
iteration := 0;
while (iteration < maxiteration) and (zx2 + zy2 < er2) do
begin
zy := 2*zx*zy + cy;
zx := zx2 - zy2 + cx;
zx2 := zx*zx;
zy2 := zy*zy;
iteration := iteration + 1;
end;
if iteration = maxiteration then
begin
color.red   := 0;
color.green := 0;
color.blue  := 0;
end
else
begin
color.red   := 255;
color.green := 255;
color.blue  := 255;
end;
write(outfile, chr(color.red), chr(color.green), chr(color.blue));
end;
end;

close(outfile);
end.
--- End code ---

Good luck and enjoy coding :)  :thumbs:

marcm200:
The smallest and simplest code to display a Mandelbrot (in ASCII) was posted by galac:
https://fractalforums.org/programming/11/small-mandelbrot-set-in-c/2658/msg13287#msg13287

The math part starts at the while loop, variables a,b denote the pixel's coordinates and If you change the print statement: " " e.g. to put a white pixel on the screen and "*" to a black pixel, then you have a good starting point.

gerson:
Welcome.
One big ressources of code  is GitHub.com.
Suggest you that read downloads topics, there are many programs discussion and you could take much ideas.

Sabine62:
@marcm200 I was looking for exactly that and couldn't find it!  :happy:
Great, thanks for sharing the link! :thumbs:


text:
# Step-by-step Solution

## Integrate $\int\log \left(8\right)x^5xdx$ with respect to x

Go!
1
2
3
4
5
6
7
8
9
0
x
y
(◻)
◻/◻
÷
2

e
π
ln
log
log
lim
d/dx
Dx
>
<
>=
<=
sin
cos
tan
cot
sec
csc

asin
acos
atan
acot
asec
acsc

sinh
cosh
tanh
coth
sech
csch

asinh
acosh
atanh
acoth
asech
acsch

### Videos

$0.129x^{7}+C_0$

## Step-by-step explanation

Problem to solve:

$\int\left(x^5log\left(8x\right)\right)dx$
1

Evaluating the logarithm of base $10$ of $8$

$\int\frac{3}{\sqrt{2}}x^5xdx$
2

When multiplying exponents with same base you can add the exponents

$\int\frac{3}{\sqrt{2}}x^{6}dx$

$0.129x^{7}+C_0$
$\int\left(x^5log\left(8x\right)\right)dx$

### Main topic:

Integral calculus

~ 0.02 seconds


text:
# First Results from the VIRIAL Survey: The Stellar Content of UVJ-selected Quiescent Galaxies at 1.5 lt z lt 2 from KMOS

J. Trevor Mendel, Roberto P. Saglia, Ralf Bender, Alessandra Beifiori, Jefferey Chan, Matteo Fossati, David J. Wilman, Kaushala Bandara, Gabriel B. Brammer, Natascha M. Förster Schreiber, Audrey Galametz, Sandesh Kulkarni, Ivelina G. Momcheva, Erica J. Nelson, Pieter G. van Dokkum, Katherine E. Whitaker, Stijn Wuyts

Research output: Contribution to journalArticlepeer-review

32 Citations (SciVal)

## Abstract

We investigate the stellar populations of 25 massive galaxies (${\rm log} [{{M}_{*}}/{{M}_{\odot }}]\geqslant 10.9$) at $1.5\lt z\lt 2$ using data obtained with the K-band Multi-Object Spectrograph (KMOS) on the ESO VLT. Targets were selected to be quiescent based on their broadband colors and redshifts using data from the 3D-HST grism survey. The mean redshift of our sample is $\bar{z}=1.75$, where KMOS YJ-band data probe age- and metallicity-sensitive absorption features in the rest-frame optical, including the G-band, Fe i, and high-order Balmer lines. Fitting simple stellar population models to a stack of our KMOS spectra, we derive a mean age of $1.03_{-0.08}^{+0.13}$ Gyr. We confirm previous results suggesting a correlation between color and age for quiescent galaxies, finding mean ages of $1.22_{-0.19}^{+0.56}$ Gyr and $0.85_{-0.05}^{+0.08}$ Gyr for the reddest and bluest galaxies in our sample. Combining our KMOS measurements with those obtained from previous studies at $0.2\lt z\lt 2$ we find evidence for a 2–3 Gyr spread in the formation epoch of massive galaxies. At $z\lt 1$ the measured stellar ages are consistent with passive evolution, while at $1\lt z\lesssim 2$ they appear to saturate at ~1 Gyr, which likely reflects changing demographics of the (mean) progenitor population. By comparing to star formation histories inferred for "normal" star-forming galaxies, we show that the timescales required to form massive galaxies at $z\gtrsim 1.5$ are consistent with the enhanced α-element abundances found in massive local early-type galaxies.
Original language English L4 The Astrophysical Journal Letters 804 1 23 Apr 2015 https://doi.org/10.1088/2041-8205/804/1/L4 Published - 1 May 2015

## Keywords

• galaxies: evolution
• galaxies: formation
• galaxies: high-redshift

## Fingerprint

Dive into the research topics of 'First Results from the VIRIAL Survey: The Stellar Content of UVJ-selected Quiescent Galaxies at 1.5 lt z lt 2 from KMOS'. Together they form a unique fingerprint.